blob: 35936b55830601a7885f60e08eb0b67ad31cddb5 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreau109201f2020-03-04 10:31:58 +010013#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreaubb869862020-04-16 10:52:41 +020019#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
20#include <sys/auxv.h>
21#endif
22
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010023#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020024#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020025#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020026#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020027#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020028#include <stdlib.h>
29#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010032#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020033#include <sys/stat.h>
34#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010035#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020036#include <netinet/in.h>
37#include <arpa/inet.h>
38
Willy Tarreau48fbcae2020-06-03 18:09:46 +020039#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020040#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020041
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020042#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020043#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020044#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020045#include <haproxy/dns.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020046#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020047#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020048#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020049#include <haproxy/namespace.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020050#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020051#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020052#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020053#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010054
Thierry Fournier93127942016-01-20 18:49:45 +010055/* This macro returns false if the test __x is false. Many
56 * of the following parsing function must be abort the processing
57 * if it returns 0, so this macro is useful for writing light code.
58 */
59#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
60
Willy Tarreau56adcf22012-12-23 18:00:29 +010061/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020062 * 2^64-1 = 18446744073709551615 or
63 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020064 *
65 * The HTML version needs room for adding the 25 characters
66 * '<span class="rls"></span>' around digits at positions 3N+1 in order
67 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020068 */
Christopher Faulet99bca652017-11-14 16:47:26 +010069THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
70THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020071
Willy Tarreau588297f2014-06-16 15:16:40 +020072/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
73 * to quote strings larger than a max configuration line.
74 */
Christopher Faulet99bca652017-11-14 16:47:26 +010075THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
76THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020077
Willy Tarreaubaaee002006-06-26 02:48:02 +020078/*
William Lallemande7340ec2012-01-24 11:15:39 +010079 * unsigned long long ASCII representation
80 *
81 * return the last char '\0' or NULL if no enough
82 * space in dst
83 */
84char *ulltoa(unsigned long long n, char *dst, size_t size)
85{
86 int i = 0;
87 char *res;
88
89 switch(n) {
90 case 1ULL ... 9ULL:
91 i = 0;
92 break;
93
94 case 10ULL ... 99ULL:
95 i = 1;
96 break;
97
98 case 100ULL ... 999ULL:
99 i = 2;
100 break;
101
102 case 1000ULL ... 9999ULL:
103 i = 3;
104 break;
105
106 case 10000ULL ... 99999ULL:
107 i = 4;
108 break;
109
110 case 100000ULL ... 999999ULL:
111 i = 5;
112 break;
113
114 case 1000000ULL ... 9999999ULL:
115 i = 6;
116 break;
117
118 case 10000000ULL ... 99999999ULL:
119 i = 7;
120 break;
121
122 case 100000000ULL ... 999999999ULL:
123 i = 8;
124 break;
125
126 case 1000000000ULL ... 9999999999ULL:
127 i = 9;
128 break;
129
130 case 10000000000ULL ... 99999999999ULL:
131 i = 10;
132 break;
133
134 case 100000000000ULL ... 999999999999ULL:
135 i = 11;
136 break;
137
138 case 1000000000000ULL ... 9999999999999ULL:
139 i = 12;
140 break;
141
142 case 10000000000000ULL ... 99999999999999ULL:
143 i = 13;
144 break;
145
146 case 100000000000000ULL ... 999999999999999ULL:
147 i = 14;
148 break;
149
150 case 1000000000000000ULL ... 9999999999999999ULL:
151 i = 15;
152 break;
153
154 case 10000000000000000ULL ... 99999999999999999ULL:
155 i = 16;
156 break;
157
158 case 100000000000000000ULL ... 999999999999999999ULL:
159 i = 17;
160 break;
161
162 case 1000000000000000000ULL ... 9999999999999999999ULL:
163 i = 18;
164 break;
165
166 case 10000000000000000000ULL ... ULLONG_MAX:
167 i = 19;
168 break;
169 }
170 if (i + 2 > size) // (i + 1) + '\0'
171 return NULL; // too long
172 res = dst + i + 1;
173 *res = '\0';
174 for (; i >= 0; i--) {
175 dst[i] = n % 10ULL + '0';
176 n /= 10ULL;
177 }
178 return res;
179}
180
181/*
182 * unsigned long ASCII representation
183 *
184 * return the last char '\0' or NULL if no enough
185 * space in dst
186 */
187char *ultoa_o(unsigned long n, char *dst, size_t size)
188{
189 int i = 0;
190 char *res;
191
192 switch (n) {
193 case 0U ... 9UL:
194 i = 0;
195 break;
196
197 case 10U ... 99UL:
198 i = 1;
199 break;
200
201 case 100U ... 999UL:
202 i = 2;
203 break;
204
205 case 1000U ... 9999UL:
206 i = 3;
207 break;
208
209 case 10000U ... 99999UL:
210 i = 4;
211 break;
212
213 case 100000U ... 999999UL:
214 i = 5;
215 break;
216
217 case 1000000U ... 9999999UL:
218 i = 6;
219 break;
220
221 case 10000000U ... 99999999UL:
222 i = 7;
223 break;
224
225 case 100000000U ... 999999999UL:
226 i = 8;
227 break;
228#if __WORDSIZE == 32
229
230 case 1000000000ULL ... ULONG_MAX:
231 i = 9;
232 break;
233
234#elif __WORDSIZE == 64
235
236 case 1000000000ULL ... 9999999999UL:
237 i = 9;
238 break;
239
240 case 10000000000ULL ... 99999999999UL:
241 i = 10;
242 break;
243
244 case 100000000000ULL ... 999999999999UL:
245 i = 11;
246 break;
247
248 case 1000000000000ULL ... 9999999999999UL:
249 i = 12;
250 break;
251
252 case 10000000000000ULL ... 99999999999999UL:
253 i = 13;
254 break;
255
256 case 100000000000000ULL ... 999999999999999UL:
257 i = 14;
258 break;
259
260 case 1000000000000000ULL ... 9999999999999999UL:
261 i = 15;
262 break;
263
264 case 10000000000000000ULL ... 99999999999999999UL:
265 i = 16;
266 break;
267
268 case 100000000000000000ULL ... 999999999999999999UL:
269 i = 17;
270 break;
271
272 case 1000000000000000000ULL ... 9999999999999999999UL:
273 i = 18;
274 break;
275
276 case 10000000000000000000ULL ... ULONG_MAX:
277 i = 19;
278 break;
279
280#endif
281 }
282 if (i + 2 > size) // (i + 1) + '\0'
283 return NULL; // too long
284 res = dst + i + 1;
285 *res = '\0';
286 for (; i >= 0; i--) {
287 dst[i] = n % 10U + '0';
288 n /= 10U;
289 }
290 return res;
291}
292
293/*
294 * signed long ASCII representation
295 *
296 * return the last char '\0' or NULL if no enough
297 * space in dst
298 */
299char *ltoa_o(long int n, char *dst, size_t size)
300{
301 char *pos = dst;
302
303 if (n < 0) {
304 if (size < 3)
305 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
306 *pos = '-';
307 pos++;
308 dst = ultoa_o(-n, pos, size - 1);
309 } else {
310 dst = ultoa_o(n, dst, size);
311 }
312 return dst;
313}
314
315/*
316 * signed long long ASCII representation
317 *
318 * return the last char '\0' or NULL if no enough
319 * space in dst
320 */
321char *lltoa(long long n, char *dst, size_t size)
322{
323 char *pos = dst;
324
325 if (n < 0) {
326 if (size < 3)
327 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
328 *pos = '-';
329 pos++;
330 dst = ulltoa(-n, pos, size - 1);
331 } else {
332 dst = ulltoa(n, dst, size);
333 }
334 return dst;
335}
336
337/*
338 * write a ascii representation of a unsigned into dst,
339 * return a pointer to the last character
340 * Pad the ascii representation with '0', using size.
341 */
342char *utoa_pad(unsigned int n, char *dst, size_t size)
343{
344 int i = 0;
345 char *ret;
346
347 switch(n) {
348 case 0U ... 9U:
349 i = 0;
350 break;
351
352 case 10U ... 99U:
353 i = 1;
354 break;
355
356 case 100U ... 999U:
357 i = 2;
358 break;
359
360 case 1000U ... 9999U:
361 i = 3;
362 break;
363
364 case 10000U ... 99999U:
365 i = 4;
366 break;
367
368 case 100000U ... 999999U:
369 i = 5;
370 break;
371
372 case 1000000U ... 9999999U:
373 i = 6;
374 break;
375
376 case 10000000U ... 99999999U:
377 i = 7;
378 break;
379
380 case 100000000U ... 999999999U:
381 i = 8;
382 break;
383
384 case 1000000000U ... 4294967295U:
385 i = 9;
386 break;
387 }
388 if (i + 2 > size) // (i + 1) + '\0'
389 return NULL; // too long
390 if (i < size)
391 i = size - 2; // padding - '\0'
392
393 ret = dst + i + 1;
394 *ret = '\0';
395 for (; i >= 0; i--) {
396 dst[i] = n % 10U + '0';
397 n /= 10U;
398 }
399 return ret;
400}
401
402/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200403 * copies at most <size-1> chars from <src> to <dst>. Last char is always
404 * set to 0, unless <size> is 0. The number of chars copied is returned
405 * (excluding the terminating zero).
406 * This code has been optimized for size and speed : on x86, it's 45 bytes
407 * long, uses only registers, and consumes only 4 cycles per char.
408 */
409int strlcpy2(char *dst, const char *src, int size)
410{
411 char *orig = dst;
412 if (size) {
413 while (--size && (*dst = *src)) {
414 src++; dst++;
415 }
416 *dst = 0;
417 }
418 return dst - orig;
419}
420
421/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200422 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200423 * the ascii representation for number 'n' in decimal.
424 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100425char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200426{
427 char *pos;
428
Willy Tarreau72d759c2007-10-25 12:14:10 +0200429 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200430 *pos-- = '\0';
431
432 do {
433 *pos-- = '0' + n % 10;
434 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200435 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200436 return pos + 1;
437}
438
Willy Tarreau91092e52007-10-25 16:58:42 +0200439/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200440 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200441 * the ascii representation for number 'n' in decimal.
442 */
443char *lltoa_r(long long int in, char *buffer, int size)
444{
445 char *pos;
446 int neg = 0;
447 unsigned long long int n;
448
449 pos = buffer + size - 1;
450 *pos-- = '\0';
451
452 if (in < 0) {
453 neg = 1;
454 n = -in;
455 }
456 else
457 n = in;
458
459 do {
460 *pos-- = '0' + n % 10;
461 n /= 10;
462 } while (n && pos >= buffer);
463 if (neg && pos > buffer)
464 *pos-- = '-';
465 return pos + 1;
466}
467
468/*
469 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200470 * the ascii representation for signed number 'n' in decimal.
471 */
472char *sltoa_r(long n, char *buffer, int size)
473{
474 char *pos;
475
476 if (n >= 0)
477 return ultoa_r(n, buffer, size);
478
479 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
480 *pos = '-';
481 return pos;
482}
483
484/*
485 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200486 * the ascii representation for number 'n' in decimal, formatted for
487 * HTML output with tags to create visual grouping by 3 digits. The
488 * output needs to support at least 171 characters.
489 */
490const char *ulltoh_r(unsigned long long n, char *buffer, int size)
491{
492 char *start;
493 int digit = 0;
494
495 start = buffer + size;
496 *--start = '\0';
497
498 do {
499 if (digit == 3 && start >= buffer + 7)
500 memcpy(start -= 7, "</span>", 7);
501
502 if (start >= buffer + 1) {
503 *--start = '0' + n % 10;
504 n /= 10;
505 }
506
507 if (digit == 3 && start >= buffer + 18)
508 memcpy(start -= 18, "<span class=\"rls\">", 18);
509
510 if (digit++ == 3)
511 digit = 1;
512 } while (n && start > buffer);
513 return start;
514}
515
516/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200517 * This function simply returns a locally allocated string containing the ascii
518 * representation for number 'n' in decimal, unless n is 0 in which case it
519 * returns the alternate string (or an empty string if the alternate string is
520 * NULL). It use is intended for limits reported in reports, where it's
521 * desirable not to display anything if there is no limit. Warning! it shares
522 * the same vector as ultoa_r().
523 */
524const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
525{
526 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
527}
528
Willy Tarreau588297f2014-06-16 15:16:40 +0200529/* returns a locally allocated string containing the quoted encoding of the
530 * input string. The output may be truncated to QSTR_SIZE chars, but it is
531 * guaranteed that the string will always be properly terminated. Quotes are
532 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
533 * always be at least 4 chars.
534 */
535const char *qstr(const char *str)
536{
537 char *ret = quoted_str[quoted_idx];
538 char *p, *end;
539
540 if (++quoted_idx >= NB_QSTR)
541 quoted_idx = 0;
542
543 p = ret;
544 end = ret + QSTR_SIZE;
545
546 *p++ = '"';
547
548 /* always keep 3 chars to support passing "" and the ending " */
549 while (*str && p < end - 3) {
550 if (*str == '"') {
551 *p++ = '"';
552 *p++ = '"';
553 }
554 else
555 *p++ = *str;
556 str++;
557 }
558 *p++ = '"';
559 return ret;
560}
561
Robert Tsai81ae1952007-12-05 10:47:29 +0100562/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200563 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
564 *
565 * It looks like this one would be a good candidate for inlining, but this is
566 * not interesting because it around 35 bytes long and often called multiple
567 * times within the same function.
568 */
569int ishex(char s)
570{
571 s -= '0';
572 if ((unsigned char)s <= 9)
573 return 1;
574 s -= 'A' - '0';
575 if ((unsigned char)s <= 5)
576 return 1;
577 s -= 'a' - 'A';
578 if ((unsigned char)s <= 5)
579 return 1;
580 return 0;
581}
582
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100583/* rounds <i> down to the closest value having max 2 digits */
584unsigned int round_2dig(unsigned int i)
585{
586 unsigned int mul = 1;
587
588 while (i >= 100) {
589 i /= 10;
590 mul *= 10;
591 }
592 return i * mul;
593}
594
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100595/*
596 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
597 * invalid character is found, a pointer to it is returned. If everything is
598 * fine, NULL is returned.
599 */
600const char *invalid_char(const char *name)
601{
602 if (!*name)
603 return name;
604
605 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100606 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100607 *name != '_' && *name != '-')
608 return name;
609 name++;
610 }
611 return NULL;
612}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200613
614/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200615 * Checks <name> for invalid characters. Valid chars are [_.-] and those
616 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200617 * If an invalid character is found, a pointer to it is returned.
618 * If everything is fine, NULL is returned.
619 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200620static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200621
622 if (!*name)
623 return name;
624
625 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100626 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200627 *name != '_' && *name != '-')
628 return name;
629
630 name++;
631 }
632
633 return NULL;
634}
635
636/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200637 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
638 * If an invalid character is found, a pointer to it is returned.
639 * If everything is fine, NULL is returned.
640 */
641const char *invalid_domainchar(const char *name) {
642 return __invalid_char(name, isalnum);
643}
644
645/*
646 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
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_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200651 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200652}
653
654/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100655 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100656 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
657 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
658 * the function tries to guess the address family from the syntax. If the
659 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100660 * string is assumed to contain only an address, no port. The address can be a
661 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
662 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
663 * The return address will only have the address family and the address set,
664 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100665 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
666 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100667 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200668 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100669struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200670{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100671 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100672 /* max IPv6 length, including brackets and terminating NULL */
673 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100674 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100675
676 /* check IPv6 with square brackets */
677 if (str[0] == '[') {
678 size_t iplength = strlen(str);
679
680 if (iplength < 4) {
681 /* minimal size is 4 when using brackets "[::]" */
682 goto fail;
683 }
684 else if (iplength >= sizeof(tmpip)) {
685 /* IPv6 literal can not be larger than tmpip */
686 goto fail;
687 }
688 else {
689 if (str[iplength - 1] != ']') {
690 /* if address started with bracket, it should end with bracket */
691 goto fail;
692 }
693 else {
694 memcpy(tmpip, str + 1, iplength - 2);
695 tmpip[iplength - 2] = '\0';
696 str = tmpip;
697 }
698 }
699 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100700
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701 /* Any IPv6 address */
702 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100703 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
704 sa->ss_family = AF_INET6;
705 else if (sa->ss_family != AF_INET6)
706 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100707 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100708 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709 }
710
Willy Tarreau24709282013-03-10 21:32:12 +0100711 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100712 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100713 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
714 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100715 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100716 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100717 }
718
719 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100720 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
721 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100722 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100723 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100724 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100725 }
726
727 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100728 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
729 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100730 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100731 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100732 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100733 }
734
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100735 if (!resolve)
736 return NULL;
737
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200738 if (!dns_hostname_validation(str, NULL))
739 return NULL;
740
David du Colombierd5f43282011-03-17 10:40:16 +0100741#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200742 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100743 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100744 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100745
746 memset(&result, 0, sizeof(result));
747 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100748 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100749 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200750 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100751 hints.ai_protocol = 0;
752
753 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100754 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
755 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100756 else if (sa->ss_family != result->ai_family) {
757 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100758 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100759 }
Willy Tarreau24709282013-03-10 21:32:12 +0100760
David du Colombierd5f43282011-03-17 10:40:16 +0100761 switch (result->ai_family) {
762 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100763 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100764 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100765 success = 1;
766 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100767 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100768 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100769 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100770 success = 1;
771 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100772 }
773 }
774
Sean Carey58ea0392013-02-15 23:39:18 +0100775 if (result)
776 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100777
778 if (success)
779 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100780 }
David du Colombierd5f43282011-03-17 10:40:16 +0100781#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200782 /* try to resolve an IPv4/IPv6 hostname */
783 he = gethostbyname(str);
784 if (he) {
785 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
786 sa->ss_family = he->h_addrtype;
787 else if (sa->ss_family != he->h_addrtype)
788 goto fail;
789
790 switch (sa->ss_family) {
791 case AF_INET:
792 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100793 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200794 return sa;
795 case AF_INET6:
796 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100797 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200798 return sa;
799 }
800 }
801
David du Colombierd5f43282011-03-17 10:40:16 +0100802 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100803 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100804 return NULL;
805}
806
807/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100808 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
809 * range or offset consisting in two integers that the caller will have to
810 * check to find the relevant input format. The following format are supported :
811 *
812 * String format | address | port | low | high
813 * addr | <addr> | 0 | 0 | 0
814 * addr: | <addr> | 0 | 0 | 0
815 * addr:port | <addr> | <port> | <port> | <port>
816 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
817 * addr:+port | <addr> | <port> | 0 | <port>
818 * addr:-port | <addr> |-<port> | <port> | 0
819 *
820 * The detection of a port range or increment by the caller is made by
821 * comparing <low> and <high>. If both are equal, then port 0 means no port
822 * was specified. The caller may pass NULL for <low> and <high> if it is not
823 * interested in retrieving port ranges.
824 *
825 * Note that <addr> above may also be :
826 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
827 * - "*" => family will be AF_INET and address will be INADDR_ANY
828 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
829 * - a host name => family and address will depend on host name resolving.
830 *
Willy Tarreau24709282013-03-10 21:32:12 +0100831 * A prefix may be passed in before the address above to force the family :
832 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
833 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
834 * - "unix@" => force address to be a path to a UNIX socket even if the
835 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200836 * - 'abns@' -> force address to belong to the abstract namespace (Linux
837 * only). These sockets are just like Unix sockets but without
838 * the need for an underlying file system. The address is a
839 * string. Technically it's like a Unix socket with a zero in
840 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100841 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100842 *
mildisff5d5102015-10-26 18:50:08 +0100843 * IPv6 addresses can be declared with or without square brackets. When using
844 * square brackets for IPv6 addresses, the port separator (colon) is optional.
845 * If not using square brackets, and in order to avoid any ambiguity with
846 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
847 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
848 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100849 *
850 * If <pfx> is non-null, it is used as a string prefix before any path-based
851 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100852 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200853 * if <fqdn> is non-null, it will be filled with :
854 * - a pointer to the FQDN of the server name to resolve if there's one, and
855 * that the caller will have to free(),
856 * - NULL if there was an explicit address that doesn't require resolution.
857 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100858 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
859 * is null, <fqdn> is still honnored so it is possible for the caller to know
860 * whether a resolution failed by setting <resolve> to null and checking if
861 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200862 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100863 * When a file descriptor is passed, its value is put into the s_addr part of
864 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100865 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100866struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100867{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100868 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100869 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100870 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100871 char *port1, *port2;
872 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200873 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100874
875 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200876 if (fqdn)
877 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200878
Willy Tarreaudad36a32013-03-11 01:20:04 +0100879 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100880 if (str2 == NULL) {
881 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100882 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100883 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884
Willy Tarreau9f69f462015-09-08 16:01:25 +0200885 if (!*str2) {
886 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
887 goto out;
888 }
889
Willy Tarreau24709282013-03-10 21:32:12 +0100890 memset(&ss, 0, sizeof(ss));
891
892 if (strncmp(str2, "unix@", 5) == 0) {
893 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200894 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100895 ss.ss_family = AF_UNIX;
896 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200897 else if (strncmp(str2, "abns@", 5) == 0) {
898 str2 += 5;
899 abstract = 1;
900 ss.ss_family = AF_UNIX;
901 }
Willy Tarreau24709282013-03-10 21:32:12 +0100902 else if (strncmp(str2, "ipv4@", 5) == 0) {
903 str2 += 5;
904 ss.ss_family = AF_INET;
905 }
906 else if (strncmp(str2, "ipv6@", 5) == 0) {
907 str2 += 5;
908 ss.ss_family = AF_INET6;
909 }
910 else if (*str2 == '/') {
911 ss.ss_family = AF_UNIX;
912 }
913 else
914 ss.ss_family = AF_UNSPEC;
915
William Lallemand2fe7dd02018-09-11 16:51:29 +0200916 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
917 char *endptr;
918
919 str2 += 9;
920
921 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100922 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200923
924 if (!*str2 || *endptr) {
925 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
926 goto out;
927 }
928
929 ss.ss_family = AF_CUST_SOCKPAIR;
930
931 }
932 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100933 char *endptr;
934
935 str2 += 3;
936 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100937 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100938
939 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100940 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100941 goto out;
942 }
943
944 /* we return AF_UNSPEC if we use a file descriptor number */
945 ss.ss_family = AF_UNSPEC;
946 }
947 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200948 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100949 int prefix_path_len;
950 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200951 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100952
953 /* complete unix socket path name during startup or soft-restart is
954 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
955 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200956 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200957 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +0100958 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100959
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200960 adr_len = strlen(str2);
961 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100962 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
963 goto out;
964 }
965
Willy Tarreauccfccef2014-05-10 01:49:15 +0200966 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200967 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200968 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200969 memcpy(un->sun_path, pfx, prefix_path_len);
970 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100971 }
Willy Tarreau24709282013-03-10 21:32:12 +0100972 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100973 char *end = str2 + strlen(str2);
974 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200975
mildisff5d5102015-10-26 18:50:08 +0100976 /* search for : or ] whatever comes first */
977 for (chr = end-1; chr > str2; chr--) {
978 if (*chr == ']' || *chr == ':')
979 break;
980 }
981
982 if (*chr == ':') {
983 /* Found a colon before a closing-bracket, must be a port separator.
984 * This guarantee backward compatibility.
985 */
986 *chr++ = '\0';
987 port1 = chr;
988 }
989 else {
990 /* Either no colon and no closing-bracket
991 * or directly ending with a closing-bracket.
992 * However, no port.
993 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100994 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100995 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200996
Willy Tarreau90807112020-02-25 08:16:33 +0100997 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100998 port2 = strchr(port1, '-');
999 if (port2)
1000 *port2++ = '\0';
1001 else
1002 port2 = port1;
1003 portl = atoi(port1);
1004 porth = atoi(port2);
1005 porta = portl;
1006 }
1007 else if (*port1 == '-') { /* negative offset */
1008 portl = atoi(port1 + 1);
1009 porta = -portl;
1010 }
1011 else if (*port1 == '+') { /* positive offset */
1012 porth = atoi(port1 + 1);
1013 porta = porth;
1014 }
1015 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001016 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001017 goto out;
1018 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001019
1020 /* first try to parse the IP without resolving. If it fails, it
1021 * tells us we need to keep a copy of the FQDN to resolve later
1022 * and to enable DNS. In this case we can proceed if <fqdn> is
1023 * set or if resolve is set, otherwise it's an error.
1024 */
1025 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001026 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001027 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1028 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1029 goto out;
1030 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001031
Willy Tarreauceccdd72016-11-02 22:27:10 +01001032 if (fqdn) {
1033 if (str2 != back)
1034 memmove(back, str2, strlen(str2) + 1);
1035 *fqdn = back;
1036 back = NULL;
1037 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001038 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001039 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001040 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001041
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001042 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001043 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001044 if (port)
1045 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001046 if (low)
1047 *low = portl;
1048 if (high)
1049 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001050 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001051 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001052}
1053
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001054/* converts <str> to a struct in_addr containing a network mask. It can be
1055 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001056 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001057 */
1058int str2mask(const char *str, struct in_addr *mask)
1059{
1060 if (strchr(str, '.') != NULL) { /* dotted notation */
1061 if (!inet_pton(AF_INET, str, mask))
1062 return 0;
1063 }
1064 else { /* mask length */
1065 char *err;
1066 unsigned long len = strtol(str, &err, 10);
1067
1068 if (!*str || (err && *err) || (unsigned)len > 32)
1069 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001070
1071 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001072 }
1073 return 1;
1074}
1075
Tim Duesterhus47185172018-01-25 16:24:49 +01001076/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001077 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001078 * if the conversion succeeds otherwise zero.
1079 */
1080int str2mask6(const char *str, struct in6_addr *mask)
1081{
1082 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1083 if (!inet_pton(AF_INET6, str, mask))
1084 return 0;
1085 }
1086 else { /* mask length */
1087 char *err;
1088 unsigned long len = strtol(str, &err, 10);
1089
1090 if (!*str || (err && *err) || (unsigned)len > 128)
1091 return 0;
1092
1093 len2mask6(len, mask);
1094 }
1095 return 1;
1096}
1097
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001098/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1099 * succeeds otherwise zero.
1100 */
1101int cidr2dotted(int cidr, struct in_addr *mask) {
1102
1103 if (cidr < 0 || cidr > 32)
1104 return 0;
1105
1106 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1107 return 1;
1108}
1109
Thierry Fournier70473a52016-02-17 17:12:14 +01001110/* Convert mask from bit length form to in_addr form.
1111 * This function never fails.
1112 */
1113void len2mask4(int len, struct in_addr *addr)
1114{
1115 if (len >= 32) {
1116 addr->s_addr = 0xffffffff;
1117 return;
1118 }
1119 if (len <= 0) {
1120 addr->s_addr = 0x00000000;
1121 return;
1122 }
1123 addr->s_addr = 0xffffffff << (32 - len);
1124 addr->s_addr = htonl(addr->s_addr);
1125}
1126
1127/* Convert mask from bit length form to in6_addr form.
1128 * This function never fails.
1129 */
1130void len2mask6(int len, struct in6_addr *addr)
1131{
1132 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1133 len -= 32;
1134 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1135 len -= 32;
1136 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1137 len -= 32;
1138 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1139}
1140
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001141/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001142 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001143 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001144 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001145 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1146 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001147int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001148{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001149 __label__ out_free, out_err;
1150 char *c, *s;
1151 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001152
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001153 s = strdup(str);
1154 if (!s)
1155 return 0;
1156
Willy Tarreaubaaee002006-06-26 02:48:02 +02001157 memset(mask, 0, sizeof(*mask));
1158 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001159
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001160 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001161 *c++ = '\0';
1162 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001163 if (!str2mask(c, mask))
1164 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001165 }
1166 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001167 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001168 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001169 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001170 struct hostent *he;
1171
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001172 if (!resolve)
1173 goto out_err;
1174
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001175 if ((he = gethostbyname(s)) == NULL) {
1176 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001177 }
1178 else
1179 *addr = *(struct in_addr *) *(he->h_addr_list);
1180 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001181
1182 ret_val = 1;
1183 out_free:
1184 free(s);
1185 return ret_val;
1186 out_err:
1187 ret_val = 0;
1188 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001189}
1190
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001191
1192/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001193 * converts <str> to two struct in6_addr* which must be pre-allocated.
1194 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001195 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001196 * Returns 1 if OK, 0 if error.
1197 */
1198int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1199{
1200 char *c, *s;
1201 int ret_val = 0;
1202 char *err;
1203 unsigned long len = 128;
1204
1205 s = strdup(str);
1206 if (!s)
1207 return 0;
1208
1209 memset(mask, 0, sizeof(*mask));
1210 memset(addr, 0, sizeof(*addr));
1211
1212 if ((c = strrchr(s, '/')) != NULL) {
1213 *c++ = '\0'; /* c points to the mask */
1214 if (!*c)
1215 goto out_free;
1216
1217 len = strtoul(c, &err, 10);
1218 if ((err && *err) || (unsigned)len > 128)
1219 goto out_free;
1220 }
1221 *mask = len; /* OK we have a valid mask in <len> */
1222
1223 if (!inet_pton(AF_INET6, s, addr))
1224 goto out_free;
1225
1226 ret_val = 1;
1227 out_free:
1228 free(s);
1229 return ret_val;
1230}
1231
1232
1233/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001234 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001235 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001236int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001237{
1238 int saw_digit, octets, ch;
1239 u_char tmp[4], *tp;
1240 const char *cp = addr;
1241
1242 saw_digit = 0;
1243 octets = 0;
1244 *(tp = tmp) = 0;
1245
1246 while (*addr) {
1247 unsigned char digit = (ch = *addr++) - '0';
1248 if (digit > 9 && ch != '.')
1249 break;
1250 if (digit <= 9) {
1251 u_int new = *tp * 10 + digit;
1252 if (new > 255)
1253 return 0;
1254 *tp = new;
1255 if (!saw_digit) {
1256 if (++octets > 4)
1257 return 0;
1258 saw_digit = 1;
1259 }
1260 } else if (ch == '.' && saw_digit) {
1261 if (octets == 4)
1262 return 0;
1263 *++tp = 0;
1264 saw_digit = 0;
1265 } else
1266 return 0;
1267 }
1268
1269 if (octets < 4)
1270 return 0;
1271
1272 memcpy(&dst->s_addr, tmp, 4);
1273 return addr-cp-1;
1274}
1275
1276/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001277 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001278 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001279 * the hostname. Actually only http and https are supported. <out> can be NULL.
1280 * This function returns the consumed length. It is useful if you parse complete
1281 * url like http://host:port/path, because the consumed length corresponds to
1282 * the first character of the path. If the conversion fails, it returns -1.
1283 *
1284 * This function tries to resolve the DNS name if haproxy is in starting mode.
1285 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001286 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001287int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001288{
1289 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001290 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001291 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001292 unsigned long long int http_code = 0;
1293 int default_port;
1294 struct hostent *he;
1295 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001296
1297 /* Firstly, try to find :// pattern */
1298 while (curr < url+ulen && url_code != 0x3a2f2f) {
1299 url_code = ((url_code & 0xffff) << 8);
1300 url_code += (unsigned char)*curr++;
1301 }
1302
1303 /* Secondly, if :// pattern is found, verify parsed stuff
1304 * before pattern is matching our http pattern.
1305 * If so parse ip address and port in uri.
1306 *
1307 * WARNING: Current code doesn't support dynamic async dns resolver.
1308 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001309 if (url_code != 0x3a2f2f)
1310 return -1;
1311
1312 /* Copy scheme, and utrn to lower case. */
1313 while (cp < curr - 3)
1314 http_code = (http_code << 8) + *cp++;
1315 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001316
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001317 /* HTTP or HTTPS url matching */
1318 if (http_code == 0x2020202068747470ULL) {
1319 default_port = 80;
1320 if (out)
1321 out->scheme = SCH_HTTP;
1322 }
1323 else if (http_code == 0x2020206874747073ULL) {
1324 default_port = 443;
1325 if (out)
1326 out->scheme = SCH_HTTPS;
1327 }
1328 else
1329 return -1;
1330
1331 /* If the next char is '[', the host address is IPv6. */
1332 if (*curr == '[') {
1333 curr++;
1334
1335 /* Check trash size */
1336 if (trash.size < ulen)
1337 return -1;
1338
1339 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001340 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001341 for (end = curr;
1342 end < url + ulen && *end != ']';
1343 end++, p++)
1344 *p = *end;
1345 if (*end != ']')
1346 return -1;
1347 *p = '\0';
1348
1349 /* Update out. */
1350 if (out) {
1351 out->host = curr;
1352 out->host_len = end - curr;
1353 }
1354
1355 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001356 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001357 return -1;
1358 end++;
1359
1360 /* Decode port. */
1361 if (*end == ':') {
1362 end++;
1363 default_port = read_uint(&end, url + ulen);
1364 }
1365 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1366 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1367 return end - url;
1368 }
1369 else {
1370 /* We are looking for IP address. If you want to parse and
1371 * resolve hostname found in url, you can use str2sa_range(), but
1372 * be warned this can slow down global daemon performances
1373 * while handling lagging dns responses.
1374 */
1375 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1376 if (ret) {
1377 /* Update out. */
1378 if (out) {
1379 out->host = curr;
1380 out->host_len = ret;
1381 }
1382
1383 curr += ret;
1384
1385 /* Decode port. */
1386 if (*curr == ':') {
1387 curr++;
1388 default_port = read_uint(&curr, url + ulen);
1389 }
1390 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1391
1392 /* Set family. */
1393 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1394 return curr - url;
1395 }
1396 else if (global.mode & MODE_STARTING) {
1397 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1398 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001399 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001400
1401 /* look for : or / or end */
1402 for (end = curr;
1403 end < url + ulen && *end != '/' && *end != ':';
1404 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001405 memcpy(trash.area, curr, end - curr);
1406 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001407
1408 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001409 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001410 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001411 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001412
1413 /* Update out. */
1414 if (out) {
1415 out->host = curr;
1416 out->host_len = end - curr;
1417 }
1418
1419 /* Decode port. */
1420 if (*end == ':') {
1421 end++;
1422 default_port = read_uint(&end, url + ulen);
1423 }
1424
1425 /* Copy IP address, set port and family. */
1426 switch (he->h_addrtype) {
1427 case AF_INET:
1428 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1429 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1430 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1431 return end - url;
1432
1433 case AF_INET6:
1434 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1435 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1436 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1437 return end - url;
1438 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001439 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001440 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001441 return -1;
1442}
1443
Willy Tarreau631f01c2011-09-05 00:36:48 +02001444/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1445 * address family is returned so that it's easy for the caller to adapt to the
1446 * output format. Zero is returned if the address family is not supported. -1
1447 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1448 * supported.
1449 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001450int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001451{
1452
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001453 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001454
1455 if (size < 5)
1456 return 0;
1457 *str = '\0';
1458
1459 switch (addr->ss_family) {
1460 case AF_INET:
1461 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1462 break;
1463 case AF_INET6:
1464 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1465 break;
1466 case AF_UNIX:
1467 memcpy(str, "unix", 5);
1468 return addr->ss_family;
1469 default:
1470 return 0;
1471 }
1472
1473 if (inet_ntop(addr->ss_family, ptr, str, size))
1474 return addr->ss_family;
1475
1476 /* failed */
1477 return -1;
1478}
1479
Simon Horman75ab8bd2014-06-16 09:39:41 +09001480/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1481 * address family is returned so that it's easy for the caller to adapt to the
1482 * output format. Zero is returned if the address family is not supported. -1
1483 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1484 * supported.
1485 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001486int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001487{
1488
1489 uint16_t port;
1490
1491
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001492 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001493 return 0;
1494 *str = '\0';
1495
1496 switch (addr->ss_family) {
1497 case AF_INET:
1498 port = ((struct sockaddr_in *)addr)->sin_port;
1499 break;
1500 case AF_INET6:
1501 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1502 break;
1503 case AF_UNIX:
1504 memcpy(str, "unix", 5);
1505 return addr->ss_family;
1506 default:
1507 return 0;
1508 }
1509
1510 snprintf(str, size, "%u", ntohs(port));
1511 return addr->ss_family;
1512}
1513
Willy Tarreau16e01562016-08-09 16:46:18 +02001514/* check if the given address is local to the system or not. It will return
1515 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1516 * it is. We don't want to iterate over all interfaces for this (and it is not
1517 * portable). So instead we try to bind in UDP to this address on a free non
1518 * privileged port and to connect to the same address, port 0 (connect doesn't
1519 * care). If it succeeds, we own the address. Note that non-inet addresses are
1520 * considered local since they're most likely AF_UNIX.
1521 */
1522int addr_is_local(const struct netns_entry *ns,
1523 const struct sockaddr_storage *orig)
1524{
1525 struct sockaddr_storage addr;
1526 int result;
1527 int fd;
1528
1529 if (!is_inet_addr(orig))
1530 return 1;
1531
1532 memcpy(&addr, orig, sizeof(addr));
1533 set_host_port(&addr, 0);
1534
1535 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1536 if (fd < 0)
1537 return -1;
1538
1539 result = -1;
1540 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1541 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1542 result = 0; // fail, non-local address
1543 else
1544 result = 1; // success, local address
1545 }
1546 else {
1547 if (errno == EADDRNOTAVAIL)
1548 result = 0; // definitely not local :-)
1549 }
1550 close(fd);
1551
1552 return result;
1553}
1554
Willy Tarreaubaaee002006-06-26 02:48:02 +02001555/* will try to encode the string <string> replacing all characters tagged in
1556 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1557 * prefixed by <escape>, and will store the result between <start> (included)
1558 * and <stop> (excluded), and will always terminate the string with a '\0'
1559 * before <stop>. The position of the '\0' is returned if the conversion
1560 * completes. If bytes are missing between <start> and <stop>, then the
1561 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1562 * cannot even be stored so we return <start> without writing the 0.
1563 * The input string must also be zero-terminated.
1564 */
1565const char hextab[16] = "0123456789ABCDEF";
1566char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001567 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001568 const char *string)
1569{
1570 if (start < stop) {
1571 stop--; /* reserve one byte for the final '\0' */
1572 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001573 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001574 *start++ = *string;
1575 else {
1576 if (start + 3 >= stop)
1577 break;
1578 *start++ = escape;
1579 *start++ = hextab[(*string >> 4) & 15];
1580 *start++ = hextab[*string & 15];
1581 }
1582 string++;
1583 }
1584 *start = '\0';
1585 }
1586 return start;
1587}
1588
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001589/*
1590 * Same behavior as encode_string() above, except that it encodes chunk
1591 * <chunk> instead of a string.
1592 */
1593char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001594 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001595 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001596{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001597 char *str = chunk->area;
1598 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001599
1600 if (start < stop) {
1601 stop--; /* reserve one byte for the final '\0' */
1602 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001603 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001604 *start++ = *str;
1605 else {
1606 if (start + 3 >= stop)
1607 break;
1608 *start++ = escape;
1609 *start++ = hextab[(*str >> 4) & 15];
1610 *start++ = hextab[*str & 15];
1611 }
1612 str++;
1613 }
1614 *start = '\0';
1615 }
1616 return start;
1617}
1618
Dragan Dosen0edd1092016-02-12 13:23:02 +01001619/*
1620 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001621 * character. The input <string> must be zero-terminated. The result will
1622 * be stored between <start> (included) and <stop> (excluded). This
1623 * function will always try to terminate the resulting string with a '\0'
1624 * before <stop>, and will return its position if the conversion
1625 * completes.
1626 */
1627char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001628 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001629 const char *string)
1630{
1631 if (start < stop) {
1632 stop--; /* reserve one byte for the final '\0' */
1633 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001634 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001635 *start++ = *string;
1636 else {
1637 if (start + 2 >= stop)
1638 break;
1639 *start++ = escape;
1640 *start++ = *string;
1641 }
1642 string++;
1643 }
1644 *start = '\0';
1645 }
1646 return start;
1647}
1648
1649/*
1650 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001651 * character. <chunk> contains the input to be escaped. The result will be
1652 * stored between <start> (included) and <stop> (excluded). The function
1653 * will always try to terminate the resulting string with a '\0' before
1654 * <stop>, and will return its position if the conversion completes.
1655 */
1656char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001657 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001658 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001659{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001660 char *str = chunk->area;
1661 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001662
1663 if (start < stop) {
1664 stop--; /* reserve one byte for the final '\0' */
1665 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001666 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001667 *start++ = *str;
1668 else {
1669 if (start + 2 >= stop)
1670 break;
1671 *start++ = escape;
1672 *start++ = *str;
1673 }
1674 str++;
1675 }
1676 *start = '\0';
1677 }
1678 return start;
1679}
1680
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001681/* Check a string for using it in a CSV output format. If the string contains
1682 * one of the following four char <">, <,>, CR or LF, the string is
1683 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1684 * <str> is the input string to be escaped. The function assumes that
1685 * the input string is null-terminated.
1686 *
1687 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001688 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001689 * format.
1690 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001691 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001692 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001693 * If <quote> is 1, the converter puts the quotes only if any reserved character
1694 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001695 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001696 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001697 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001698 * The function returns the converted string on its output. If an error
1699 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001700 * for using the function directly as printf() argument.
1701 *
1702 * If the output buffer is too short to contain the input string, the result
1703 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001704 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001705 * This function appends the encoding to the existing output chunk, and it
1706 * guarantees that it starts immediately at the first available character of
1707 * the chunk. Please use csv_enc() instead if you want to replace the output
1708 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001709 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001710const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001711{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001712 char *end = output->area + output->size;
1713 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001714 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001715
Willy Tarreaub631c292016-01-08 10:04:08 +01001716 if (quote == 1) {
1717 /* automatic quoting: first verify if we'll have to quote the string */
1718 if (!strpbrk(str, "\n\r,\""))
1719 quote = 0;
1720 }
1721
1722 if (quote)
1723 *ptr++ = '"';
1724
Willy Tarreau898529b2016-01-06 18:07:04 +01001725 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1726 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001727 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001728 ptr++;
1729 if (ptr >= end - 2) {
1730 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001731 break;
1732 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001733 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001734 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001735 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001736 str++;
1737 }
1738
Willy Tarreaub631c292016-01-08 10:04:08 +01001739 if (quote)
1740 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001741
Willy Tarreau898529b2016-01-06 18:07:04 +01001742 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001743 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001744 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001745}
1746
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001747/* Decode an URL-encoded string in-place. The resulting string might
1748 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001749 * aborted, the string is truncated before the issue and a negative value is
1750 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001751 * If the 'in_form' argument is non-nul the string is assumed to be part of
1752 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1753 * turned to a space. If it's zero, this will only be done after a question
1754 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001755 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001756int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001757{
1758 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001759 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001760
1761 in = string;
1762 out = string;
1763 while (*in) {
1764 switch (*in) {
1765 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001766 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001767 break;
1768 case '%' :
1769 if (!ishex(in[1]) || !ishex(in[2]))
1770 goto end;
1771 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1772 in += 2;
1773 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001774 case '?':
1775 in_form = 1;
1776 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001777 default:
1778 *out++ = *in;
1779 break;
1780 }
1781 in++;
1782 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001783 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001784 end:
1785 *out = 0;
1786 return ret;
1787}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001788
Willy Tarreau6911fa42007-03-04 18:06:08 +01001789unsigned int str2ui(const char *s)
1790{
1791 return __str2ui(s);
1792}
1793
1794unsigned int str2uic(const char *s)
1795{
1796 return __str2uic(s);
1797}
1798
1799unsigned int strl2ui(const char *s, int len)
1800{
1801 return __strl2ui(s, len);
1802}
1803
1804unsigned int strl2uic(const char *s, int len)
1805{
1806 return __strl2uic(s, len);
1807}
1808
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001809unsigned int read_uint(const char **s, const char *end)
1810{
1811 return __read_uint(s, end);
1812}
1813
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001814/* This function reads an unsigned integer from the string pointed to by <s> and
1815 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1816 * function automatically stops at <end>. If the number overflows, the 2^64-1
1817 * value is returned.
1818 */
1819unsigned long long int read_uint64(const char **s, const char *end)
1820{
1821 const char *ptr = *s;
1822 unsigned long long int i = 0, tmp;
1823 unsigned int j;
1824
1825 while (ptr < end) {
1826
1827 /* read next char */
1828 j = *ptr - '0';
1829 if (j > 9)
1830 goto read_uint64_end;
1831
1832 /* add char to the number and check overflow. */
1833 tmp = i * 10;
1834 if (tmp / 10 != i) {
1835 i = ULLONG_MAX;
1836 goto read_uint64_eat;
1837 }
1838 if (ULLONG_MAX - tmp < j) {
1839 i = ULLONG_MAX;
1840 goto read_uint64_eat;
1841 }
1842 i = tmp + j;
1843 ptr++;
1844 }
1845read_uint64_eat:
1846 /* eat each numeric char */
1847 while (ptr < end) {
1848 if ((unsigned int)(*ptr - '0') > 9)
1849 break;
1850 ptr++;
1851 }
1852read_uint64_end:
1853 *s = ptr;
1854 return i;
1855}
1856
1857/* This function reads an integer from the string pointed to by <s> and returns
1858 * it. The <s> pointer is adjusted to point to the first unread char. The function
1859 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1860 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1861 * returned.
1862 */
1863long long int read_int64(const char **s, const char *end)
1864{
1865 unsigned long long int i = 0;
1866 int neg = 0;
1867
1868 /* Look for minus char. */
1869 if (**s == '-') {
1870 neg = 1;
1871 (*s)++;
1872 }
1873 else if (**s == '+')
1874 (*s)++;
1875
1876 /* convert as positive number. */
1877 i = read_uint64(s, end);
1878
1879 if (neg) {
1880 if (i > 0x8000000000000000ULL)
1881 return LLONG_MIN;
1882 return -i;
1883 }
1884 if (i > 0x7fffffffffffffffULL)
1885 return LLONG_MAX;
1886 return i;
1887}
1888
Willy Tarreau6911fa42007-03-04 18:06:08 +01001889/* This one is 7 times faster than strtol() on athlon with checks.
1890 * It returns the value of the number composed of all valid digits read,
1891 * and can process negative numbers too.
1892 */
1893int strl2ic(const char *s, int len)
1894{
1895 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001896 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001897
1898 if (len > 0) {
1899 if (*s != '-') {
1900 /* positive number */
1901 while (len-- > 0) {
1902 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001903 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001904 if (j > 9)
1905 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001906 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001907 }
1908 } else {
1909 /* negative number */
1910 s++;
1911 while (--len > 0) {
1912 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001913 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001914 if (j > 9)
1915 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001916 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001917 }
1918 }
1919 }
1920 return i;
1921}
1922
1923
1924/* This function reads exactly <len> chars from <s> and converts them to a
1925 * signed integer which it stores into <ret>. It accurately detects any error
1926 * (truncated string, invalid chars, overflows). It is meant to be used in
1927 * applications designed for hostile environments. It returns zero when the
1928 * number has successfully been converted, non-zero otherwise. When an error
1929 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1930 * faster than strtol().
1931 */
1932int strl2irc(const char *s, int len, int *ret)
1933{
1934 int i = 0;
1935 int j;
1936
1937 if (!len)
1938 return 1;
1939
1940 if (*s != '-') {
1941 /* positive number */
1942 while (len-- > 0) {
1943 j = (*s++) - '0';
1944 if (j > 9) return 1; /* invalid char */
1945 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1946 i = i * 10;
1947 if (i + j < i) return 1; /* check for addition overflow */
1948 i = i + j;
1949 }
1950 } else {
1951 /* negative number */
1952 s++;
1953 while (--len > 0) {
1954 j = (*s++) - '0';
1955 if (j > 9) return 1; /* invalid char */
1956 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1957 i = i * 10;
1958 if (i - j > i) return 1; /* check for subtract overflow */
1959 i = i - j;
1960 }
1961 }
1962 *ret = i;
1963 return 0;
1964}
1965
1966
1967/* This function reads exactly <len> chars from <s> and converts them to a
1968 * signed integer which it stores into <ret>. It accurately detects any error
1969 * (truncated string, invalid chars, overflows). It is meant to be used in
1970 * applications designed for hostile environments. It returns zero when the
1971 * number has successfully been converted, non-zero otherwise. When an error
1972 * is returned, the <ret> value is left untouched. It is about 3 times slower
1973 * than str2irc().
1974 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001975
1976int strl2llrc(const char *s, int len, long long *ret)
1977{
1978 long long i = 0;
1979 int j;
1980
1981 if (!len)
1982 return 1;
1983
1984 if (*s != '-') {
1985 /* positive number */
1986 while (len-- > 0) {
1987 j = (*s++) - '0';
1988 if (j > 9) return 1; /* invalid char */
1989 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1990 i = i * 10LL;
1991 if (i + j < i) return 1; /* check for addition overflow */
1992 i = i + j;
1993 }
1994 } else {
1995 /* negative number */
1996 s++;
1997 while (--len > 0) {
1998 j = (*s++) - '0';
1999 if (j > 9) return 1; /* invalid char */
2000 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2001 i = i * 10LL;
2002 if (i - j > i) return 1; /* check for subtract overflow */
2003 i = i - j;
2004 }
2005 }
2006 *ret = i;
2007 return 0;
2008}
2009
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002010/* This function is used with pat_parse_dotted_ver(). It converts a string
2011 * composed by two number separated by a dot. Each part must contain in 16 bits
2012 * because internally they will be represented as a 32-bit quantity stored in
2013 * a 64-bit integer. It returns zero when the number has successfully been
2014 * converted, non-zero otherwise. When an error is returned, the <ret> value
2015 * is left untouched.
2016 *
2017 * "1.3" -> 0x0000000000010003
2018 * "65535.65535" -> 0x00000000ffffffff
2019 */
2020int strl2llrc_dotted(const char *text, int len, long long *ret)
2021{
2022 const char *end = &text[len];
2023 const char *p;
2024 long long major, minor;
2025
2026 /* Look for dot. */
2027 for (p = text; p < end; p++)
2028 if (*p == '.')
2029 break;
2030
2031 /* Convert major. */
2032 if (strl2llrc(text, p - text, &major) != 0)
2033 return 1;
2034
2035 /* Check major. */
2036 if (major >= 65536)
2037 return 1;
2038
2039 /* Convert minor. */
2040 minor = 0;
2041 if (p < end)
2042 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2043 return 1;
2044
2045 /* Check minor. */
2046 if (minor >= 65536)
2047 return 1;
2048
2049 /* Compose value. */
2050 *ret = (major << 16) | (minor & 0xffff);
2051 return 0;
2052}
2053
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002054/* This function parses a time value optionally followed by a unit suffix among
2055 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2056 * expected by the caller. The computation does its best to avoid overflows.
2057 * The value is returned in <ret> if everything is fine, and a NULL is returned
2058 * by the function. In case of error, a pointer to the error is returned and
2059 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002060 * Values resulting in values larger than or equal to 2^31 after conversion are
2061 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2062 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002063 */
2064const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2065{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002066 unsigned long long imult, idiv;
2067 unsigned long long omult, odiv;
2068 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002069
2070 omult = odiv = 1;
2071
2072 switch (unit_flags & TIME_UNIT_MASK) {
2073 case TIME_UNIT_US: omult = 1000000; break;
2074 case TIME_UNIT_MS: omult = 1000; break;
2075 case TIME_UNIT_S: break;
2076 case TIME_UNIT_MIN: odiv = 60; break;
2077 case TIME_UNIT_HOUR: odiv = 3600; break;
2078 case TIME_UNIT_DAY: odiv = 86400; break;
2079 default: break;
2080 }
2081
2082 value = 0;
2083
2084 while (1) {
2085 unsigned int j;
2086
2087 j = *text - '0';
2088 if (j > 9)
2089 break;
2090 text++;
2091 value *= 10;
2092 value += j;
2093 }
2094
2095 imult = idiv = 1;
2096 switch (*text) {
2097 case '\0': /* no unit = default unit */
2098 imult = omult = idiv = odiv = 1;
2099 break;
2100 case 's': /* second = unscaled unit */
2101 break;
2102 case 'u': /* microsecond : "us" */
2103 if (text[1] == 's') {
2104 idiv = 1000000;
2105 text++;
2106 }
2107 break;
2108 case 'm': /* millisecond : "ms" or minute: "m" */
2109 if (text[1] == 's') {
2110 idiv = 1000;
2111 text++;
2112 } else
2113 imult = 60;
2114 break;
2115 case 'h': /* hour : "h" */
2116 imult = 3600;
2117 break;
2118 case 'd': /* day : "d" */
2119 imult = 86400;
2120 break;
2121 default:
2122 return text;
2123 break;
2124 }
2125
2126 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2127 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2128 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2129 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2130
Willy Tarreau9faebe32019-06-07 19:00:37 +02002131 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2132 if (result >= 0x80000000)
2133 return PARSE_TIME_OVER;
2134 if (!result && value)
2135 return PARSE_TIME_UNDER;
2136 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002137 return NULL;
2138}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002139
Emeric Brun39132b22010-01-04 14:57:24 +01002140/* this function converts the string starting at <text> to an unsigned int
2141 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002142 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002143 */
2144const char *parse_size_err(const char *text, unsigned *ret) {
2145 unsigned value = 0;
2146
2147 while (1) {
2148 unsigned int j;
2149
2150 j = *text - '0';
2151 if (j > 9)
2152 break;
2153 if (value > ~0U / 10)
2154 return text;
2155 value *= 10;
2156 if (value > (value + j))
2157 return text;
2158 value += j;
2159 text++;
2160 }
2161
2162 switch (*text) {
2163 case '\0':
2164 break;
2165 case 'K':
2166 case 'k':
2167 if (value > ~0U >> 10)
2168 return text;
2169 value = value << 10;
2170 break;
2171 case 'M':
2172 case 'm':
2173 if (value > ~0U >> 20)
2174 return text;
2175 value = value << 20;
2176 break;
2177 case 'G':
2178 case 'g':
2179 if (value > ~0U >> 30)
2180 return text;
2181 value = value << 30;
2182 break;
2183 default:
2184 return text;
2185 }
2186
Godbach58048a22015-01-28 17:36:16 +08002187 if (*text != '\0' && *++text != '\0')
2188 return text;
2189
Emeric Brun39132b22010-01-04 14:57:24 +01002190 *ret = value;
2191 return NULL;
2192}
2193
Willy Tarreau126d4062013-12-03 17:50:47 +01002194/*
2195 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002196 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002197 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002198 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002199 */
2200int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2201{
2202 int len;
2203 const char *p = source;
2204 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002205 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002206
2207 len = strlen(source);
2208 if (len % 2) {
2209 memprintf(err, "an even number of hex digit is expected");
2210 return 0;
2211 }
2212
2213 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002214
Willy Tarreau126d4062013-12-03 17:50:47 +01002215 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002216 *binstr = calloc(len, sizeof(char));
2217 if (!*binstr) {
2218 memprintf(err, "out of memory while loading string pattern");
2219 return 0;
2220 }
2221 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002222 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002223 else {
2224 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002225 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002226 len, *binstrlen);
2227 return 0;
2228 }
2229 alloc = 0;
2230 }
2231 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002232
2233 i = j = 0;
2234 while (j < len) {
2235 if (!ishex(p[i++]))
2236 goto bad_input;
2237 if (!ishex(p[i++]))
2238 goto bad_input;
2239 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2240 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002241 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002242
2243bad_input:
2244 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002245 if (alloc) {
2246 free(*binstr);
2247 *binstr = NULL;
2248 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002249 return 0;
2250}
2251
Willy Tarreau946ba592009-05-10 15:41:18 +02002252/* copies at most <n> characters from <src> and always terminates with '\0' */
2253char *my_strndup(const char *src, int n)
2254{
2255 int len = 0;
2256 char *ret;
2257
2258 while (len < n && src[len])
2259 len++;
2260
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002261 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002262 if (!ret)
2263 return ret;
2264 memcpy(ret, src, len);
2265 ret[len] = '\0';
2266 return ret;
2267}
2268
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002269/*
2270 * search needle in haystack
2271 * returns the pointer if found, returns NULL otherwise
2272 */
2273const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2274{
2275 const void *c = NULL;
2276 unsigned char f;
2277
2278 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2279 return NULL;
2280
2281 f = *(char *)needle;
2282 c = haystack;
2283 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2284 if ((haystacklen - (c - haystack)) < needlelen)
2285 return NULL;
2286
2287 if (memcmp(c, needle, needlelen) == 0)
2288 return c;
2289 ++c;
2290 }
2291 return NULL;
2292}
2293
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002294/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002295size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2296{
2297 size_t ret = 0;
2298
2299 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2300 str++;
2301 ret++;
2302 }
2303 return ret;
2304}
2305
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002306/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002307size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2308{
2309 size_t ret = 0;
2310
2311 while (ret < len) {
2312 if(memchr(reject, *((int *)str), rejectlen))
2313 return ret;
2314 str++;
2315 ret++;
2316 }
2317 return ret;
2318}
2319
Willy Tarreau482b00d2009-10-04 22:48:42 +02002320/* This function returns the first unused key greater than or equal to <key> in
2321 * ID tree <root>. Zero is returned if no place is found.
2322 */
2323unsigned int get_next_id(struct eb_root *root, unsigned int key)
2324{
2325 struct eb32_node *used;
2326
2327 do {
2328 used = eb32_lookup_ge(root, key);
2329 if (!used || used->key > key)
2330 return key; /* key is available */
2331 key++;
2332 } while (key);
2333 return key;
2334}
2335
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002336/* dump the full tree to <file> in DOT format for debugging purposes. Will
2337 * optionally highlight node <subj> if found, depending on operation <op> :
2338 * 0 : nothing
2339 * >0 : insertion, node/leaf are surrounded in red
2340 * <0 : removal, node/leaf are dashed with no background
2341 * Will optionally add "desc" as a label on the graph if set and non-null.
2342 */
2343void 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 +01002344{
2345 struct eb32sc_node *node;
2346 unsigned long scope = -1;
2347
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002348 fprintf(file, "digraph ebtree {\n");
2349
2350 if (desc && *desc) {
2351 fprintf(file,
2352 " fontname=\"fixed\";\n"
2353 " fontsize=8;\n"
2354 " label=\"%s\";\n", desc);
2355 }
2356
Willy Tarreaued3cda02017-11-15 15:04:05 +01002357 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002358 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2359 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002360 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2361 );
2362
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002363 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002364 (long)eb_root_to_node(root),
2365 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002366 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2367
2368 node = eb32sc_first(root, scope);
2369 while (node) {
2370 if (node->node.node_p) {
2371 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002372 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2373 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2374 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002375
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002376 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002377 (long)node,
2378 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002379 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002380
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002381 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002382 (long)node,
2383 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002384 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2385
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002386 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002387 (long)node,
2388 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002389 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2390 }
2391
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002392 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2393 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2394 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002395
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002396 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002397 (long)node,
2398 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002399 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002400 node = eb32sc_next(node, scope);
2401 }
2402 fprintf(file, "}\n");
2403}
2404
Willy Tarreau348238b2010-01-18 15:05:57 +01002405/* This function compares a sample word possibly followed by blanks to another
2406 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2407 * otherwise zero. This intends to be used when checking HTTP headers for some
2408 * values. Note that it validates a word followed only by blanks but does not
2409 * validate a word followed by blanks then other chars.
2410 */
2411int word_match(const char *sample, int slen, const char *word, int wlen)
2412{
2413 if (slen < wlen)
2414 return 0;
2415
2416 while (wlen) {
2417 char c = *sample ^ *word;
2418 if (c && c != ('A' ^ 'a'))
2419 return 0;
2420 sample++;
2421 word++;
2422 slen--;
2423 wlen--;
2424 }
2425
2426 while (slen) {
2427 if (*sample != ' ' && *sample != '\t')
2428 return 0;
2429 sample++;
2430 slen--;
2431 }
2432 return 1;
2433}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002434
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002435/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2436 * is particularly fast because it avoids expensive operations such as
2437 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002438 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002439 */
2440unsigned int inetaddr_host(const char *text)
2441{
2442 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2443 register unsigned int dig100, dig10, dig1;
2444 int s;
2445 const char *p, *d;
2446
2447 dig1 = dig10 = dig100 = ascii_zero;
2448 s = 24;
2449
2450 p = text;
2451 while (1) {
2452 if (((unsigned)(*p - '0')) <= 9) {
2453 p++;
2454 continue;
2455 }
2456
2457 /* here, we have a complete byte between <text> and <p> (exclusive) */
2458 if (p == text)
2459 goto end;
2460
2461 d = p - 1;
2462 dig1 |= (unsigned int)(*d << s);
2463 if (d == text)
2464 goto end;
2465
2466 d--;
2467 dig10 |= (unsigned int)(*d << s);
2468 if (d == text)
2469 goto end;
2470
2471 d--;
2472 dig100 |= (unsigned int)(*d << s);
2473 end:
2474 if (!s || *p != '.')
2475 break;
2476
2477 s -= 8;
2478 text = ++p;
2479 }
2480
2481 dig100 -= ascii_zero;
2482 dig10 -= ascii_zero;
2483 dig1 -= ascii_zero;
2484 return ((dig100 * 10) + dig10) * 10 + dig1;
2485}
2486
2487/*
2488 * Idem except the first unparsed character has to be passed in <stop>.
2489 */
2490unsigned int inetaddr_host_lim(const char *text, const char *stop)
2491{
2492 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2493 register unsigned int dig100, dig10, dig1;
2494 int s;
2495 const char *p, *d;
2496
2497 dig1 = dig10 = dig100 = ascii_zero;
2498 s = 24;
2499
2500 p = text;
2501 while (1) {
2502 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2503 p++;
2504 continue;
2505 }
2506
2507 /* here, we have a complete byte between <text> and <p> (exclusive) */
2508 if (p == text)
2509 goto end;
2510
2511 d = p - 1;
2512 dig1 |= (unsigned int)(*d << s);
2513 if (d == text)
2514 goto end;
2515
2516 d--;
2517 dig10 |= (unsigned int)(*d << s);
2518 if (d == text)
2519 goto end;
2520
2521 d--;
2522 dig100 |= (unsigned int)(*d << s);
2523 end:
2524 if (!s || p == stop || *p != '.')
2525 break;
2526
2527 s -= 8;
2528 text = ++p;
2529 }
2530
2531 dig100 -= ascii_zero;
2532 dig10 -= ascii_zero;
2533 dig1 -= ascii_zero;
2534 return ((dig100 * 10) + dig10) * 10 + dig1;
2535}
2536
2537/*
2538 * Idem except the pointer to first unparsed byte is returned into <ret> which
2539 * must not be NULL.
2540 */
Willy Tarreau74172752010-10-15 23:21:42 +02002541unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002542{
2543 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2544 register unsigned int dig100, dig10, dig1;
2545 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002546 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002547
2548 dig1 = dig10 = dig100 = ascii_zero;
2549 s = 24;
2550
2551 p = text;
2552 while (1) {
2553 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2554 p++;
2555 continue;
2556 }
2557
2558 /* here, we have a complete byte between <text> and <p> (exclusive) */
2559 if (p == text)
2560 goto end;
2561
2562 d = p - 1;
2563 dig1 |= (unsigned int)(*d << s);
2564 if (d == text)
2565 goto end;
2566
2567 d--;
2568 dig10 |= (unsigned int)(*d << s);
2569 if (d == text)
2570 goto end;
2571
2572 d--;
2573 dig100 |= (unsigned int)(*d << s);
2574 end:
2575 if (!s || p == stop || *p != '.')
2576 break;
2577
2578 s -= 8;
2579 text = ++p;
2580 }
2581
2582 *ret = p;
2583 dig100 -= ascii_zero;
2584 dig10 -= ascii_zero;
2585 dig1 -= ascii_zero;
2586 return ((dig100 * 10) + dig10) * 10 + dig1;
2587}
2588
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002589/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2590 * or the number of chars read in case of success. Maybe this could be replaced
2591 * by one of the functions above. Also, apparently this function does not support
2592 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002593 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002594 */
2595int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2596{
2597 const char *addr;
2598 int saw_digit, octets, ch;
2599 u_char tmp[4], *tp;
2600 const char *cp = buf;
2601
2602 saw_digit = 0;
2603 octets = 0;
2604 *(tp = tmp) = 0;
2605
2606 for (addr = buf; addr - buf < len; addr++) {
2607 unsigned char digit = (ch = *addr) - '0';
2608
2609 if (digit > 9 && ch != '.')
2610 break;
2611
2612 if (digit <= 9) {
2613 u_int new = *tp * 10 + digit;
2614
2615 if (new > 255)
2616 return 0;
2617
2618 *tp = new;
2619
2620 if (!saw_digit) {
2621 if (++octets > 4)
2622 return 0;
2623 saw_digit = 1;
2624 }
2625 } else if (ch == '.' && saw_digit) {
2626 if (octets == 4)
2627 return 0;
2628
2629 *++tp = 0;
2630 saw_digit = 0;
2631 } else
2632 return 0;
2633 }
2634
2635 if (octets < 4)
2636 return 0;
2637
2638 memcpy(&dst->s_addr, tmp, 4);
2639 return addr - cp;
2640}
2641
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002642/* This function converts the string in <buf> of the len <len> to
2643 * struct in6_addr <dst> which must be allocated by the caller.
2644 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002645 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002646 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002647int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2648{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002649 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002650 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002651
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002652 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002653 return 0;
2654
2655 memcpy(null_term_ip6, buf, len);
2656 null_term_ip6[len] = '\0';
2657
Willy Tarreau075415a2013-12-12 11:29:39 +01002658 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002659 return 0;
2660
Willy Tarreau075415a2013-12-12 11:29:39 +01002661 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002662 return 1;
2663}
2664
Willy Tarreauacf95772010-06-14 19:09:21 +02002665/* To be used to quote config arg positions. Returns the short string at <ptr>
2666 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2667 * if ptr is NULL or empty. The string is locally allocated.
2668 */
2669const char *quote_arg(const char *ptr)
2670{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002671 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002672 int i;
2673
2674 if (!ptr || !*ptr)
2675 return "end of line";
2676 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002677 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002678 val[i] = *ptr++;
2679 val[i++] = '\'';
2680 val[i] = '\0';
2681 return val;
2682}
2683
Willy Tarreau5b180202010-07-18 10:40:48 +02002684/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2685int get_std_op(const char *str)
2686{
2687 int ret = -1;
2688
2689 if (*str == 'e' && str[1] == 'q')
2690 ret = STD_OP_EQ;
2691 else if (*str == 'n' && str[1] == 'e')
2692 ret = STD_OP_NE;
2693 else if (*str == 'l') {
2694 if (str[1] == 'e') ret = STD_OP_LE;
2695 else if (str[1] == 't') ret = STD_OP_LT;
2696 }
2697 else if (*str == 'g') {
2698 if (str[1] == 'e') ret = STD_OP_GE;
2699 else if (str[1] == 't') ret = STD_OP_GT;
2700 }
2701
2702 if (ret == -1 || str[2] != '\0')
2703 return -1;
2704 return ret;
2705}
2706
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002707/* hash a 32-bit integer to another 32-bit integer */
2708unsigned int full_hash(unsigned int a)
2709{
2710 return __full_hash(a);
2711}
2712
Willy Tarreauf3241112019-02-26 09:56:22 +01002713/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2714 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2715 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2716 * a popcount variant and is described here :
2717 * https://graphics.stanford.edu/~seander/bithacks.html
2718 */
2719unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2720{
2721 unsigned long a, b, c, d;
2722 unsigned int s;
2723 unsigned int t;
2724
2725 a = m - ((m >> 1) & ~0UL/3);
2726 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2727 c = (b + (b >> 4)) & ~0UL/0x11;
2728 d = (c + (c >> 8)) & ~0UL/0x101;
2729
2730 r++; // make r be 1..64
2731
2732 t = 0;
2733 s = LONGBITS;
2734 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002735 unsigned long d2 = (d >> 16) >> 16;
2736 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002737 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2738 }
2739
2740 t = (d >> (s - 16)) & 0xff;
2741 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2742 t = (c >> (s - 8)) & 0xf;
2743 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2744 t = (b >> (s - 4)) & 0x7;
2745 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2746 t = (a >> (s - 2)) & 0x3;
2747 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2748 t = (m >> (s - 1)) & 0x1;
2749 s -= ((t - r) & 256) >> 8;
2750
2751 return s - 1;
2752}
2753
2754/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2755 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2756 * using mask_prep_rank_map() below.
2757 */
2758unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2759 unsigned long a, unsigned long b,
2760 unsigned long c, unsigned long d)
2761{
2762 unsigned int s;
2763 unsigned int t;
2764
2765 r++; // make r be 1..64
2766
2767 t = 0;
2768 s = LONGBITS;
2769 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002770 unsigned long d2 = (d >> 16) >> 16;
2771 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002772 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2773 }
2774
2775 t = (d >> (s - 16)) & 0xff;
2776 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2777 t = (c >> (s - 8)) & 0xf;
2778 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2779 t = (b >> (s - 4)) & 0x7;
2780 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2781 t = (a >> (s - 2)) & 0x3;
2782 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2783 t = (m >> (s - 1)) & 0x1;
2784 s -= ((t - r) & 256) >> 8;
2785
2786 return s - 1;
2787}
2788
2789/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2790 * above.
2791 */
2792void mask_prep_rank_map(unsigned long m,
2793 unsigned long *a, unsigned long *b,
2794 unsigned long *c, unsigned long *d)
2795{
2796 *a = m - ((m >> 1) & ~0UL/3);
2797 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2798 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2799 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2800}
2801
David du Colombier4f92d322011-03-24 11:09:31 +01002802/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002803 * otherwise zero. Note that <addr> may not necessarily be aligned
2804 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002805 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002806int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002807{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002808 struct in_addr addr_copy;
2809
2810 memcpy(&addr_copy, addr, sizeof(addr_copy));
2811 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002812}
2813
2814/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002815 * otherwise zero. Note that <addr> may not necessarily be aligned
2816 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002817 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002818int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002819{
2820 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002821 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002822
Willy Tarreaueec1d382016-07-13 11:59:39 +02002823 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002824 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002825 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002826 (((int *)net)[i] & ((int *)mask)[i]))
2827 return 0;
2828 return 1;
2829}
2830
2831/* RFC 4291 prefix */
2832const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2833 0x00, 0x00, 0x00, 0x00,
2834 0x00, 0x00, 0xFF, 0xFF };
2835
Joseph Herlant32b83272018-11-15 11:58:28 -08002836/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002837 * Input and output may overlap.
2838 */
David du Colombier4f92d322011-03-24 11:09:31 +01002839void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2840{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002841 struct in_addr tmp_addr;
2842
2843 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002844 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002845 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002846}
2847
Joseph Herlant32b83272018-11-15 11:58:28 -08002848/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002849 * Return true if conversion is possible and false otherwise.
2850 */
2851int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2852{
2853 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2854 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2855 sizeof(struct in_addr));
2856 return 1;
2857 }
2858
2859 return 0;
2860}
2861
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002862/* compare two struct sockaddr_storage and return:
2863 * 0 (true) if the addr is the same in both
2864 * 1 (false) if the addr is not the same in both
2865 * -1 (unable) if one of the addr is not AF_INET*
2866 */
2867int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2868{
2869 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2870 return -1;
2871
2872 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2873 return -1;
2874
2875 if (ss1->ss_family != ss2->ss_family)
2876 return 1;
2877
2878 switch (ss1->ss_family) {
2879 case AF_INET:
2880 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2881 &((struct sockaddr_in *)ss2)->sin_addr,
2882 sizeof(struct in_addr)) != 0;
2883 case AF_INET6:
2884 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2885 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2886 sizeof(struct in6_addr)) != 0;
2887 }
2888
2889 return 1;
2890}
2891
Baptiste Assmann08396c82016-01-31 00:27:17 +01002892/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002893 * The caller must allocate and clear <dest> before calling.
2894 * The source must be in either AF_INET or AF_INET6 family, or the destination
2895 * address will be undefined. If the destination address used to hold a port,
2896 * it is preserved, so that this function can be used to switch to another
2897 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002898 */
2899struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2900{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002901 int prev_port;
2902
2903 prev_port = get_net_port(dest);
2904 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002905 dest->ss_family = source->ss_family;
2906
2907 /* copy new addr and apply it */
2908 switch (source->ss_family) {
2909 case AF_INET:
2910 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002911 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002912 break;
2913 case AF_INET6:
2914 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 +01002915 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002916 break;
2917 }
2918
2919 return dest;
2920}
2921
William Lallemand421f5b52012-02-06 18:15:57 +01002922char *human_time(int t, short hz_div) {
2923 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2924 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002925 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002926 int cnt=2; // print two numbers
2927
2928 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002929 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002930 return rv;
2931 }
2932
2933 if (unlikely(hz_div > 1))
2934 t /= hz_div;
2935
2936 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002937 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002938 cnt--;
2939 }
2940
2941 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002942 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002943 cnt--;
2944 }
2945
2946 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002947 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002948 cnt--;
2949 }
2950
2951 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002952 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002953
2954 return rv;
2955}
2956
2957const char *monthname[12] = {
2958 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2959 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2960};
2961
2962/* date2str_log: write a date in the format :
2963 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2964 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2965 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2966 *
2967 * without using sprintf. return a pointer to the last char written (\0) or
2968 * NULL if there isn't enough space.
2969 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002970char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002971{
2972
2973 if (size < 25) /* the size is fixed: 24 chars + \0 */
2974 return NULL;
2975
2976 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002977 if (!dst)
2978 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002979 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002980
William Lallemand421f5b52012-02-06 18:15:57 +01002981 memcpy(dst, monthname[tm->tm_mon], 3); // month
2982 dst += 3;
2983 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002984
William Lallemand421f5b52012-02-06 18:15:57 +01002985 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002986 if (!dst)
2987 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002988 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002989
William Lallemand421f5b52012-02-06 18:15:57 +01002990 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002991 if (!dst)
2992 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002993 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002994
William Lallemand421f5b52012-02-06 18:15:57 +01002995 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002996 if (!dst)
2997 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002998 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002999
William Lallemand421f5b52012-02-06 18:15:57 +01003000 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003001 if (!dst)
3002 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003003 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003004
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003005 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003006 if (!dst)
3007 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003008 *dst = '\0';
3009
3010 return dst;
3011}
3012
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003013/* Base year used to compute leap years */
3014#define TM_YEAR_BASE 1900
3015
3016/* Return the difference in seconds between two times (leap seconds are ignored).
3017 * Retrieved from glibc 2.18 source code.
3018 */
3019static int my_tm_diff(const struct tm *a, const struct tm *b)
3020{
3021 /* Compute intervening leap days correctly even if year is negative.
3022 * Take care to avoid int overflow in leap day calculations,
3023 * but it's OK to assume that A and B are close to each other.
3024 */
3025 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3026 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3027 int a100 = a4 / 25 - (a4 % 25 < 0);
3028 int b100 = b4 / 25 - (b4 % 25 < 0);
3029 int a400 = a100 >> 2;
3030 int b400 = b100 >> 2;
3031 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3032 int years = a->tm_year - b->tm_year;
3033 int days = (365 * years + intervening_leap_days
3034 + (a->tm_yday - b->tm_yday));
3035 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3036 + (a->tm_min - b->tm_min))
3037 + (a->tm_sec - b->tm_sec));
3038}
3039
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003040/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003041 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003042 * The string returned has the same format as returned by strftime(... "%z", tm).
3043 * Offsets are kept in an internal cache for better performances.
3044 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003045const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003046{
3047 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003048 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003049
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003050 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003051 struct tm tm_gmt;
3052 int diff;
3053 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003054
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003055 /* Pretend DST not active if its status is unknown */
3056 if (isdst < 0)
3057 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003058
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003059 /* Fetch the offset and initialize it if needed */
3060 gmt_offset = gmt_offsets[isdst & 0x01];
3061 if (unlikely(!*gmt_offset)) {
3062 get_gmtime(t, &tm_gmt);
3063 diff = my_tm_diff(tm, &tm_gmt);
3064 if (diff < 0) {
3065 diff = -diff;
3066 *gmt_offset = '-';
3067 } else {
3068 *gmt_offset = '+';
3069 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003070 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003071 diff /= 60; /* Convert to minutes */
3072 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3073 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003074
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003075 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003076}
3077
William Lallemand421f5b52012-02-06 18:15:57 +01003078/* gmt2str_log: write a date in the format :
3079 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3080 * return a pointer to the last char written (\0) or
3081 * NULL if there isn't enough space.
3082 */
3083char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3084{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003085 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003086 return NULL;
3087
3088 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003089 if (!dst)
3090 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003091 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003092
William Lallemand421f5b52012-02-06 18:15:57 +01003093 memcpy(dst, monthname[tm->tm_mon], 3); // month
3094 dst += 3;
3095 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003096
William Lallemand421f5b52012-02-06 18:15:57 +01003097 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003098 if (!dst)
3099 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003100 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003101
William Lallemand421f5b52012-02-06 18:15:57 +01003102 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003103 if (!dst)
3104 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003105 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003106
William Lallemand421f5b52012-02-06 18:15:57 +01003107 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003108 if (!dst)
3109 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003110 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003111
William Lallemand421f5b52012-02-06 18:15:57 +01003112 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003113 if (!dst)
3114 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003115 *dst++ = ' ';
3116 *dst++ = '+';
3117 *dst++ = '0';
3118 *dst++ = '0';
3119 *dst++ = '0';
3120 *dst++ = '0';
3121 *dst = '\0';
3122
3123 return dst;
3124}
3125
Yuxans Yao4e25b012012-10-19 10:36:09 +08003126/* localdate2str_log: write a date in the format :
3127 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003128 * Both t and tm must represent the same time.
3129 * return a pointer to the last char written (\0) or
3130 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003131 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003132char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003133{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003134 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003135 if (size < 27) /* the size is fixed: 26 chars + \0 */
3136 return NULL;
3137
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003138 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003139
Yuxans Yao4e25b012012-10-19 10:36:09 +08003140 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003141 if (!dst)
3142 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003143 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003144
Yuxans Yao4e25b012012-10-19 10:36:09 +08003145 memcpy(dst, monthname[tm->tm_mon], 3); // month
3146 dst += 3;
3147 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003148
Yuxans Yao4e25b012012-10-19 10:36:09 +08003149 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003150 if (!dst)
3151 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003152 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003153
Yuxans Yao4e25b012012-10-19 10:36:09 +08003154 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003155 if (!dst)
3156 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003157 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003158
Yuxans Yao4e25b012012-10-19 10:36:09 +08003159 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003160 if (!dst)
3161 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003162 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003163
Yuxans Yao4e25b012012-10-19 10:36:09 +08003164 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003165 if (!dst)
3166 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003167 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003168
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003169 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003170 dst += 5;
3171 *dst = '\0';
3172
3173 return dst;
3174}
3175
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003176/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3177 * It is meant as a portable replacement for timegm() for use with valid inputs.
3178 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3179 */
3180time_t my_timegm(const struct tm *tm)
3181{
3182 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3183 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3184 * sum of the extra N days for elapsed months. The sum of all these N
3185 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3186 * in a 5-bit word. This means that with 60 bits we can represent a
3187 * matrix of all these values at once, which is fast and efficient to
3188 * access. The extra February day for leap years is not counted here.
3189 *
3190 * Jan : none = 0 (0)
3191 * Feb : Jan = 3 (3)
3192 * Mar : Jan..Feb = 3 (3 + 0)
3193 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3194 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3195 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3196 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3197 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3198 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3199 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3200 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3201 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3202 */
3203 uint64_t extra =
3204 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3205 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3206 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3207 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3208
3209 unsigned int y = tm->tm_year + 1900;
3210 unsigned int m = tm->tm_mon;
3211 unsigned long days = 0;
3212
3213 /* days since 1/1/1970 for full years */
3214 days += days_since_zero(y) - days_since_zero(1970);
3215
3216 /* days for full months in the current year */
3217 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3218
3219 /* count + 1 after March for leap years. A leap year is a year multiple
3220 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3221 * is leap, 1900 isn't, 1904 is.
3222 */
3223 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3224 days++;
3225
3226 days += tm->tm_mday - 1;
3227 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3228}
3229
Thierry Fournier93127942016-01-20 18:49:45 +01003230/* This function check a char. It returns true and updates
3231 * <date> and <len> pointer to the new position if the
3232 * character is found.
3233 */
3234static inline int parse_expect_char(const char **date, int *len, char c)
3235{
3236 if (*len < 1 || **date != c)
3237 return 0;
3238 (*len)--;
3239 (*date)++;
3240 return 1;
3241}
3242
3243/* This function expects a string <str> of len <l>. It return true and updates.
3244 * <date> and <len> if the string matches, otherwise, it returns false.
3245 */
3246static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3247{
3248 if (*len < l || strncmp(*date, str, l) != 0)
3249 return 0;
3250 (*len) -= l;
3251 (*date) += l;
3252 return 1;
3253}
3254
3255/* This macro converts 3 chars name in integer. */
3256#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3257
3258/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3259 * / %x54.75.65 ; "Tue", case-sensitive
3260 * / %x57.65.64 ; "Wed", case-sensitive
3261 * / %x54.68.75 ; "Thu", case-sensitive
3262 * / %x46.72.69 ; "Fri", case-sensitive
3263 * / %x53.61.74 ; "Sat", case-sensitive
3264 * / %x53.75.6E ; "Sun", case-sensitive
3265 *
3266 * This array must be alphabetically sorted
3267 */
3268static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3269{
3270 if (*len < 3)
3271 return 0;
3272 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3273 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3274 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3275 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3276 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3277 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3278 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3279 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3280 default: return 0;
3281 }
3282 *len -= 3;
3283 *date += 3;
3284 return 1;
3285}
3286
3287/* month = %x4A.61.6E ; "Jan", case-sensitive
3288 * / %x46.65.62 ; "Feb", case-sensitive
3289 * / %x4D.61.72 ; "Mar", case-sensitive
3290 * / %x41.70.72 ; "Apr", case-sensitive
3291 * / %x4D.61.79 ; "May", case-sensitive
3292 * / %x4A.75.6E ; "Jun", case-sensitive
3293 * / %x4A.75.6C ; "Jul", case-sensitive
3294 * / %x41.75.67 ; "Aug", case-sensitive
3295 * / %x53.65.70 ; "Sep", case-sensitive
3296 * / %x4F.63.74 ; "Oct", case-sensitive
3297 * / %x4E.6F.76 ; "Nov", case-sensitive
3298 * / %x44.65.63 ; "Dec", case-sensitive
3299 *
3300 * This array must be alphabetically sorted
3301 */
3302static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3303{
3304 if (*len < 3)
3305 return 0;
3306 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3307 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3308 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3309 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3310 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3311 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3312 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3313 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3314 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3315 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3316 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3317 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3318 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3319 default: return 0;
3320 }
3321 *len -= 3;
3322 *date += 3;
3323 return 1;
3324}
3325
3326/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3327 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3328 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3329 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3330 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3331 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3332 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3333 *
3334 * This array must be alphabetically sorted
3335 */
3336static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3337{
3338 if (*len < 6) /* Minimum length. */
3339 return 0;
3340 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3341 case STR2I3('M','o','n'):
3342 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3343 tm->tm_wday = 1;
3344 return 1;
3345 case STR2I3('T','u','e'):
3346 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3347 tm->tm_wday = 2;
3348 return 1;
3349 case STR2I3('W','e','d'):
3350 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3351 tm->tm_wday = 3;
3352 return 1;
3353 case STR2I3('T','h','u'):
3354 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3355 tm->tm_wday = 4;
3356 return 1;
3357 case STR2I3('F','r','i'):
3358 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3359 tm->tm_wday = 5;
3360 return 1;
3361 case STR2I3('S','a','t'):
3362 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3363 tm->tm_wday = 6;
3364 return 1;
3365 case STR2I3('S','u','n'):
3366 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3367 tm->tm_wday = 7;
3368 return 1;
3369 }
3370 return 0;
3371}
3372
3373/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3374static inline int parse_digit(const char **date, int *len, int *digit)
3375{
3376 if (*len < 1 || **date < '0' || **date > '9')
3377 return 0;
3378 *digit = (**date - '0');
3379 (*date)++;
3380 (*len)--;
3381 return 1;
3382}
3383
3384/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3385static inline int parse_2digit(const char **date, int *len, int *digit)
3386{
3387 int value;
3388
3389 RET0_UNLESS(parse_digit(date, len, &value));
3390 (*digit) = value * 10;
3391 RET0_UNLESS(parse_digit(date, len, &value));
3392 (*digit) += value;
3393
3394 return 1;
3395}
3396
3397/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3398static inline int parse_4digit(const char **date, int *len, int *digit)
3399{
3400 int value;
3401
3402 RET0_UNLESS(parse_digit(date, len, &value));
3403 (*digit) = value * 1000;
3404
3405 RET0_UNLESS(parse_digit(date, len, &value));
3406 (*digit) += value * 100;
3407
3408 RET0_UNLESS(parse_digit(date, len, &value));
3409 (*digit) += value * 10;
3410
3411 RET0_UNLESS(parse_digit(date, len, &value));
3412 (*digit) += value;
3413
3414 return 1;
3415}
3416
3417/* time-of-day = hour ":" minute ":" second
3418 * ; 00:00:00 - 23:59:60 (leap second)
3419 *
3420 * hour = 2DIGIT
3421 * minute = 2DIGIT
3422 * second = 2DIGIT
3423 */
3424static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3425{
3426 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3427 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3428 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3429 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3430 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3431 return 1;
3432}
3433
3434/* From RFC7231
3435 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3436 *
3437 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3438 * ; fixed length/zone/capitalization subset of the format
3439 * ; see Section 3.3 of [RFC5322]
3440 *
3441 *
3442 * date1 = day SP month SP year
3443 * ; e.g., 02 Jun 1982
3444 *
3445 * day = 2DIGIT
3446 * year = 4DIGIT
3447 *
3448 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3449 *
3450 * time-of-day = hour ":" minute ":" second
3451 * ; 00:00:00 - 23:59:60 (leap second)
3452 *
3453 * hour = 2DIGIT
3454 * minute = 2DIGIT
3455 * second = 2DIGIT
3456 *
3457 * DIGIT = decimal 0-9
3458 */
3459int parse_imf_date(const char *date, int len, struct tm *tm)
3460{
David Carlier327298c2016-11-20 10:42:38 +00003461 /* tm_gmtoff, if present, ought to be zero'ed */
3462 memset(tm, 0, sizeof(*tm));
3463
Thierry Fournier93127942016-01-20 18:49:45 +01003464 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3465 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3466 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3467 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3468 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3469 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3470 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3471 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3472 tm->tm_year -= 1900;
3473 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3474 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3475 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3476 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3477 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003478 return 1;
3479}
3480
3481/* From RFC7231
3482 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3483 *
3484 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3485 * date2 = day "-" month "-" 2DIGIT
3486 * ; e.g., 02-Jun-82
3487 *
3488 * day = 2DIGIT
3489 */
3490int parse_rfc850_date(const char *date, int len, struct tm *tm)
3491{
3492 int year;
3493
David Carlier327298c2016-11-20 10:42:38 +00003494 /* tm_gmtoff, if present, ought to be zero'ed */
3495 memset(tm, 0, sizeof(*tm));
3496
Thierry Fournier93127942016-01-20 18:49:45 +01003497 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3498 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3499 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3500 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3501 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3502 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3503 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3504
3505 /* year = 2DIGIT
3506 *
3507 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3508 * two-digit year, MUST interpret a timestamp that appears to be more
3509 * than 50 years in the future as representing the most recent year in
3510 * the past that had the same last two digits.
3511 */
3512 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3513
3514 /* expect SP */
3515 if (!parse_expect_char(&date, &len, ' ')) {
3516 /* Maybe we have the date with 4 digits. */
3517 RET0_UNLESS(parse_2digit(&date, &len, &year));
3518 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3519 /* expect SP */
3520 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3521 } else {
3522 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3523 * tm_year is the number of year since 1900, so for +1900, we
3524 * do nothing, and for +2000, we add 100.
3525 */
3526 if (tm->tm_year <= 60)
3527 tm->tm_year += 100;
3528 }
3529
3530 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3531 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3532 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3533 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003534
3535 return 1;
3536}
3537
3538/* From RFC7231
3539 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3540 *
3541 * asctime-date = day-name SP date3 SP time-of-day SP year
3542 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3543 * ; e.g., Jun 2
3544 *
3545 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3546 * whitespace in an HTTP-date beyond that specifically included as SP in
3547 * the grammar.
3548 */
3549int parse_asctime_date(const char *date, int len, struct tm *tm)
3550{
David Carlier327298c2016-11-20 10:42:38 +00003551 /* tm_gmtoff, if present, ought to be zero'ed */
3552 memset(tm, 0, sizeof(*tm));
3553
Thierry Fournier93127942016-01-20 18:49:45 +01003554 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3555 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3556 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3557 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3558
3559 /* expect SP and 1DIGIT or 2DIGIT */
3560 if (parse_expect_char(&date, &len, ' '))
3561 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3562 else
3563 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3564
3565 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3566 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3567 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3568 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3569 tm->tm_year -= 1900;
3570 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003571 return 1;
3572}
3573
3574/* From RFC7231
3575 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3576 *
3577 * HTTP-date = IMF-fixdate / obs-date
3578 * obs-date = rfc850-date / asctime-date
3579 *
3580 * parses an HTTP date in the RFC format and is accepted
3581 * alternatives. <date> is the strinf containing the date,
3582 * len is the len of the string. <tm> is filled with the
3583 * parsed time. We must considers this time as GMT.
3584 */
3585int parse_http_date(const char *date, int len, struct tm *tm)
3586{
3587 if (parse_imf_date(date, len, tm))
3588 return 1;
3589
3590 if (parse_rfc850_date(date, len, tm))
3591 return 1;
3592
3593 if (parse_asctime_date(date, len, tm))
3594 return 1;
3595
3596 return 0;
3597}
3598
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003599/* Dynamically allocates a string of the proper length to hold the formatted
3600 * output. NULL is returned on error. The caller is responsible for freeing the
3601 * memory area using free(). The resulting string is returned in <out> if the
3602 * pointer is not NULL. A previous version of <out> might be used to build the
3603 * new string, and it will be freed before returning if it is not NULL, which
3604 * makes it possible to build complex strings from iterative calls without
3605 * having to care about freeing intermediate values, as in the example below :
3606 *
3607 * memprintf(&err, "invalid argument: '%s'", arg);
3608 * ...
3609 * memprintf(&err, "parser said : <%s>\n", *err);
3610 * ...
3611 * free(*err);
3612 *
3613 * This means that <err> must be initialized to NULL before first invocation.
3614 * The return value also holds the allocated string, which eases error checking
3615 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003616 * passed instead and it will be ignored. The returned message will then also
3617 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003618 *
3619 * It is also convenient to use it without any free except the last one :
3620 * err = NULL;
3621 * if (!fct1(err)) report(*err);
3622 * if (!fct2(err)) report(*err);
3623 * if (!fct3(err)) report(*err);
3624 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003625 *
3626 * memprintf relies on memvprintf. This last version can be called from any
3627 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003628 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003629char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003630{
3631 va_list args;
3632 char *ret = NULL;
3633 int allocated = 0;
3634 int needed = 0;
3635
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003636 if (!out)
3637 return NULL;
3638
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003639 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003640 char buf1;
3641
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003642 /* vsnprintf() will return the required length even when the
3643 * target buffer is NULL. We do this in a loop just in case
3644 * intermediate evaluations get wrong.
3645 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003646 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003647 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003648 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003649 if (needed < allocated) {
3650 /* Note: on Solaris 8, the first iteration always
3651 * returns -1 if allocated is zero, so we force a
3652 * retry.
3653 */
3654 if (!allocated)
3655 needed = 0;
3656 else
3657 break;
3658 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003659
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003660 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003661 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003662 } while (ret);
3663
3664 if (needed < 0) {
3665 /* an error was encountered */
3666 free(ret);
3667 ret = NULL;
3668 }
3669
3670 if (out) {
3671 free(*out);
3672 *out = ret;
3673 }
3674
3675 return ret;
3676}
William Lallemand421f5b52012-02-06 18:15:57 +01003677
Christopher Faulet93a518f2017-10-24 11:25:33 +02003678char *memprintf(char **out, const char *format, ...)
3679{
3680 va_list args;
3681 char *ret = NULL;
3682
3683 va_start(args, format);
3684 ret = memvprintf(out, format, args);
3685 va_end(args);
3686
3687 return ret;
3688}
3689
Willy Tarreau21c705b2012-09-14 11:40:36 +02003690/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3691 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003692 * freed by the caller. It also supports being passed a NULL which results in the same
3693 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003694 * Example of use :
3695 * parse(cmd, &err); (callee: memprintf(&err, ...))
3696 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3697 * free(err);
3698 */
3699char *indent_msg(char **out, int level)
3700{
3701 char *ret, *in, *p;
3702 int needed = 0;
3703 int lf = 0;
3704 int lastlf = 0;
3705 int len;
3706
Willy Tarreau70eec382012-10-10 08:56:47 +02003707 if (!out || !*out)
3708 return NULL;
3709
Willy Tarreau21c705b2012-09-14 11:40:36 +02003710 in = *out - 1;
3711 while ((in = strchr(in + 1, '\n')) != NULL) {
3712 lastlf = in - *out;
3713 lf++;
3714 }
3715
3716 if (!lf) /* single line, no LF, return it as-is */
3717 return *out;
3718
3719 len = strlen(*out);
3720
3721 if (lf == 1 && lastlf == len - 1) {
3722 /* single line, LF at end, strip it and return as-is */
3723 (*out)[lastlf] = 0;
3724 return *out;
3725 }
3726
3727 /* OK now we have at least one LF, we need to process the whole string
3728 * as a multi-line string. What we'll do :
3729 * - prefix with an LF if there is none
3730 * - add <level> spaces before each line
3731 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3732 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3733 */
3734
3735 needed = 1 + level * (lf + 1) + len + 1;
3736 p = ret = malloc(needed);
3737 in = *out;
3738
3739 /* skip initial LFs */
3740 while (*in == '\n')
3741 in++;
3742
3743 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3744 while (*in) {
3745 *p++ = '\n';
3746 memset(p, ' ', level);
3747 p += level;
3748 do {
3749 *p++ = *in++;
3750 } while (*in && *in != '\n');
3751 if (*in)
3752 in++;
3753 }
3754 *p = 0;
3755
3756 free(*out);
3757 *out = ret;
3758
3759 return ret;
3760}
3761
Willy Tarreaua2c99112019-08-21 13:17:37 +02003762/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3763 * and end of lines replaced with <eol> if not 0. The first line to indent has
3764 * to be indicated in <first> (starts at zero), so that it is possible to skip
3765 * indenting the first line if it has to be appended after an existing message.
3766 * Empty strings are never indented, and NULL strings are considered empty both
3767 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3768 * character, non-zero otherwise.
3769 */
3770int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3771{
3772 int bol, lf;
3773 int pfxlen = pfx ? strlen(pfx) : 0;
3774
3775 if (!in)
3776 return 0;
3777
3778 bol = 1;
3779 lf = 0;
3780 while (*in) {
3781 if (bol && pfxlen) {
3782 if (first > 0)
3783 first--;
3784 else
3785 b_putblk(out, pfx, pfxlen);
3786 bol = 0;
3787 }
3788
3789 lf = (*in == '\n');
3790 bol |= lf;
3791 b_putchr(out, (lf && eol) ? eol : *in);
3792 in++;
3793 }
3794 return lf;
3795}
3796
Willy Tarreau9d22e562019-03-29 18:49:09 +01003797/* removes environment variable <name> from the environment as found in
3798 * environ. This is only provided as an alternative for systems without
3799 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003800 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003801 * <name> and to replace the matching pointers with the last pointer of
3802 * the array (since variables are not ordered).
3803 * It always returns 0 (success).
3804 */
3805int my_unsetenv(const char *name)
3806{
3807 extern char **environ;
3808 char **p = environ;
3809 int vars;
3810 int next;
3811 int len;
3812
3813 len = strlen(name);
3814 for (vars = 0; p[vars]; vars++)
3815 ;
3816 next = 0;
3817 while (next < vars) {
3818 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3819 next++;
3820 continue;
3821 }
3822 if (next < vars - 1)
3823 p[next] = p[vars - 1];
3824 p[--vars] = NULL;
3825 }
3826 return 0;
3827}
3828
Willy Tarreaudad36a32013-03-11 01:20:04 +01003829/* Convert occurrences of environment variables in the input string to their
3830 * corresponding value. A variable is identified as a series of alphanumeric
3831 * characters or underscores following a '$' sign. The <in> string must be
3832 * free()able. NULL returns NULL. The resulting string might be reallocated if
3833 * some expansion is made. Variable names may also be enclosed into braces if
3834 * needed (eg: to concatenate alphanum characters).
3835 */
3836char *env_expand(char *in)
3837{
3838 char *txt_beg;
3839 char *out;
3840 char *txt_end;
3841 char *var_beg;
3842 char *var_end;
3843 char *value;
3844 char *next;
3845 int out_len;
3846 int val_len;
3847
3848 if (!in)
3849 return in;
3850
3851 value = out = NULL;
3852 out_len = 0;
3853
3854 txt_beg = in;
3855 do {
3856 /* look for next '$' sign in <in> */
3857 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3858
3859 if (!*txt_end && !out) /* end and no expansion performed */
3860 return in;
3861
3862 val_len = 0;
3863 next = txt_end;
3864 if (*txt_end == '$') {
3865 char save;
3866
3867 var_beg = txt_end + 1;
3868 if (*var_beg == '{')
3869 var_beg++;
3870
3871 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003872 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003873 var_end++;
3874 }
3875
3876 next = var_end;
3877 if (*var_end == '}' && (var_beg > txt_end + 1))
3878 next++;
3879
3880 /* get value of the variable name at this location */
3881 save = *var_end;
3882 *var_end = '\0';
3883 value = getenv(var_beg);
3884 *var_end = save;
3885 val_len = value ? strlen(value) : 0;
3886 }
3887
Hubert Verstraete831962e2016-06-28 22:44:26 +02003888 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003889 if (txt_end > txt_beg) {
3890 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3891 out_len += txt_end - txt_beg;
3892 }
3893 if (val_len) {
3894 memcpy(out + out_len, value, val_len);
3895 out_len += val_len;
3896 }
3897 out[out_len] = 0;
3898 txt_beg = next;
3899 } while (*txt_beg);
3900
3901 /* here we know that <out> was allocated and that we don't need <in> anymore */
3902 free(in);
3903 return out;
3904}
3905
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003906
3907/* same as strstr() but case-insensitive and with limit length */
3908const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3909{
3910 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003911 unsigned int slen, plen;
3912 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003913
3914 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3915 return NULL;
3916
3917 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3918 return str1;
3919
3920 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3921 return NULL;
3922
3923 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3924 while (toupper(*start) != toupper(*str2)) {
3925 start++;
3926 slen--;
3927 tmp1++;
3928
3929 if (tmp1 >= len_str1)
3930 return NULL;
3931
3932 /* if pattern longer than string */
3933 if (slen < plen)
3934 return NULL;
3935 }
3936
3937 sptr = start;
3938 pptr = (char *)str2;
3939
3940 tmp2 = 0;
3941 while (toupper(*sptr) == toupper(*pptr)) {
3942 sptr++;
3943 pptr++;
3944 tmp2++;
3945
3946 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3947 return start;
3948 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3949 return NULL;
3950 }
3951 }
3952 return NULL;
3953}
3954
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003955/* This function read the next valid utf8 char.
3956 * <s> is the byte srray to be decode, <len> is its length.
3957 * The function returns decoded char encoded like this:
3958 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3959 * are the length read. The decoded character is stored in <c>.
3960 */
3961unsigned char utf8_next(const char *s, int len, unsigned int *c)
3962{
3963 const unsigned char *p = (unsigned char *)s;
3964 int dec;
3965 unsigned char code = UTF8_CODE_OK;
3966
3967 if (len < 1)
3968 return UTF8_CODE_OK;
3969
3970 /* Check the type of UTF8 sequence
3971 *
3972 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3973 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3974 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3975 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3976 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3977 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3978 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3979 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3980 */
3981 switch (*p) {
3982 case 0x00 ... 0x7f:
3983 *c = *p;
3984 return UTF8_CODE_OK | 1;
3985
3986 case 0x80 ... 0xbf:
3987 *c = *p;
3988 return UTF8_CODE_BADSEQ | 1;
3989
3990 case 0xc0 ... 0xdf:
3991 if (len < 2) {
3992 *c = *p;
3993 return UTF8_CODE_BADSEQ | 1;
3994 }
3995 *c = *p & 0x1f;
3996 dec = 1;
3997 break;
3998
3999 case 0xe0 ... 0xef:
4000 if (len < 3) {
4001 *c = *p;
4002 return UTF8_CODE_BADSEQ | 1;
4003 }
4004 *c = *p & 0x0f;
4005 dec = 2;
4006 break;
4007
4008 case 0xf0 ... 0xf7:
4009 if (len < 4) {
4010 *c = *p;
4011 return UTF8_CODE_BADSEQ | 1;
4012 }
4013 *c = *p & 0x07;
4014 dec = 3;
4015 break;
4016
4017 case 0xf8 ... 0xfb:
4018 if (len < 5) {
4019 *c = *p;
4020 return UTF8_CODE_BADSEQ | 1;
4021 }
4022 *c = *p & 0x03;
4023 dec = 4;
4024 break;
4025
4026 case 0xfc ... 0xfd:
4027 if (len < 6) {
4028 *c = *p;
4029 return UTF8_CODE_BADSEQ | 1;
4030 }
4031 *c = *p & 0x01;
4032 dec = 5;
4033 break;
4034
4035 case 0xfe ... 0xff:
4036 default:
4037 *c = *p;
4038 return UTF8_CODE_BADSEQ | 1;
4039 }
4040
4041 p++;
4042
4043 while (dec > 0) {
4044
4045 /* need 0x10 for the 2 first bits */
4046 if ( ( *p & 0xc0 ) != 0x80 )
4047 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4048
4049 /* add data at char */
4050 *c = ( *c << 6 ) | ( *p & 0x3f );
4051
4052 dec--;
4053 p++;
4054 }
4055
4056 /* Check ovelong encoding.
4057 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4058 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4059 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4060 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004061 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004062 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4063 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4064 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4065 code |= UTF8_CODE_OVERLONG;
4066
4067 /* Check invalid UTF8 range. */
4068 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4069 (*c >= 0xfffe && *c <= 0xffff))
4070 code |= UTF8_CODE_INVRANGE;
4071
4072 return code | ((p-(unsigned char *)s)&0x0f);
4073}
4074
Maxime de Roucydc887852016-05-13 23:52:54 +02004075/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4076 * On failure : return 0 and <err> filled with an error message.
4077 * The caller is responsible for freeing the <err> and <str> copy
4078 * memory area using free()
4079 */
4080int list_append_word(struct list *li, const char *str, char **err)
4081{
4082 struct wordlist *wl;
4083
4084 wl = calloc(1, sizeof(*wl));
4085 if (!wl) {
4086 memprintf(err, "out of memory");
4087 goto fail_wl;
4088 }
4089
4090 wl->s = strdup(str);
4091 if (!wl->s) {
4092 memprintf(err, "out of memory");
4093 goto fail_wl_s;
4094 }
4095
4096 LIST_ADDQ(li, &wl->list);
4097
4098 return 1;
4099
4100fail_wl_s:
4101 free(wl->s);
4102fail_wl:
4103 free(wl);
4104 return 0;
4105}
4106
Willy Tarreau37101052019-05-20 16:48:20 +02004107/* indicates if a memory location may safely be read or not. The trick consists
4108 * in performing a harmless syscall using this location as an input and letting
4109 * the operating system report whether it's OK or not. For this we have the
4110 * stat() syscall, which will return EFAULT when the memory location supposed
4111 * to contain the file name is not readable. If it is readable it will then
4112 * either return 0 if the area contains an existing file name, or -1 with
4113 * another code. This must not be abused, and some audit systems might detect
4114 * this as abnormal activity. It's used only for unsafe dumps.
4115 */
4116int may_access(const void *ptr)
4117{
4118 struct stat buf;
4119
4120 if (stat(ptr, &buf) == 0)
4121 return 1;
4122 if (errno == EFAULT)
4123 return 0;
4124 return 1;
4125}
4126
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004127/* print a string of text buffer to <out>. The format is :
4128 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4129 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4130 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4131 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004132int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004133{
4134 unsigned char c;
4135 int ptr = 0;
4136
4137 while (buf[ptr] && ptr < bsize) {
4138 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004139 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004140 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004141 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004142 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004143 }
4144 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004145 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004146 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004147 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004148 switch (c) {
4149 case ' ': c = ' '; break;
4150 case '\t': c = 't'; break;
4151 case '\n': c = 'n'; break;
4152 case '\r': c = 'r'; break;
4153 case '\e': c = 'e'; break;
4154 case '\\': c = '\\'; break;
4155 case '=': c = '='; break;
4156 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004157 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004158 }
4159 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004160 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004161 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004162 out->area[out->data++] = '\\';
4163 out->area[out->data++] = 'x';
4164 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4165 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004166 }
4167 ptr++;
4168 }
4169
4170 return ptr;
4171}
4172
4173/* print a buffer in hexa.
4174 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4175 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004176int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004177{
4178 unsigned char c;
4179 int ptr = 0;
4180
4181 while (ptr < bsize) {
4182 c = buf[ptr];
4183
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004184 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004185 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004186 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4187 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004188
4189 ptr++;
4190 }
4191 return ptr;
4192}
4193
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004194/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4195 * prepending each line with prefix <pfx>. The output is *not* initialized.
4196 * The output will not wrap pas the buffer's end so it is more optimal if the
4197 * caller makes sure the buffer is aligned first. A trailing zero will always
4198 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004199 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4200 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004201 */
Willy Tarreau37101052019-05-20 16:48:20 +02004202void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004203{
4204 const unsigned char *d = buf;
4205 int i, j, start;
4206
4207 d = (const unsigned char *)(((unsigned long)buf) & -16);
4208 start = ((unsigned long)buf) & 15;
4209
4210 for (i = 0; i < start + len; i += 16) {
4211 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4212
Willy Tarreau37101052019-05-20 16:48:20 +02004213 // 0: unchecked, 1: checked safe, 2: danger
4214 unsafe = !!unsafe;
4215 if (unsafe && !may_access(d + i))
4216 unsafe = 2;
4217
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004218 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004219 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004220 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004221 else if (unsafe > 1)
4222 chunk_strcat(out, "** ");
4223 else
4224 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004225
4226 if (j == 7)
4227 chunk_strcat(out, "- ");
4228 }
4229 chunk_strcat(out, " ");
4230 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004231 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004232 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004233 else if (unsafe > 1)
4234 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004235 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004236 chunk_appendf(out, "%c", d[i + j]);
4237 else
4238 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004239 }
4240 chunk_strcat(out, "\n");
4241 }
4242}
4243
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004244/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4245 * enclosed in brackets after the address itself, formatted on 14 chars
4246 * including the "0x" prefix. This is meant to be used as a prefix for code
4247 * areas. For example:
4248 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4249 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4250 * is emitted. A NULL <pfx> will be considered empty.
4251 */
4252void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4253{
4254 int ok = 0;
4255 int i;
4256
4257 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4258
4259 for (i = 0; i < n; i++) {
4260 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4261 ok = may_access(addr + i);
4262 if (ok)
4263 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4264 else
4265 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4266 }
4267}
4268
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004269/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4270 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4271 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4272 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4273 * lines are respected within the limit of 70 output chars. Lines that are
4274 * continuation of a previous truncated line begin with "+" instead of " "
4275 * after the offset. The new pointer is returned.
4276 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004277int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004278 int *line, int ptr)
4279{
4280 int end;
4281 unsigned char c;
4282
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004283 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004284 if (end > out->size)
4285 return ptr;
4286
4287 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4288
4289 while (ptr < len && ptr < bsize) {
4290 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004291 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004292 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004293 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004294 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004295 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004296 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004297 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004298 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004299 switch (c) {
4300 case '\t': c = 't'; break;
4301 case '\n': c = 'n'; break;
4302 case '\r': c = 'r'; break;
4303 case '\e': c = 'e'; break;
4304 case '\\': c = '\\'; break;
4305 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004306 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004307 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004308 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004309 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004310 out->area[out->data++] = '\\';
4311 out->area[out->data++] = 'x';
4312 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4313 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004314 }
4315 if (buf[ptr++] == '\n') {
4316 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004317 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004318 *line = ptr;
4319 return ptr;
4320 }
4321 }
4322 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004323 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004324 return ptr;
4325}
4326
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004327/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004328 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4329 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004330 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004331void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4332 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004333{
Willy Tarreau73459792017-04-11 07:58:08 +02004334 unsigned int i;
4335 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004336
4337 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4338 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004339 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004340 for (j = 0; j < 8; j++) {
4341 if (b + j >= 0 && b + j < len)
4342 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4343 else
4344 fprintf(out, " ");
4345 }
4346
4347 if (b + j >= 0 && b + j < len)
4348 fputc('-', out);
4349 else
4350 fputc(' ', out);
4351
4352 for (j = 8; j < 16; j++) {
4353 if (b + j >= 0 && b + j < len)
4354 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4355 else
4356 fprintf(out, " ");
4357 }
4358
4359 fprintf(out, " ");
4360 for (j = 0; j < 16; j++) {
4361 if (b + j >= 0 && b + j < len) {
4362 if (isprint((unsigned char)buf[b + j]))
4363 fputc((unsigned char)buf[b + j], out);
4364 else
4365 fputc('.', out);
4366 }
4367 else
4368 fputc(' ', out);
4369 }
4370 fputc('\n', out);
4371 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004372}
4373
Willy Tarreaubb869862020-04-16 10:52:41 +02004374/* Tries to report the executable path name on platforms supporting this. If
4375 * not found or not possible, returns NULL.
4376 */
4377const char *get_exec_path()
4378{
4379 const char *ret = NULL;
4380
4381#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4382 long execfn = getauxval(AT_EXECFN);
4383
4384 if (execfn && execfn != ENOENT)
4385 ret = (const char *)execfn;
4386#endif
4387 return ret;
4388}
4389
Willy Tarreau109201f2020-03-04 10:31:58 +01004390#ifdef __ELF__
Willy Tarreau9133e482020-03-04 10:19:36 +01004391/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4392 * also returns the symbol size in <size>, otherwise returns 0 there.
4393 */
4394static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4395{
4396 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004397#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004398 const ElfW(Sym) *sym;
4399
4400 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4401 if (ret)
4402 *size = sym ? sym->st_size : 0;
4403#else
4404 ret = dladdr(addr, dli);
4405 *size = 0;
4406#endif
4407 return ret;
4408}
4409#endif
4410
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004411/* Tries to append to buffer <buf> some indications about the symbol at address
4412 * <addr> using the following form:
4413 * lib:+0xoffset (unresolvable address from lib's base)
4414 * main+0xoffset (unresolvable address from main (+/-))
4415 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4416 * name (resolved exact exec address)
4417 * lib:name (resolved exact lib address)
4418 * name+0xoffset/0xsize (resolved address within exec symbol)
4419 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4420 *
4421 * The file name (lib or executable) is limited to what lies between the last
4422 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4423 * the output if not null. The file is not dumped when it's the same as the one
Willy Tarreau109201f2020-03-04 10:31:58 +01004424 * that contains the "main" symbol, or when __ELF__ is not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004425 *
4426 * The symbol's base address is returned, or NULL when unresolved, in order to
4427 * allow the caller to match it against known ones.
4428 */
4429void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
4430{
4431 const struct {
4432 const void *func;
4433 const char *name;
4434 } fcts[] = {
4435 { .func = process_stream, .name = "process_stream" },
4436 { .func = task_run_applet, .name = "task_run_applet" },
4437 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4438 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4439 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4440 { .func = listener_accept, .name = "listener_accept" },
4441 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4442 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4443#ifdef USE_LUA
4444 { .func = hlua_process_task, .name = "hlua_process_task" },
4445#endif
4446#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4447 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4448 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4449#endif
4450 };
4451
Willy Tarreau109201f2020-03-04 10:31:58 +01004452#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004453 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004454 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004455 const char *fname, *p;
4456#endif
4457 int i;
4458
4459 if (pfx)
4460 chunk_appendf(buf, "%s", pfx);
4461
4462 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4463 if (addr == fcts[i].func) {
4464 chunk_appendf(buf, "%s", fcts[i].name);
4465 return addr;
4466 }
4467 }
4468
Willy Tarreau109201f2020-03-04 10:31:58 +01004469#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004470 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004471 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004472 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004473
4474 /* 1. prefix the library name if it's not the same object as the one
4475 * that contains the main function. The name is picked between last '/'
4476 * and first following '.'.
4477 */
4478 if (!dladdr(main, &dli_main))
4479 dli_main.dli_fbase = NULL;
4480
4481 if (dli_main.dli_fbase != dli.dli_fbase) {
4482 fname = dli.dli_fname;
4483 p = strrchr(fname, '/');
4484 if (p++)
4485 fname = p;
4486 p = strchr(fname, '.');
4487 if (!p)
4488 p = fname + strlen(fname);
4489
4490 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4491 }
4492
4493 /* 2. symbol name */
4494 if (dli.dli_sname) {
4495 /* known, dump it and return symbol's address (exact or relative) */
4496 chunk_appendf(buf, "%s", dli.dli_sname);
4497 if (addr != dli.dli_saddr) {
4498 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004499 if (size)
4500 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004501 }
4502 return dli.dli_saddr;
4503 }
4504 else if (dli_main.dli_fbase != dli.dli_fbase) {
4505 /* unresolved symbol from a known library, report relative offset */
4506 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4507 return NULL;
4508 }
Willy Tarreau109201f2020-03-04 10:31:58 +01004509#endif /* __ELF__ */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004510 unknown:
4511 /* unresolved symbol from the main file, report relative offset to main */
4512 if ((void*)addr < (void*)main)
4513 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4514 else
4515 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4516 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004517}
4518
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004519/*
4520 * Allocate an array of unsigned int with <nums> as address from <str> string
4521 * made of integer sepereated by dot characters.
4522 *
4523 * First, initializes the value with <sz> as address to 0 and initializes the
4524 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4525 * address updating <sz> pointed value to the size of this array.
4526 *
4527 * Returns 1 if succeeded, 0 if not.
4528 */
4529int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4530{
4531 unsigned int *n;
4532 const char *s, *end;
4533
4534 s = str;
4535 *sz = 0;
4536 end = str + strlen(str);
4537 *nums = n = NULL;
4538
4539 while (1) {
4540 unsigned int r;
4541
4542 if (s >= end)
4543 break;
4544
4545 r = read_uint(&s, end);
4546 /* Expected characters after having read an uint: '\0' or '.',
4547 * if '.', must not be terminal.
4548 */
4549 if (*s != '\0'&& (*s++ != '.' || s == end))
4550 return 0;
4551
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004552 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004553 if (!n)
4554 return 0;
4555
4556 n[(*sz)++] = r;
4557 }
4558 *nums = n;
4559
4560 return 1;
4561}
4562
Willy Tarreau4d589e72019-08-23 19:02:26 +02004563
4564/* returns the number of bytes needed to encode <v> as a varint. An inline
4565 * version exists for use with constants (__varint_bytes()).
4566 */
4567int varint_bytes(uint64_t v)
4568{
4569 int len = 1;
4570
4571 if (v >= 240) {
4572 v = (v - 240) >> 4;
4573 while (1) {
4574 len++;
4575 if (v < 128)
4576 break;
4577 v = (v - 128) >> 7;
4578 }
4579 }
4580 return len;
4581}
4582
Willy Tarreau52bf8392020-03-08 00:42:37 +01004583
4584/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004585static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004586
4587/* This is a thread-safe implementation of xoroshiro128** described below:
4588 * http://prng.di.unimi.it/
4589 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4590 * supports fast jumps and passes all common quality tests. It is thread-safe,
4591 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4592 * local lock on other ones.
4593 */
4594uint64_t ha_random64()
4595{
4596 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004597 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4598 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004599
4600#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4601 static HA_SPINLOCK_T rand_lock;
4602
4603 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4604#endif
4605
4606 old[0] = ha_random_state[0];
4607 old[1] = ha_random_state[1];
4608
4609#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4610 do {
4611#endif
4612 result = rotl64(old[0] * 5, 7) * 9;
4613 new[1] = old[0] ^ old[1];
4614 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4615 new[1] = rotl64(new[1], 37); // c
4616
4617#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4618 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4619#else
4620 ha_random_state[0] = new[0];
4621 ha_random_state[1] = new[1];
4622#if defined(USE_THREAD)
4623 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4624#endif
4625#endif
4626 return result;
4627}
4628
4629/* seeds the random state using up to <len> bytes from <seed>, starting with
4630 * the first non-zero byte.
4631 */
4632void ha_random_seed(const unsigned char *seed, size_t len)
4633{
4634 size_t pos;
4635
4636 /* the seed must not be all zeroes, so we pre-fill it with alternating
4637 * bits and overwrite part of them with the block starting at the first
4638 * non-zero byte from the seed.
4639 */
4640 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4641
4642 for (pos = 0; pos < len; pos++)
4643 if (seed[pos] != 0)
4644 break;
4645
4646 if (pos == len)
4647 return;
4648
4649 seed += pos;
4650 len -= pos;
4651
4652 if (len > sizeof(ha_random_state))
4653 len = sizeof(ha_random_state);
4654
4655 memcpy(ha_random_state, seed, len);
4656}
4657
4658/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4659 * and is equivalent to calling ha_random64() as many times. It is used to
4660 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4661 * different generators (i.e. different processes after a fork). The <dist>
4662 * argument is the distance to jump to and is used in a loop so it rather not
4663 * be too large if the processing time is a concern.
4664 *
4665 * BEWARE: this function is NOT thread-safe and must not be called during
4666 * concurrent accesses to ha_random64().
4667 */
4668void ha_random_jump96(uint32_t dist)
4669{
4670 while (dist--) {
4671 uint64_t s0 = 0;
4672 uint64_t s1 = 0;
4673 int b;
4674
4675 for (b = 0; b < 64; b++) {
4676 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4677 s0 ^= ha_random_state[0];
4678 s1 ^= ha_random_state[1];
4679 }
4680 ha_random64();
4681 }
4682
4683 for (b = 0; b < 64; b++) {
4684 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4685 s0 ^= ha_random_state[0];
4686 s1 ^= ha_random_state[1];
4687 }
4688 ha_random64();
4689 }
4690 ha_random_state[0] = s0;
4691 ha_random_state[1] = s1;
4692 }
4693}
4694
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004695/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4696 * bytes large.
4697 */
4698void ha_generate_uuid(struct buffer *output)
4699{
4700 uint32_t rnd[4];
4701 uint64_t last;
4702
4703 last = ha_random64();
4704 rnd[0] = last;
4705 rnd[1] = last >> 32;
4706
4707 last = ha_random64();
4708 rnd[2] = last;
4709 rnd[3] = last >> 32;
4710
4711 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4712 rnd[0],
4713 rnd[1] & 0xFFFF,
4714 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4715 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4716 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4717}
4718
4719
Willy Tarreaubaaee002006-06-26 02:48:02 +02004720/*
4721 * Local variables:
4722 * c-indent-level: 8
4723 * c-basic-offset: 8
4724 * End:
4725 */