blob: d948993b254256d97fe185dfb012aceceb5a2212 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010019#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020020#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020022#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020023#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <stdlib.h>
25#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010026#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020027#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010028#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020029#include <sys/stat.h>
30#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010031#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netinet/in.h>
33#include <arpa/inet.h>
34
Willy Tarreau30053062020-08-20 16:39:14 +020035#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
36#include <sys/auxv.h>
37#endif
38
Willy Tarreau48fbcae2020-06-03 18:09:46 +020039#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020040#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020041
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020042#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020043#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020044#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020045#include <haproxy/dns.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020046#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020047#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020048#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020049#include <haproxy/namespace.h>
Willy 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
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200864 * the address when cast to sockaddr_in and the address family is
865 * AF_CUST_EXISTING_FD.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100866 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100867struct 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 +0100868{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100869 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100870 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100871 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100872 char *port1, *port2;
873 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200874 int abstract = 0;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200875 int is_udp = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100876
877 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200878 if (fqdn)
879 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200880
Willy Tarreaudad36a32013-03-11 01:20:04 +0100881 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100882 if (str2 == NULL) {
883 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100884 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100885 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200886
Willy Tarreau9f69f462015-09-08 16:01:25 +0200887 if (!*str2) {
888 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
889 goto out;
890 }
891
Willy Tarreau24709282013-03-10 21:32:12 +0100892 memset(&ss, 0, sizeof(ss));
893
894 if (strncmp(str2, "unix@", 5) == 0) {
895 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200896 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100897 ss.ss_family = AF_UNIX;
898 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200899 else if (strncmp(str2, "abns@", 5) == 0) {
900 str2 += 5;
901 abstract = 1;
902 ss.ss_family = AF_UNIX;
903 }
Willy Tarreau24709282013-03-10 21:32:12 +0100904 else if (strncmp(str2, "ipv4@", 5) == 0) {
905 str2 += 5;
906 ss.ss_family = AF_INET;
907 }
908 else if (strncmp(str2, "ipv6@", 5) == 0) {
909 str2 += 5;
910 ss.ss_family = AF_INET6;
911 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200912 else if (strncmp(str2, "udp4@", 5) == 0) {
913 str2 += 5;
914 ss.ss_family = AF_INET;
915 is_udp = 1;
916 }
917 else if (strncmp(str2, "udp6@", 5) == 0) {
918 str2 += 5;
919 ss.ss_family = AF_INET6;
920 is_udp = 1;
921 }
922 else if (strncmp(str2, "udp@", 4) == 0) {
923 str2 += 4;
924 ss.ss_family = AF_UNSPEC;
925 is_udp = 1;
926 }
Willy Tarreau24709282013-03-10 21:32:12 +0100927 else if (*str2 == '/') {
928 ss.ss_family = AF_UNIX;
929 }
930 else
931 ss.ss_family = AF_UNSPEC;
932
William Lallemand2fe7dd02018-09-11 16:51:29 +0200933 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
934 char *endptr;
935
936 str2 += 9;
937
938 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100939 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200940
941 if (!*str2 || *endptr) {
942 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
943 goto out;
944 }
945
946 ss.ss_family = AF_CUST_SOCKPAIR;
947
948 }
949 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100950 char *endptr;
951
952 str2 += 3;
953 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100954 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100955
956 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100957 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100958 goto out;
959 }
960
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200961 /* we return AF_CUST_EXISTING_FD if we use a file descriptor number */
962 ss.ss_family = AF_CUST_EXISTING_FD;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100963 }
964 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200965 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100966 int prefix_path_len;
967 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200968 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100969
970 /* complete unix socket path name during startup or soft-restart is
971 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
972 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200973 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200974 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +0100975 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100976
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200977 adr_len = strlen(str2);
978 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100979 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
980 goto out;
981 }
982
Willy Tarreauccfccef2014-05-10 01:49:15 +0200983 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200984 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200985 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200986 memcpy(un->sun_path, pfx, prefix_path_len);
987 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100988 }
Willy Tarreau24709282013-03-10 21:32:12 +0100989 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100990 char *end = str2 + strlen(str2);
991 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200992
mildisff5d5102015-10-26 18:50:08 +0100993 /* search for : or ] whatever comes first */
994 for (chr = end-1; chr > str2; chr--) {
995 if (*chr == ']' || *chr == ':')
996 break;
997 }
998
999 if (*chr == ':') {
1000 /* Found a colon before a closing-bracket, must be a port separator.
1001 * This guarantee backward compatibility.
1002 */
1003 *chr++ = '\0';
1004 port1 = chr;
1005 }
1006 else {
1007 /* Either no colon and no closing-bracket
1008 * or directly ending with a closing-bracket.
1009 * However, no port.
1010 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001011 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001012 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001013
Willy Tarreau90807112020-02-25 08:16:33 +01001014 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001015 port2 = strchr(port1, '-');
1016 if (port2)
1017 *port2++ = '\0';
1018 else
1019 port2 = port1;
1020 portl = atoi(port1);
1021 porth = atoi(port2);
1022 porta = portl;
1023 }
1024 else if (*port1 == '-') { /* negative offset */
1025 portl = atoi(port1 + 1);
1026 porta = -portl;
1027 }
1028 else if (*port1 == '+') { /* positive offset */
1029 porth = atoi(port1 + 1);
1030 porta = porth;
1031 }
1032 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001033 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001034 goto out;
1035 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001036
1037 /* first try to parse the IP without resolving. If it fails, it
1038 * tells us we need to keep a copy of the FQDN to resolve later
1039 * and to enable DNS. In this case we can proceed if <fqdn> is
1040 * set or if resolve is set, otherwise it's an error.
1041 */
1042 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001043 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001044 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1045 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1046 goto out;
1047 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001048
Willy Tarreauceccdd72016-11-02 22:27:10 +01001049 if (fqdn) {
1050 if (str2 != back)
1051 memmove(back, str2, strlen(str2) + 1);
1052 *fqdn = back;
1053 back = NULL;
1054 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001055 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001056 set_host_port(&ss, porta);
Emeric Brun3835c0d2020-07-07 09:46:09 +02001057 if (is_udp) {
1058 if (ss.ss_family == AF_INET6)
1059 ss.ss_family = AF_CUST_UDP6;
1060 else
1061 ss.ss_family = AF_CUST_UDP4;
1062 }
1063
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001064 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001065
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001066 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001067 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001068 if (port)
1069 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001070 if (low)
1071 *low = portl;
1072 if (high)
1073 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001074 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001075 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001076}
1077
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001078/* converts <str> to a struct in_addr containing a network mask. It can be
1079 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001080 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001081 */
1082int str2mask(const char *str, struct in_addr *mask)
1083{
1084 if (strchr(str, '.') != NULL) { /* dotted notation */
1085 if (!inet_pton(AF_INET, str, mask))
1086 return 0;
1087 }
1088 else { /* mask length */
1089 char *err;
1090 unsigned long len = strtol(str, &err, 10);
1091
1092 if (!*str || (err && *err) || (unsigned)len > 32)
1093 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001094
1095 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001096 }
1097 return 1;
1098}
1099
Tim Duesterhus47185172018-01-25 16:24:49 +01001100/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001101 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001102 * if the conversion succeeds otherwise zero.
1103 */
1104int str2mask6(const char *str, struct in6_addr *mask)
1105{
1106 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1107 if (!inet_pton(AF_INET6, str, mask))
1108 return 0;
1109 }
1110 else { /* mask length */
1111 char *err;
1112 unsigned long len = strtol(str, &err, 10);
1113
1114 if (!*str || (err && *err) || (unsigned)len > 128)
1115 return 0;
1116
1117 len2mask6(len, mask);
1118 }
1119 return 1;
1120}
1121
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001122/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1123 * succeeds otherwise zero.
1124 */
1125int cidr2dotted(int cidr, struct in_addr *mask) {
1126
1127 if (cidr < 0 || cidr > 32)
1128 return 0;
1129
1130 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1131 return 1;
1132}
1133
Thierry Fournier70473a52016-02-17 17:12:14 +01001134/* Convert mask from bit length form to in_addr form.
1135 * This function never fails.
1136 */
1137void len2mask4(int len, struct in_addr *addr)
1138{
1139 if (len >= 32) {
1140 addr->s_addr = 0xffffffff;
1141 return;
1142 }
1143 if (len <= 0) {
1144 addr->s_addr = 0x00000000;
1145 return;
1146 }
1147 addr->s_addr = 0xffffffff << (32 - len);
1148 addr->s_addr = htonl(addr->s_addr);
1149}
1150
1151/* Convert mask from bit length form to in6_addr form.
1152 * This function never fails.
1153 */
1154void len2mask6(int len, struct in6_addr *addr)
1155{
1156 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1157 len -= 32;
1158 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1159 len -= 32;
1160 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1161 len -= 32;
1162 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1163}
1164
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001165/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001166 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001167 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001168 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001169 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1170 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001171int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001172{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001173 __label__ out_free, out_err;
1174 char *c, *s;
1175 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001176
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001177 s = strdup(str);
1178 if (!s)
1179 return 0;
1180
Willy Tarreaubaaee002006-06-26 02:48:02 +02001181 memset(mask, 0, sizeof(*mask));
1182 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001183
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001184 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001185 *c++ = '\0';
1186 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001187 if (!str2mask(c, mask))
1188 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001189 }
1190 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001191 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001192 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001193 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001194 struct hostent *he;
1195
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001196 if (!resolve)
1197 goto out_err;
1198
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001199 if ((he = gethostbyname(s)) == NULL) {
1200 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001201 }
1202 else
1203 *addr = *(struct in_addr *) *(he->h_addr_list);
1204 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001205
1206 ret_val = 1;
1207 out_free:
1208 free(s);
1209 return ret_val;
1210 out_err:
1211 ret_val = 0;
1212 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001213}
1214
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001215
1216/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001217 * converts <str> to two struct in6_addr* which must be pre-allocated.
1218 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001219 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001220 * Returns 1 if OK, 0 if error.
1221 */
1222int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1223{
1224 char *c, *s;
1225 int ret_val = 0;
1226 char *err;
1227 unsigned long len = 128;
1228
1229 s = strdup(str);
1230 if (!s)
1231 return 0;
1232
1233 memset(mask, 0, sizeof(*mask));
1234 memset(addr, 0, sizeof(*addr));
1235
1236 if ((c = strrchr(s, '/')) != NULL) {
1237 *c++ = '\0'; /* c points to the mask */
1238 if (!*c)
1239 goto out_free;
1240
1241 len = strtoul(c, &err, 10);
1242 if ((err && *err) || (unsigned)len > 128)
1243 goto out_free;
1244 }
1245 *mask = len; /* OK we have a valid mask in <len> */
1246
1247 if (!inet_pton(AF_INET6, s, addr))
1248 goto out_free;
1249
1250 ret_val = 1;
1251 out_free:
1252 free(s);
1253 return ret_val;
1254}
1255
1256
1257/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001258 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001259 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001260int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001261{
1262 int saw_digit, octets, ch;
1263 u_char tmp[4], *tp;
1264 const char *cp = addr;
1265
1266 saw_digit = 0;
1267 octets = 0;
1268 *(tp = tmp) = 0;
1269
1270 while (*addr) {
1271 unsigned char digit = (ch = *addr++) - '0';
1272 if (digit > 9 && ch != '.')
1273 break;
1274 if (digit <= 9) {
1275 u_int new = *tp * 10 + digit;
1276 if (new > 255)
1277 return 0;
1278 *tp = new;
1279 if (!saw_digit) {
1280 if (++octets > 4)
1281 return 0;
1282 saw_digit = 1;
1283 }
1284 } else if (ch == '.' && saw_digit) {
1285 if (octets == 4)
1286 return 0;
1287 *++tp = 0;
1288 saw_digit = 0;
1289 } else
1290 return 0;
1291 }
1292
1293 if (octets < 4)
1294 return 0;
1295
1296 memcpy(&dst->s_addr, tmp, 4);
1297 return addr-cp-1;
1298}
1299
1300/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001301 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001302 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001303 * the hostname. Actually only http and https are supported. <out> can be NULL.
1304 * This function returns the consumed length. It is useful if you parse complete
1305 * url like http://host:port/path, because the consumed length corresponds to
1306 * the first character of the path. If the conversion fails, it returns -1.
1307 *
1308 * This function tries to resolve the DNS name if haproxy is in starting mode.
1309 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001310 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001311int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001312{
1313 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001314 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001315 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001316 unsigned long long int http_code = 0;
1317 int default_port;
1318 struct hostent *he;
1319 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001320
1321 /* Firstly, try to find :// pattern */
1322 while (curr < url+ulen && url_code != 0x3a2f2f) {
1323 url_code = ((url_code & 0xffff) << 8);
1324 url_code += (unsigned char)*curr++;
1325 }
1326
1327 /* Secondly, if :// pattern is found, verify parsed stuff
1328 * before pattern is matching our http pattern.
1329 * If so parse ip address and port in uri.
1330 *
1331 * WARNING: Current code doesn't support dynamic async dns resolver.
1332 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001333 if (url_code != 0x3a2f2f)
1334 return -1;
1335
1336 /* Copy scheme, and utrn to lower case. */
1337 while (cp < curr - 3)
1338 http_code = (http_code << 8) + *cp++;
1339 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001340
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001341 /* HTTP or HTTPS url matching */
1342 if (http_code == 0x2020202068747470ULL) {
1343 default_port = 80;
1344 if (out)
1345 out->scheme = SCH_HTTP;
1346 }
1347 else if (http_code == 0x2020206874747073ULL) {
1348 default_port = 443;
1349 if (out)
1350 out->scheme = SCH_HTTPS;
1351 }
1352 else
1353 return -1;
1354
1355 /* If the next char is '[', the host address is IPv6. */
1356 if (*curr == '[') {
1357 curr++;
1358
1359 /* Check trash size */
1360 if (trash.size < ulen)
1361 return -1;
1362
1363 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001364 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001365 for (end = curr;
1366 end < url + ulen && *end != ']';
1367 end++, p++)
1368 *p = *end;
1369 if (*end != ']')
1370 return -1;
1371 *p = '\0';
1372
1373 /* Update out. */
1374 if (out) {
1375 out->host = curr;
1376 out->host_len = end - curr;
1377 }
1378
1379 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001380 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001381 return -1;
1382 end++;
1383
1384 /* Decode port. */
1385 if (*end == ':') {
1386 end++;
1387 default_port = read_uint(&end, url + ulen);
1388 }
1389 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1390 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1391 return end - url;
1392 }
1393 else {
1394 /* We are looking for IP address. If you want to parse and
1395 * resolve hostname found in url, you can use str2sa_range(), but
1396 * be warned this can slow down global daemon performances
1397 * while handling lagging dns responses.
1398 */
1399 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1400 if (ret) {
1401 /* Update out. */
1402 if (out) {
1403 out->host = curr;
1404 out->host_len = ret;
1405 }
1406
1407 curr += ret;
1408
1409 /* Decode port. */
1410 if (*curr == ':') {
1411 curr++;
1412 default_port = read_uint(&curr, url + ulen);
1413 }
1414 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1415
1416 /* Set family. */
1417 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1418 return curr - url;
1419 }
1420 else if (global.mode & MODE_STARTING) {
1421 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1422 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001423 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001424
1425 /* look for : or / or end */
1426 for (end = curr;
1427 end < url + ulen && *end != '/' && *end != ':';
1428 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001429 memcpy(trash.area, curr, end - curr);
1430 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001431
1432 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001433 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001434 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001435 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001436
1437 /* Update out. */
1438 if (out) {
1439 out->host = curr;
1440 out->host_len = end - curr;
1441 }
1442
1443 /* Decode port. */
1444 if (*end == ':') {
1445 end++;
1446 default_port = read_uint(&end, url + ulen);
1447 }
1448
1449 /* Copy IP address, set port and family. */
1450 switch (he->h_addrtype) {
1451 case AF_INET:
1452 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1453 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1454 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1455 return end - url;
1456
1457 case AF_INET6:
1458 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1459 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1460 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1461 return end - url;
1462 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001463 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001464 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001465 return -1;
1466}
1467
Willy Tarreau631f01c2011-09-05 00:36:48 +02001468/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1469 * address family is returned so that it's easy for the caller to adapt to the
1470 * output format. Zero is returned if the address family is not supported. -1
1471 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1472 * supported.
1473 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001474int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001475{
1476
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001477 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001478
1479 if (size < 5)
1480 return 0;
1481 *str = '\0';
1482
1483 switch (addr->ss_family) {
1484 case AF_INET:
1485 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1486 break;
1487 case AF_INET6:
1488 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1489 break;
1490 case AF_UNIX:
1491 memcpy(str, "unix", 5);
1492 return addr->ss_family;
1493 default:
1494 return 0;
1495 }
1496
1497 if (inet_ntop(addr->ss_family, ptr, str, size))
1498 return addr->ss_family;
1499
1500 /* failed */
1501 return -1;
1502}
1503
Simon Horman75ab8bd2014-06-16 09:39:41 +09001504/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1505 * address family is returned so that it's easy for the caller to adapt to the
1506 * output format. Zero is returned if the address family is not supported. -1
1507 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1508 * supported.
1509 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001510int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001511{
1512
1513 uint16_t port;
1514
1515
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001516 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001517 return 0;
1518 *str = '\0';
1519
1520 switch (addr->ss_family) {
1521 case AF_INET:
1522 port = ((struct sockaddr_in *)addr)->sin_port;
1523 break;
1524 case AF_INET6:
1525 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1526 break;
1527 case AF_UNIX:
1528 memcpy(str, "unix", 5);
1529 return addr->ss_family;
1530 default:
1531 return 0;
1532 }
1533
1534 snprintf(str, size, "%u", ntohs(port));
1535 return addr->ss_family;
1536}
1537
Willy Tarreau16e01562016-08-09 16:46:18 +02001538/* check if the given address is local to the system or not. It will return
1539 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1540 * it is. We don't want to iterate over all interfaces for this (and it is not
1541 * portable). So instead we try to bind in UDP to this address on a free non
1542 * privileged port and to connect to the same address, port 0 (connect doesn't
1543 * care). If it succeeds, we own the address. Note that non-inet addresses are
1544 * considered local since they're most likely AF_UNIX.
1545 */
1546int addr_is_local(const struct netns_entry *ns,
1547 const struct sockaddr_storage *orig)
1548{
1549 struct sockaddr_storage addr;
1550 int result;
1551 int fd;
1552
1553 if (!is_inet_addr(orig))
1554 return 1;
1555
1556 memcpy(&addr, orig, sizeof(addr));
1557 set_host_port(&addr, 0);
1558
1559 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1560 if (fd < 0)
1561 return -1;
1562
1563 result = -1;
1564 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1565 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1566 result = 0; // fail, non-local address
1567 else
1568 result = 1; // success, local address
1569 }
1570 else {
1571 if (errno == EADDRNOTAVAIL)
1572 result = 0; // definitely not local :-)
1573 }
1574 close(fd);
1575
1576 return result;
1577}
1578
Willy Tarreaubaaee002006-06-26 02:48:02 +02001579/* will try to encode the string <string> replacing all characters tagged in
1580 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1581 * prefixed by <escape>, and will store the result between <start> (included)
1582 * and <stop> (excluded), and will always terminate the string with a '\0'
1583 * before <stop>. The position of the '\0' is returned if the conversion
1584 * completes. If bytes are missing between <start> and <stop>, then the
1585 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1586 * cannot even be stored so we return <start> without writing the 0.
1587 * The input string must also be zero-terminated.
1588 */
1589const char hextab[16] = "0123456789ABCDEF";
1590char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001591 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001592 const char *string)
1593{
1594 if (start < stop) {
1595 stop--; /* reserve one byte for the final '\0' */
1596 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001597 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001598 *start++ = *string;
1599 else {
1600 if (start + 3 >= stop)
1601 break;
1602 *start++ = escape;
1603 *start++ = hextab[(*string >> 4) & 15];
1604 *start++ = hextab[*string & 15];
1605 }
1606 string++;
1607 }
1608 *start = '\0';
1609 }
1610 return start;
1611}
1612
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001613/*
1614 * Same behavior as encode_string() above, except that it encodes chunk
1615 * <chunk> instead of a string.
1616 */
1617char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001618 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001619 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001620{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001621 char *str = chunk->area;
1622 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001623
1624 if (start < stop) {
1625 stop--; /* reserve one byte for the final '\0' */
1626 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001627 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001628 *start++ = *str;
1629 else {
1630 if (start + 3 >= stop)
1631 break;
1632 *start++ = escape;
1633 *start++ = hextab[(*str >> 4) & 15];
1634 *start++ = hextab[*str & 15];
1635 }
1636 str++;
1637 }
1638 *start = '\0';
1639 }
1640 return start;
1641}
1642
Dragan Dosen0edd1092016-02-12 13:23:02 +01001643/*
1644 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001645 * character. The input <string> must be zero-terminated. The result will
1646 * be stored between <start> (included) and <stop> (excluded). This
1647 * function will always try to terminate the resulting string with a '\0'
1648 * before <stop>, and will return its position if the conversion
1649 * completes.
1650 */
1651char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001652 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001653 const char *string)
1654{
1655 if (start < stop) {
1656 stop--; /* reserve one byte for the final '\0' */
1657 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001658 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001659 *start++ = *string;
1660 else {
1661 if (start + 2 >= stop)
1662 break;
1663 *start++ = escape;
1664 *start++ = *string;
1665 }
1666 string++;
1667 }
1668 *start = '\0';
1669 }
1670 return start;
1671}
1672
1673/*
1674 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001675 * character. <chunk> contains the input to be escaped. The result will be
1676 * stored between <start> (included) and <stop> (excluded). The function
1677 * will always try to terminate the resulting string with a '\0' before
1678 * <stop>, and will return its position if the conversion completes.
1679 */
1680char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001681 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001682 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001683{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001684 char *str = chunk->area;
1685 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001686
1687 if (start < stop) {
1688 stop--; /* reserve one byte for the final '\0' */
1689 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001690 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001691 *start++ = *str;
1692 else {
1693 if (start + 2 >= stop)
1694 break;
1695 *start++ = escape;
1696 *start++ = *str;
1697 }
1698 str++;
1699 }
1700 *start = '\0';
1701 }
1702 return start;
1703}
1704
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001705/* Check a string for using it in a CSV output format. If the string contains
1706 * one of the following four char <">, <,>, CR or LF, the string is
1707 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1708 * <str> is the input string to be escaped. The function assumes that
1709 * the input string is null-terminated.
1710 *
1711 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001712 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001713 * format.
1714 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001715 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001716 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001717 * If <quote> is 1, the converter puts the quotes only if any reserved character
1718 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001719 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001720 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001721 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001722 * The function returns the converted string on its output. If an error
1723 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001724 * for using the function directly as printf() argument.
1725 *
1726 * If the output buffer is too short to contain the input string, the result
1727 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001728 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001729 * This function appends the encoding to the existing output chunk, and it
1730 * guarantees that it starts immediately at the first available character of
1731 * the chunk. Please use csv_enc() instead if you want to replace the output
1732 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001733 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001734const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001735{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001736 char *end = output->area + output->size;
1737 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001738 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001739
Willy Tarreaub631c292016-01-08 10:04:08 +01001740 if (quote == 1) {
1741 /* automatic quoting: first verify if we'll have to quote the string */
1742 if (!strpbrk(str, "\n\r,\""))
1743 quote = 0;
1744 }
1745
1746 if (quote)
1747 *ptr++ = '"';
1748
Willy Tarreau898529b2016-01-06 18:07:04 +01001749 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1750 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001751 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001752 ptr++;
1753 if (ptr >= end - 2) {
1754 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001755 break;
1756 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001757 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001758 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001759 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001760 str++;
1761 }
1762
Willy Tarreaub631c292016-01-08 10:04:08 +01001763 if (quote)
1764 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001765
Willy Tarreau898529b2016-01-06 18:07:04 +01001766 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001767 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001768 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001769}
1770
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001771/* Decode an URL-encoded string in-place. The resulting string might
1772 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001773 * aborted, the string is truncated before the issue and a negative value is
1774 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001775 * If the 'in_form' argument is non-nul the string is assumed to be part of
1776 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1777 * turned to a space. If it's zero, this will only be done after a question
1778 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001779 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001780int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001781{
1782 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001783 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001784
1785 in = string;
1786 out = string;
1787 while (*in) {
1788 switch (*in) {
1789 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001790 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001791 break;
1792 case '%' :
1793 if (!ishex(in[1]) || !ishex(in[2]))
1794 goto end;
1795 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1796 in += 2;
1797 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001798 case '?':
1799 in_form = 1;
1800 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001801 default:
1802 *out++ = *in;
1803 break;
1804 }
1805 in++;
1806 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001807 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001808 end:
1809 *out = 0;
1810 return ret;
1811}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001812
Willy Tarreau6911fa42007-03-04 18:06:08 +01001813unsigned int str2ui(const char *s)
1814{
1815 return __str2ui(s);
1816}
1817
1818unsigned int str2uic(const char *s)
1819{
1820 return __str2uic(s);
1821}
1822
1823unsigned int strl2ui(const char *s, int len)
1824{
1825 return __strl2ui(s, len);
1826}
1827
1828unsigned int strl2uic(const char *s, int len)
1829{
1830 return __strl2uic(s, len);
1831}
1832
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001833unsigned int read_uint(const char **s, const char *end)
1834{
1835 return __read_uint(s, end);
1836}
1837
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001838/* This function reads an unsigned integer from the string pointed to by <s> and
1839 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1840 * function automatically stops at <end>. If the number overflows, the 2^64-1
1841 * value is returned.
1842 */
1843unsigned long long int read_uint64(const char **s, const char *end)
1844{
1845 const char *ptr = *s;
1846 unsigned long long int i = 0, tmp;
1847 unsigned int j;
1848
1849 while (ptr < end) {
1850
1851 /* read next char */
1852 j = *ptr - '0';
1853 if (j > 9)
1854 goto read_uint64_end;
1855
1856 /* add char to the number and check overflow. */
1857 tmp = i * 10;
1858 if (tmp / 10 != i) {
1859 i = ULLONG_MAX;
1860 goto read_uint64_eat;
1861 }
1862 if (ULLONG_MAX - tmp < j) {
1863 i = ULLONG_MAX;
1864 goto read_uint64_eat;
1865 }
1866 i = tmp + j;
1867 ptr++;
1868 }
1869read_uint64_eat:
1870 /* eat each numeric char */
1871 while (ptr < end) {
1872 if ((unsigned int)(*ptr - '0') > 9)
1873 break;
1874 ptr++;
1875 }
1876read_uint64_end:
1877 *s = ptr;
1878 return i;
1879}
1880
1881/* This function reads an integer from the string pointed to by <s> and returns
1882 * it. The <s> pointer is adjusted to point to the first unread char. The function
1883 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1884 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1885 * returned.
1886 */
1887long long int read_int64(const char **s, const char *end)
1888{
1889 unsigned long long int i = 0;
1890 int neg = 0;
1891
1892 /* Look for minus char. */
1893 if (**s == '-') {
1894 neg = 1;
1895 (*s)++;
1896 }
1897 else if (**s == '+')
1898 (*s)++;
1899
1900 /* convert as positive number. */
1901 i = read_uint64(s, end);
1902
1903 if (neg) {
1904 if (i > 0x8000000000000000ULL)
1905 return LLONG_MIN;
1906 return -i;
1907 }
1908 if (i > 0x7fffffffffffffffULL)
1909 return LLONG_MAX;
1910 return i;
1911}
1912
Willy Tarreau6911fa42007-03-04 18:06:08 +01001913/* This one is 7 times faster than strtol() on athlon with checks.
1914 * It returns the value of the number composed of all valid digits read,
1915 * and can process negative numbers too.
1916 */
1917int strl2ic(const char *s, int len)
1918{
1919 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001920 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001921
1922 if (len > 0) {
1923 if (*s != '-') {
1924 /* positive number */
1925 while (len-- > 0) {
1926 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001927 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001928 if (j > 9)
1929 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001930 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001931 }
1932 } else {
1933 /* negative number */
1934 s++;
1935 while (--len > 0) {
1936 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001937 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001938 if (j > 9)
1939 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001940 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001941 }
1942 }
1943 }
1944 return i;
1945}
1946
1947
1948/* This function reads exactly <len> chars from <s> and converts them to a
1949 * signed integer which it stores into <ret>. It accurately detects any error
1950 * (truncated string, invalid chars, overflows). It is meant to be used in
1951 * applications designed for hostile environments. It returns zero when the
1952 * number has successfully been converted, non-zero otherwise. When an error
1953 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1954 * faster than strtol().
1955 */
1956int strl2irc(const char *s, int len, int *ret)
1957{
1958 int i = 0;
1959 int j;
1960
1961 if (!len)
1962 return 1;
1963
1964 if (*s != '-') {
1965 /* positive number */
1966 while (len-- > 0) {
1967 j = (*s++) - '0';
1968 if (j > 9) return 1; /* invalid char */
1969 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1970 i = i * 10;
1971 if (i + j < i) return 1; /* check for addition overflow */
1972 i = i + j;
1973 }
1974 } else {
1975 /* negative number */
1976 s++;
1977 while (--len > 0) {
1978 j = (*s++) - '0';
1979 if (j > 9) return 1; /* invalid char */
1980 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1981 i = i * 10;
1982 if (i - j > i) return 1; /* check for subtract overflow */
1983 i = i - j;
1984 }
1985 }
1986 *ret = i;
1987 return 0;
1988}
1989
1990
1991/* This function reads exactly <len> chars from <s> and converts them to a
1992 * signed integer which it stores into <ret>. It accurately detects any error
1993 * (truncated string, invalid chars, overflows). It is meant to be used in
1994 * applications designed for hostile environments. It returns zero when the
1995 * number has successfully been converted, non-zero otherwise. When an error
1996 * is returned, the <ret> value is left untouched. It is about 3 times slower
1997 * than str2irc().
1998 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001999
2000int strl2llrc(const char *s, int len, long long *ret)
2001{
2002 long long i = 0;
2003 int j;
2004
2005 if (!len)
2006 return 1;
2007
2008 if (*s != '-') {
2009 /* positive number */
2010 while (len-- > 0) {
2011 j = (*s++) - '0';
2012 if (j > 9) return 1; /* invalid char */
2013 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2014 i = i * 10LL;
2015 if (i + j < i) return 1; /* check for addition overflow */
2016 i = i + j;
2017 }
2018 } else {
2019 /* negative number */
2020 s++;
2021 while (--len > 0) {
2022 j = (*s++) - '0';
2023 if (j > 9) return 1; /* invalid char */
2024 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2025 i = i * 10LL;
2026 if (i - j > i) return 1; /* check for subtract overflow */
2027 i = i - j;
2028 }
2029 }
2030 *ret = i;
2031 return 0;
2032}
2033
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002034/* This function is used with pat_parse_dotted_ver(). It converts a string
2035 * composed by two number separated by a dot. Each part must contain in 16 bits
2036 * because internally they will be represented as a 32-bit quantity stored in
2037 * a 64-bit integer. It returns zero when the number has successfully been
2038 * converted, non-zero otherwise. When an error is returned, the <ret> value
2039 * is left untouched.
2040 *
2041 * "1.3" -> 0x0000000000010003
2042 * "65535.65535" -> 0x00000000ffffffff
2043 */
2044int strl2llrc_dotted(const char *text, int len, long long *ret)
2045{
2046 const char *end = &text[len];
2047 const char *p;
2048 long long major, minor;
2049
2050 /* Look for dot. */
2051 for (p = text; p < end; p++)
2052 if (*p == '.')
2053 break;
2054
2055 /* Convert major. */
2056 if (strl2llrc(text, p - text, &major) != 0)
2057 return 1;
2058
2059 /* Check major. */
2060 if (major >= 65536)
2061 return 1;
2062
2063 /* Convert minor. */
2064 minor = 0;
2065 if (p < end)
2066 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2067 return 1;
2068
2069 /* Check minor. */
2070 if (minor >= 65536)
2071 return 1;
2072
2073 /* Compose value. */
2074 *ret = (major << 16) | (minor & 0xffff);
2075 return 0;
2076}
2077
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002078/* This function parses a time value optionally followed by a unit suffix among
2079 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2080 * expected by the caller. The computation does its best to avoid overflows.
2081 * The value is returned in <ret> if everything is fine, and a NULL is returned
2082 * by the function. In case of error, a pointer to the error is returned and
2083 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002084 * Values resulting in values larger than or equal to 2^31 after conversion are
2085 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2086 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002087 */
2088const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2089{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002090 unsigned long long imult, idiv;
2091 unsigned long long omult, odiv;
2092 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002093
2094 omult = odiv = 1;
2095
2096 switch (unit_flags & TIME_UNIT_MASK) {
2097 case TIME_UNIT_US: omult = 1000000; break;
2098 case TIME_UNIT_MS: omult = 1000; break;
2099 case TIME_UNIT_S: break;
2100 case TIME_UNIT_MIN: odiv = 60; break;
2101 case TIME_UNIT_HOUR: odiv = 3600; break;
2102 case TIME_UNIT_DAY: odiv = 86400; break;
2103 default: break;
2104 }
2105
2106 value = 0;
2107
2108 while (1) {
2109 unsigned int j;
2110
2111 j = *text - '0';
2112 if (j > 9)
2113 break;
2114 text++;
2115 value *= 10;
2116 value += j;
2117 }
2118
2119 imult = idiv = 1;
2120 switch (*text) {
2121 case '\0': /* no unit = default unit */
2122 imult = omult = idiv = odiv = 1;
2123 break;
2124 case 's': /* second = unscaled unit */
2125 break;
2126 case 'u': /* microsecond : "us" */
2127 if (text[1] == 's') {
2128 idiv = 1000000;
2129 text++;
2130 }
2131 break;
2132 case 'm': /* millisecond : "ms" or minute: "m" */
2133 if (text[1] == 's') {
2134 idiv = 1000;
2135 text++;
2136 } else
2137 imult = 60;
2138 break;
2139 case 'h': /* hour : "h" */
2140 imult = 3600;
2141 break;
2142 case 'd': /* day : "d" */
2143 imult = 86400;
2144 break;
2145 default:
2146 return text;
2147 break;
2148 }
2149
2150 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2151 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2152 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2153 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2154
Willy Tarreau9faebe32019-06-07 19:00:37 +02002155 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2156 if (result >= 0x80000000)
2157 return PARSE_TIME_OVER;
2158 if (!result && value)
2159 return PARSE_TIME_UNDER;
2160 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002161 return NULL;
2162}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002163
Emeric Brun39132b22010-01-04 14:57:24 +01002164/* this function converts the string starting at <text> to an unsigned int
2165 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002166 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002167 */
2168const char *parse_size_err(const char *text, unsigned *ret) {
2169 unsigned value = 0;
2170
2171 while (1) {
2172 unsigned int j;
2173
2174 j = *text - '0';
2175 if (j > 9)
2176 break;
2177 if (value > ~0U / 10)
2178 return text;
2179 value *= 10;
2180 if (value > (value + j))
2181 return text;
2182 value += j;
2183 text++;
2184 }
2185
2186 switch (*text) {
2187 case '\0':
2188 break;
2189 case 'K':
2190 case 'k':
2191 if (value > ~0U >> 10)
2192 return text;
2193 value = value << 10;
2194 break;
2195 case 'M':
2196 case 'm':
2197 if (value > ~0U >> 20)
2198 return text;
2199 value = value << 20;
2200 break;
2201 case 'G':
2202 case 'g':
2203 if (value > ~0U >> 30)
2204 return text;
2205 value = value << 30;
2206 break;
2207 default:
2208 return text;
2209 }
2210
Godbach58048a22015-01-28 17:36:16 +08002211 if (*text != '\0' && *++text != '\0')
2212 return text;
2213
Emeric Brun39132b22010-01-04 14:57:24 +01002214 *ret = value;
2215 return NULL;
2216}
2217
Willy Tarreau126d4062013-12-03 17:50:47 +01002218/*
2219 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002220 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002221 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002222 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002223 */
2224int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2225{
2226 int len;
2227 const char *p = source;
2228 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002229 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002230
2231 len = strlen(source);
2232 if (len % 2) {
2233 memprintf(err, "an even number of hex digit is expected");
2234 return 0;
2235 }
2236
2237 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002238
Willy Tarreau126d4062013-12-03 17:50:47 +01002239 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002240 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002241 if (!*binstr) {
2242 memprintf(err, "out of memory while loading string pattern");
2243 return 0;
2244 }
2245 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002246 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002247 else {
2248 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002249 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002250 len, *binstrlen);
2251 return 0;
2252 }
2253 alloc = 0;
2254 }
2255 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002256
2257 i = j = 0;
2258 while (j < len) {
2259 if (!ishex(p[i++]))
2260 goto bad_input;
2261 if (!ishex(p[i++]))
2262 goto bad_input;
2263 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2264 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002265 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002266
2267bad_input:
2268 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002269 if (alloc) {
2270 free(*binstr);
2271 *binstr = NULL;
2272 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002273 return 0;
2274}
2275
Willy Tarreau946ba592009-05-10 15:41:18 +02002276/* copies at most <n> characters from <src> and always terminates with '\0' */
2277char *my_strndup(const char *src, int n)
2278{
2279 int len = 0;
2280 char *ret;
2281
2282 while (len < n && src[len])
2283 len++;
2284
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002285 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002286 if (!ret)
2287 return ret;
2288 memcpy(ret, src, len);
2289 ret[len] = '\0';
2290 return ret;
2291}
2292
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002293/*
2294 * search needle in haystack
2295 * returns the pointer if found, returns NULL otherwise
2296 */
2297const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2298{
2299 const void *c = NULL;
2300 unsigned char f;
2301
2302 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2303 return NULL;
2304
2305 f = *(char *)needle;
2306 c = haystack;
2307 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2308 if ((haystacklen - (c - haystack)) < needlelen)
2309 return NULL;
2310
2311 if (memcmp(c, needle, needlelen) == 0)
2312 return c;
2313 ++c;
2314 }
2315 return NULL;
2316}
2317
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002318/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002319size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2320{
2321 size_t ret = 0;
2322
2323 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2324 str++;
2325 ret++;
2326 }
2327 return ret;
2328}
2329
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002330/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002331size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2332{
2333 size_t ret = 0;
2334
2335 while (ret < len) {
2336 if(memchr(reject, *((int *)str), rejectlen))
2337 return ret;
2338 str++;
2339 ret++;
2340 }
2341 return ret;
2342}
2343
Willy Tarreau482b00d2009-10-04 22:48:42 +02002344/* This function returns the first unused key greater than or equal to <key> in
2345 * ID tree <root>. Zero is returned if no place is found.
2346 */
2347unsigned int get_next_id(struct eb_root *root, unsigned int key)
2348{
2349 struct eb32_node *used;
2350
2351 do {
2352 used = eb32_lookup_ge(root, key);
2353 if (!used || used->key > key)
2354 return key; /* key is available */
2355 key++;
2356 } while (key);
2357 return key;
2358}
2359
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002360/* dump the full tree to <file> in DOT format for debugging purposes. Will
2361 * optionally highlight node <subj> if found, depending on operation <op> :
2362 * 0 : nothing
2363 * >0 : insertion, node/leaf are surrounded in red
2364 * <0 : removal, node/leaf are dashed with no background
2365 * Will optionally add "desc" as a label on the graph if set and non-null.
2366 */
2367void 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 +01002368{
2369 struct eb32sc_node *node;
2370 unsigned long scope = -1;
2371
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002372 fprintf(file, "digraph ebtree {\n");
2373
2374 if (desc && *desc) {
2375 fprintf(file,
2376 " fontname=\"fixed\";\n"
2377 " fontsize=8;\n"
2378 " label=\"%s\";\n", desc);
2379 }
2380
Willy Tarreaued3cda02017-11-15 15:04:05 +01002381 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002382 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2383 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002384 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2385 );
2386
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002387 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002388 (long)eb_root_to_node(root),
2389 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002390 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2391
2392 node = eb32sc_first(root, scope);
2393 while (node) {
2394 if (node->node.node_p) {
2395 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002396 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2397 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2398 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002399
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002400 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002401 (long)node,
2402 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002403 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002404
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002405 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002406 (long)node,
2407 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002408 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2409
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002410 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002411 (long)node,
2412 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002413 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2414 }
2415
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002416 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2417 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2418 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002419
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002420 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002421 (long)node,
2422 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002423 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002424 node = eb32sc_next(node, scope);
2425 }
2426 fprintf(file, "}\n");
2427}
2428
Willy Tarreau348238b2010-01-18 15:05:57 +01002429/* This function compares a sample word possibly followed by blanks to another
2430 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2431 * otherwise zero. This intends to be used when checking HTTP headers for some
2432 * values. Note that it validates a word followed only by blanks but does not
2433 * validate a word followed by blanks then other chars.
2434 */
2435int word_match(const char *sample, int slen, const char *word, int wlen)
2436{
2437 if (slen < wlen)
2438 return 0;
2439
2440 while (wlen) {
2441 char c = *sample ^ *word;
2442 if (c && c != ('A' ^ 'a'))
2443 return 0;
2444 sample++;
2445 word++;
2446 slen--;
2447 wlen--;
2448 }
2449
2450 while (slen) {
2451 if (*sample != ' ' && *sample != '\t')
2452 return 0;
2453 sample++;
2454 slen--;
2455 }
2456 return 1;
2457}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002458
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002459/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2460 * is particularly fast because it avoids expensive operations such as
2461 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002462 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002463 */
2464unsigned int inetaddr_host(const char *text)
2465{
2466 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2467 register unsigned int dig100, dig10, dig1;
2468 int s;
2469 const char *p, *d;
2470
2471 dig1 = dig10 = dig100 = ascii_zero;
2472 s = 24;
2473
2474 p = text;
2475 while (1) {
2476 if (((unsigned)(*p - '0')) <= 9) {
2477 p++;
2478 continue;
2479 }
2480
2481 /* here, we have a complete byte between <text> and <p> (exclusive) */
2482 if (p == text)
2483 goto end;
2484
2485 d = p - 1;
2486 dig1 |= (unsigned int)(*d << s);
2487 if (d == text)
2488 goto end;
2489
2490 d--;
2491 dig10 |= (unsigned int)(*d << s);
2492 if (d == text)
2493 goto end;
2494
2495 d--;
2496 dig100 |= (unsigned int)(*d << s);
2497 end:
2498 if (!s || *p != '.')
2499 break;
2500
2501 s -= 8;
2502 text = ++p;
2503 }
2504
2505 dig100 -= ascii_zero;
2506 dig10 -= ascii_zero;
2507 dig1 -= ascii_zero;
2508 return ((dig100 * 10) + dig10) * 10 + dig1;
2509}
2510
2511/*
2512 * Idem except the first unparsed character has to be passed in <stop>.
2513 */
2514unsigned int inetaddr_host_lim(const char *text, const char *stop)
2515{
2516 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2517 register unsigned int dig100, dig10, dig1;
2518 int s;
2519 const char *p, *d;
2520
2521 dig1 = dig10 = dig100 = ascii_zero;
2522 s = 24;
2523
2524 p = text;
2525 while (1) {
2526 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2527 p++;
2528 continue;
2529 }
2530
2531 /* here, we have a complete byte between <text> and <p> (exclusive) */
2532 if (p == text)
2533 goto end;
2534
2535 d = p - 1;
2536 dig1 |= (unsigned int)(*d << s);
2537 if (d == text)
2538 goto end;
2539
2540 d--;
2541 dig10 |= (unsigned int)(*d << s);
2542 if (d == text)
2543 goto end;
2544
2545 d--;
2546 dig100 |= (unsigned int)(*d << s);
2547 end:
2548 if (!s || p == stop || *p != '.')
2549 break;
2550
2551 s -= 8;
2552 text = ++p;
2553 }
2554
2555 dig100 -= ascii_zero;
2556 dig10 -= ascii_zero;
2557 dig1 -= ascii_zero;
2558 return ((dig100 * 10) + dig10) * 10 + dig1;
2559}
2560
2561/*
2562 * Idem except the pointer to first unparsed byte is returned into <ret> which
2563 * must not be NULL.
2564 */
Willy Tarreau74172752010-10-15 23:21:42 +02002565unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002566{
2567 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2568 register unsigned int dig100, dig10, dig1;
2569 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002570 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002571
2572 dig1 = dig10 = dig100 = ascii_zero;
2573 s = 24;
2574
2575 p = text;
2576 while (1) {
2577 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2578 p++;
2579 continue;
2580 }
2581
2582 /* here, we have a complete byte between <text> and <p> (exclusive) */
2583 if (p == text)
2584 goto end;
2585
2586 d = p - 1;
2587 dig1 |= (unsigned int)(*d << s);
2588 if (d == text)
2589 goto end;
2590
2591 d--;
2592 dig10 |= (unsigned int)(*d << s);
2593 if (d == text)
2594 goto end;
2595
2596 d--;
2597 dig100 |= (unsigned int)(*d << s);
2598 end:
2599 if (!s || p == stop || *p != '.')
2600 break;
2601
2602 s -= 8;
2603 text = ++p;
2604 }
2605
2606 *ret = p;
2607 dig100 -= ascii_zero;
2608 dig10 -= ascii_zero;
2609 dig1 -= ascii_zero;
2610 return ((dig100 * 10) + dig10) * 10 + dig1;
2611}
2612
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002613/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2614 * or the number of chars read in case of success. Maybe this could be replaced
2615 * by one of the functions above. Also, apparently this function does not support
2616 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002617 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002618 */
2619int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2620{
2621 const char *addr;
2622 int saw_digit, octets, ch;
2623 u_char tmp[4], *tp;
2624 const char *cp = buf;
2625
2626 saw_digit = 0;
2627 octets = 0;
2628 *(tp = tmp) = 0;
2629
2630 for (addr = buf; addr - buf < len; addr++) {
2631 unsigned char digit = (ch = *addr) - '0';
2632
2633 if (digit > 9 && ch != '.')
2634 break;
2635
2636 if (digit <= 9) {
2637 u_int new = *tp * 10 + digit;
2638
2639 if (new > 255)
2640 return 0;
2641
2642 *tp = new;
2643
2644 if (!saw_digit) {
2645 if (++octets > 4)
2646 return 0;
2647 saw_digit = 1;
2648 }
2649 } else if (ch == '.' && saw_digit) {
2650 if (octets == 4)
2651 return 0;
2652
2653 *++tp = 0;
2654 saw_digit = 0;
2655 } else
2656 return 0;
2657 }
2658
2659 if (octets < 4)
2660 return 0;
2661
2662 memcpy(&dst->s_addr, tmp, 4);
2663 return addr - cp;
2664}
2665
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002666/* This function converts the string in <buf> of the len <len> to
2667 * struct in6_addr <dst> which must be allocated by the caller.
2668 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002669 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002670 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002671int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2672{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002673 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002674 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002675
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002676 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002677 return 0;
2678
2679 memcpy(null_term_ip6, buf, len);
2680 null_term_ip6[len] = '\0';
2681
Willy Tarreau075415a2013-12-12 11:29:39 +01002682 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002683 return 0;
2684
Willy Tarreau075415a2013-12-12 11:29:39 +01002685 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002686 return 1;
2687}
2688
Willy Tarreauacf95772010-06-14 19:09:21 +02002689/* To be used to quote config arg positions. Returns the short string at <ptr>
2690 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2691 * if ptr is NULL or empty. The string is locally allocated.
2692 */
2693const char *quote_arg(const char *ptr)
2694{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002695 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002696 int i;
2697
2698 if (!ptr || !*ptr)
2699 return "end of line";
2700 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002701 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002702 val[i] = *ptr++;
2703 val[i++] = '\'';
2704 val[i] = '\0';
2705 return val;
2706}
2707
Willy Tarreau5b180202010-07-18 10:40:48 +02002708/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2709int get_std_op(const char *str)
2710{
2711 int ret = -1;
2712
2713 if (*str == 'e' && str[1] == 'q')
2714 ret = STD_OP_EQ;
2715 else if (*str == 'n' && str[1] == 'e')
2716 ret = STD_OP_NE;
2717 else if (*str == 'l') {
2718 if (str[1] == 'e') ret = STD_OP_LE;
2719 else if (str[1] == 't') ret = STD_OP_LT;
2720 }
2721 else if (*str == 'g') {
2722 if (str[1] == 'e') ret = STD_OP_GE;
2723 else if (str[1] == 't') ret = STD_OP_GT;
2724 }
2725
2726 if (ret == -1 || str[2] != '\0')
2727 return -1;
2728 return ret;
2729}
2730
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002731/* hash a 32-bit integer to another 32-bit integer */
2732unsigned int full_hash(unsigned int a)
2733{
2734 return __full_hash(a);
2735}
2736
Willy Tarreauf3241112019-02-26 09:56:22 +01002737/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2738 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2739 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2740 * a popcount variant and is described here :
2741 * https://graphics.stanford.edu/~seander/bithacks.html
2742 */
2743unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2744{
2745 unsigned long a, b, c, d;
2746 unsigned int s;
2747 unsigned int t;
2748
2749 a = m - ((m >> 1) & ~0UL/3);
2750 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2751 c = (b + (b >> 4)) & ~0UL/0x11;
2752 d = (c + (c >> 8)) & ~0UL/0x101;
2753
2754 r++; // make r be 1..64
2755
2756 t = 0;
2757 s = LONGBITS;
2758 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002759 unsigned long d2 = (d >> 16) >> 16;
2760 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002761 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2762 }
2763
2764 t = (d >> (s - 16)) & 0xff;
2765 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2766 t = (c >> (s - 8)) & 0xf;
2767 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2768 t = (b >> (s - 4)) & 0x7;
2769 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2770 t = (a >> (s - 2)) & 0x3;
2771 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2772 t = (m >> (s - 1)) & 0x1;
2773 s -= ((t - r) & 256) >> 8;
2774
2775 return s - 1;
2776}
2777
2778/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2779 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2780 * using mask_prep_rank_map() below.
2781 */
2782unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2783 unsigned long a, unsigned long b,
2784 unsigned long c, unsigned long d)
2785{
2786 unsigned int s;
2787 unsigned int t;
2788
2789 r++; // make r be 1..64
2790
2791 t = 0;
2792 s = LONGBITS;
2793 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002794 unsigned long d2 = (d >> 16) >> 16;
2795 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002796 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2797 }
2798
2799 t = (d >> (s - 16)) & 0xff;
2800 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2801 t = (c >> (s - 8)) & 0xf;
2802 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2803 t = (b >> (s - 4)) & 0x7;
2804 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2805 t = (a >> (s - 2)) & 0x3;
2806 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2807 t = (m >> (s - 1)) & 0x1;
2808 s -= ((t - r) & 256) >> 8;
2809
2810 return s - 1;
2811}
2812
2813/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2814 * above.
2815 */
2816void mask_prep_rank_map(unsigned long m,
2817 unsigned long *a, unsigned long *b,
2818 unsigned long *c, unsigned long *d)
2819{
2820 *a = m - ((m >> 1) & ~0UL/3);
2821 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2822 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2823 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2824}
2825
David du Colombier4f92d322011-03-24 11:09:31 +01002826/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002827 * otherwise zero. Note that <addr> may not necessarily be aligned
2828 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002829 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002830int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002831{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002832 struct in_addr addr_copy;
2833
2834 memcpy(&addr_copy, addr, sizeof(addr_copy));
2835 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002836}
2837
2838/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002839 * otherwise zero. Note that <addr> may not necessarily be aligned
2840 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002841 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002842int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002843{
2844 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002845 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002846
Willy Tarreaueec1d382016-07-13 11:59:39 +02002847 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002848 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002849 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002850 (((int *)net)[i] & ((int *)mask)[i]))
2851 return 0;
2852 return 1;
2853}
2854
2855/* RFC 4291 prefix */
2856const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2857 0x00, 0x00, 0x00, 0x00,
2858 0x00, 0x00, 0xFF, 0xFF };
2859
Joseph Herlant32b83272018-11-15 11:58:28 -08002860/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002861 * Input and output may overlap.
2862 */
David du Colombier4f92d322011-03-24 11:09:31 +01002863void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2864{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002865 struct in_addr tmp_addr;
2866
2867 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002868 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002869 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002870}
2871
Joseph Herlant32b83272018-11-15 11:58:28 -08002872/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002873 * Return true if conversion is possible and false otherwise.
2874 */
2875int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2876{
2877 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2878 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2879 sizeof(struct in_addr));
2880 return 1;
2881 }
2882
2883 return 0;
2884}
2885
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002886/* compare two struct sockaddr_storage and return:
2887 * 0 (true) if the addr is the same in both
2888 * 1 (false) if the addr is not the same in both
2889 * -1 (unable) if one of the addr is not AF_INET*
2890 */
2891int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2892{
2893 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2894 return -1;
2895
2896 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2897 return -1;
2898
2899 if (ss1->ss_family != ss2->ss_family)
2900 return 1;
2901
2902 switch (ss1->ss_family) {
2903 case AF_INET:
2904 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2905 &((struct sockaddr_in *)ss2)->sin_addr,
2906 sizeof(struct in_addr)) != 0;
2907 case AF_INET6:
2908 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2909 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2910 sizeof(struct in6_addr)) != 0;
2911 }
2912
2913 return 1;
2914}
2915
Baptiste Assmann08396c82016-01-31 00:27:17 +01002916/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002917 * The caller must allocate and clear <dest> before calling.
2918 * The source must be in either AF_INET or AF_INET6 family, or the destination
2919 * address will be undefined. If the destination address used to hold a port,
2920 * it is preserved, so that this function can be used to switch to another
2921 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002922 */
2923struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2924{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002925 int prev_port;
2926
2927 prev_port = get_net_port(dest);
2928 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002929 dest->ss_family = source->ss_family;
2930
2931 /* copy new addr and apply it */
2932 switch (source->ss_family) {
2933 case AF_INET:
2934 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002935 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002936 break;
2937 case AF_INET6:
2938 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 +01002939 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002940 break;
2941 }
2942
2943 return dest;
2944}
2945
William Lallemand421f5b52012-02-06 18:15:57 +01002946char *human_time(int t, short hz_div) {
2947 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2948 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002949 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002950 int cnt=2; // print two numbers
2951
2952 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002953 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002954 return rv;
2955 }
2956
2957 if (unlikely(hz_div > 1))
2958 t /= hz_div;
2959
2960 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002961 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002962 cnt--;
2963 }
2964
2965 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002966 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002967 cnt--;
2968 }
2969
2970 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002971 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002972 cnt--;
2973 }
2974
2975 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002976 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002977
2978 return rv;
2979}
2980
2981const char *monthname[12] = {
2982 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2983 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2984};
2985
2986/* date2str_log: write a date in the format :
2987 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2988 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2989 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2990 *
2991 * without using sprintf. return a pointer to the last char written (\0) or
2992 * NULL if there isn't enough space.
2993 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002994char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002995{
2996
2997 if (size < 25) /* the size is fixed: 24 chars + \0 */
2998 return NULL;
2999
3000 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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
William Lallemand421f5b52012-02-06 18:15:57 +01003005 memcpy(dst, monthname[tm->tm_mon], 3); // month
3006 dst += 3;
3007 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003008
William Lallemand421f5b52012-02-06 18:15:57 +01003009 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003010 if (!dst)
3011 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003012 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003013
William Lallemand421f5b52012-02-06 18:15:57 +01003014 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003015 if (!dst)
3016 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003017 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003018
William Lallemand421f5b52012-02-06 18:15:57 +01003019 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003020 if (!dst)
3021 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003022 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003023
William Lallemand421f5b52012-02-06 18:15:57 +01003024 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003025 if (!dst)
3026 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003027 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003028
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003029 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003030 if (!dst)
3031 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003032 *dst = '\0';
3033
3034 return dst;
3035}
3036
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003037/* Base year used to compute leap years */
3038#define TM_YEAR_BASE 1900
3039
3040/* Return the difference in seconds between two times (leap seconds are ignored).
3041 * Retrieved from glibc 2.18 source code.
3042 */
3043static int my_tm_diff(const struct tm *a, const struct tm *b)
3044{
3045 /* Compute intervening leap days correctly even if year is negative.
3046 * Take care to avoid int overflow in leap day calculations,
3047 * but it's OK to assume that A and B are close to each other.
3048 */
3049 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3050 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3051 int a100 = a4 / 25 - (a4 % 25 < 0);
3052 int b100 = b4 / 25 - (b4 % 25 < 0);
3053 int a400 = a100 >> 2;
3054 int b400 = b100 >> 2;
3055 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3056 int years = a->tm_year - b->tm_year;
3057 int days = (365 * years + intervening_leap_days
3058 + (a->tm_yday - b->tm_yday));
3059 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3060 + (a->tm_min - b->tm_min))
3061 + (a->tm_sec - b->tm_sec));
3062}
3063
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003064/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003065 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003066 * The string returned has the same format as returned by strftime(... "%z", tm).
3067 * Offsets are kept in an internal cache for better performances.
3068 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003069const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003070{
3071 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003072 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003073
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003074 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003075 struct tm tm_gmt;
3076 int diff;
3077 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003078
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003079 /* Pretend DST not active if its status is unknown */
3080 if (isdst < 0)
3081 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003082
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003083 /* Fetch the offset and initialize it if needed */
3084 gmt_offset = gmt_offsets[isdst & 0x01];
3085 if (unlikely(!*gmt_offset)) {
3086 get_gmtime(t, &tm_gmt);
3087 diff = my_tm_diff(tm, &tm_gmt);
3088 if (diff < 0) {
3089 diff = -diff;
3090 *gmt_offset = '-';
3091 } else {
3092 *gmt_offset = '+';
3093 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003094 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003095 diff /= 60; /* Convert to minutes */
3096 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3097 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003098
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003099 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003100}
3101
William Lallemand421f5b52012-02-06 18:15:57 +01003102/* gmt2str_log: write a date in the format :
3103 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3104 * return a pointer to the last char written (\0) or
3105 * NULL if there isn't enough space.
3106 */
3107char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3108{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003109 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003110 return NULL;
3111
3112 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003113 if (!dst)
3114 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003115 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003116
William Lallemand421f5b52012-02-06 18:15:57 +01003117 memcpy(dst, monthname[tm->tm_mon], 3); // month
3118 dst += 3;
3119 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003120
William Lallemand421f5b52012-02-06 18:15:57 +01003121 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003122 if (!dst)
3123 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003124 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003125
William Lallemand421f5b52012-02-06 18:15:57 +01003126 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003127 if (!dst)
3128 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003129 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003130
William Lallemand421f5b52012-02-06 18:15:57 +01003131 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003132 if (!dst)
3133 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003134 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003135
William Lallemand421f5b52012-02-06 18:15:57 +01003136 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003137 if (!dst)
3138 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003139 *dst++ = ' ';
3140 *dst++ = '+';
3141 *dst++ = '0';
3142 *dst++ = '0';
3143 *dst++ = '0';
3144 *dst++ = '0';
3145 *dst = '\0';
3146
3147 return dst;
3148}
3149
Yuxans Yao4e25b012012-10-19 10:36:09 +08003150/* localdate2str_log: write a date in the format :
3151 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003152 * Both t and tm must represent the same time.
3153 * return a pointer to the last char written (\0) or
3154 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003155 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003156char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003157{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003158 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003159 if (size < 27) /* the size is fixed: 26 chars + \0 */
3160 return NULL;
3161
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003162 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003163
Yuxans Yao4e25b012012-10-19 10:36:09 +08003164 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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
Yuxans Yao4e25b012012-10-19 10:36:09 +08003169 memcpy(dst, monthname[tm->tm_mon], 3); // month
3170 dst += 3;
3171 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003172
Yuxans Yao4e25b012012-10-19 10:36:09 +08003173 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003174 if (!dst)
3175 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003176 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003177
Yuxans Yao4e25b012012-10-19 10:36:09 +08003178 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003179 if (!dst)
3180 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003181 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003182
Yuxans Yao4e25b012012-10-19 10:36:09 +08003183 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003184 if (!dst)
3185 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003186 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003187
Yuxans Yao4e25b012012-10-19 10:36:09 +08003188 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003189 if (!dst)
3190 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003191 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003192
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003193 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003194 dst += 5;
3195 *dst = '\0';
3196
3197 return dst;
3198}
3199
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003200/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3201 * It is meant as a portable replacement for timegm() for use with valid inputs.
3202 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3203 */
3204time_t my_timegm(const struct tm *tm)
3205{
3206 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3207 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3208 * sum of the extra N days for elapsed months. The sum of all these N
3209 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3210 * in a 5-bit word. This means that with 60 bits we can represent a
3211 * matrix of all these values at once, which is fast and efficient to
3212 * access. The extra February day for leap years is not counted here.
3213 *
3214 * Jan : none = 0 (0)
3215 * Feb : Jan = 3 (3)
3216 * Mar : Jan..Feb = 3 (3 + 0)
3217 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3218 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3219 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3220 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3221 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3222 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3223 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3224 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3225 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3226 */
3227 uint64_t extra =
3228 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3229 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3230 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3231 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3232
3233 unsigned int y = tm->tm_year + 1900;
3234 unsigned int m = tm->tm_mon;
3235 unsigned long days = 0;
3236
3237 /* days since 1/1/1970 for full years */
3238 days += days_since_zero(y) - days_since_zero(1970);
3239
3240 /* days for full months in the current year */
3241 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3242
3243 /* count + 1 after March for leap years. A leap year is a year multiple
3244 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3245 * is leap, 1900 isn't, 1904 is.
3246 */
3247 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3248 days++;
3249
3250 days += tm->tm_mday - 1;
3251 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3252}
3253
Thierry Fournier93127942016-01-20 18:49:45 +01003254/* This function check a char. It returns true and updates
3255 * <date> and <len> pointer to the new position if the
3256 * character is found.
3257 */
3258static inline int parse_expect_char(const char **date, int *len, char c)
3259{
3260 if (*len < 1 || **date != c)
3261 return 0;
3262 (*len)--;
3263 (*date)++;
3264 return 1;
3265}
3266
3267/* This function expects a string <str> of len <l>. It return true and updates.
3268 * <date> and <len> if the string matches, otherwise, it returns false.
3269 */
3270static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3271{
3272 if (*len < l || strncmp(*date, str, l) != 0)
3273 return 0;
3274 (*len) -= l;
3275 (*date) += l;
3276 return 1;
3277}
3278
3279/* This macro converts 3 chars name in integer. */
3280#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3281
3282/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3283 * / %x54.75.65 ; "Tue", case-sensitive
3284 * / %x57.65.64 ; "Wed", case-sensitive
3285 * / %x54.68.75 ; "Thu", case-sensitive
3286 * / %x46.72.69 ; "Fri", case-sensitive
3287 * / %x53.61.74 ; "Sat", case-sensitive
3288 * / %x53.75.6E ; "Sun", case-sensitive
3289 *
3290 * This array must be alphabetically sorted
3291 */
3292static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3293{
3294 if (*len < 3)
3295 return 0;
3296 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3297 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3298 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3299 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3300 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3301 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3302 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3303 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3304 default: return 0;
3305 }
3306 *len -= 3;
3307 *date += 3;
3308 return 1;
3309}
3310
3311/* month = %x4A.61.6E ; "Jan", case-sensitive
3312 * / %x46.65.62 ; "Feb", case-sensitive
3313 * / %x4D.61.72 ; "Mar", case-sensitive
3314 * / %x41.70.72 ; "Apr", case-sensitive
3315 * / %x4D.61.79 ; "May", case-sensitive
3316 * / %x4A.75.6E ; "Jun", case-sensitive
3317 * / %x4A.75.6C ; "Jul", case-sensitive
3318 * / %x41.75.67 ; "Aug", case-sensitive
3319 * / %x53.65.70 ; "Sep", case-sensitive
3320 * / %x4F.63.74 ; "Oct", case-sensitive
3321 * / %x4E.6F.76 ; "Nov", case-sensitive
3322 * / %x44.65.63 ; "Dec", case-sensitive
3323 *
3324 * This array must be alphabetically sorted
3325 */
3326static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3327{
3328 if (*len < 3)
3329 return 0;
3330 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3331 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3332 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3333 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3334 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3335 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3336 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3337 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3338 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3339 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3340 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3341 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3342 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3343 default: return 0;
3344 }
3345 *len -= 3;
3346 *date += 3;
3347 return 1;
3348}
3349
3350/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3351 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3352 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3353 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3354 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3355 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3356 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3357 *
3358 * This array must be alphabetically sorted
3359 */
3360static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3361{
3362 if (*len < 6) /* Minimum length. */
3363 return 0;
3364 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3365 case STR2I3('M','o','n'):
3366 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3367 tm->tm_wday = 1;
3368 return 1;
3369 case STR2I3('T','u','e'):
3370 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3371 tm->tm_wday = 2;
3372 return 1;
3373 case STR2I3('W','e','d'):
3374 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3375 tm->tm_wday = 3;
3376 return 1;
3377 case STR2I3('T','h','u'):
3378 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3379 tm->tm_wday = 4;
3380 return 1;
3381 case STR2I3('F','r','i'):
3382 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3383 tm->tm_wday = 5;
3384 return 1;
3385 case STR2I3('S','a','t'):
3386 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3387 tm->tm_wday = 6;
3388 return 1;
3389 case STR2I3('S','u','n'):
3390 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3391 tm->tm_wday = 7;
3392 return 1;
3393 }
3394 return 0;
3395}
3396
3397/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3398static inline int parse_digit(const char **date, int *len, int *digit)
3399{
3400 if (*len < 1 || **date < '0' || **date > '9')
3401 return 0;
3402 *digit = (**date - '0');
3403 (*date)++;
3404 (*len)--;
3405 return 1;
3406}
3407
3408/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3409static inline int parse_2digit(const char **date, int *len, int *digit)
3410{
3411 int value;
3412
3413 RET0_UNLESS(parse_digit(date, len, &value));
3414 (*digit) = value * 10;
3415 RET0_UNLESS(parse_digit(date, len, &value));
3416 (*digit) += value;
3417
3418 return 1;
3419}
3420
3421/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3422static inline int parse_4digit(const char **date, int *len, int *digit)
3423{
3424 int value;
3425
3426 RET0_UNLESS(parse_digit(date, len, &value));
3427 (*digit) = value * 1000;
3428
3429 RET0_UNLESS(parse_digit(date, len, &value));
3430 (*digit) += value * 100;
3431
3432 RET0_UNLESS(parse_digit(date, len, &value));
3433 (*digit) += value * 10;
3434
3435 RET0_UNLESS(parse_digit(date, len, &value));
3436 (*digit) += value;
3437
3438 return 1;
3439}
3440
3441/* time-of-day = hour ":" minute ":" second
3442 * ; 00:00:00 - 23:59:60 (leap second)
3443 *
3444 * hour = 2DIGIT
3445 * minute = 2DIGIT
3446 * second = 2DIGIT
3447 */
3448static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3449{
3450 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3451 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3452 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3453 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3454 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3455 return 1;
3456}
3457
3458/* From RFC7231
3459 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3460 *
3461 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3462 * ; fixed length/zone/capitalization subset of the format
3463 * ; see Section 3.3 of [RFC5322]
3464 *
3465 *
3466 * date1 = day SP month SP year
3467 * ; e.g., 02 Jun 1982
3468 *
3469 * day = 2DIGIT
3470 * year = 4DIGIT
3471 *
3472 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3473 *
3474 * time-of-day = hour ":" minute ":" second
3475 * ; 00:00:00 - 23:59:60 (leap second)
3476 *
3477 * hour = 2DIGIT
3478 * minute = 2DIGIT
3479 * second = 2DIGIT
3480 *
3481 * DIGIT = decimal 0-9
3482 */
3483int parse_imf_date(const char *date, int len, struct tm *tm)
3484{
David Carlier327298c2016-11-20 10:42:38 +00003485 /* tm_gmtoff, if present, ought to be zero'ed */
3486 memset(tm, 0, sizeof(*tm));
3487
Thierry Fournier93127942016-01-20 18:49:45 +01003488 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3489 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3490 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3491 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3492 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3493 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3494 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3495 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3496 tm->tm_year -= 1900;
3497 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3498 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3499 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3500 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3501 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003502 return 1;
3503}
3504
3505/* From RFC7231
3506 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3507 *
3508 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3509 * date2 = day "-" month "-" 2DIGIT
3510 * ; e.g., 02-Jun-82
3511 *
3512 * day = 2DIGIT
3513 */
3514int parse_rfc850_date(const char *date, int len, struct tm *tm)
3515{
3516 int year;
3517
David Carlier327298c2016-11-20 10:42:38 +00003518 /* tm_gmtoff, if present, ought to be zero'ed */
3519 memset(tm, 0, sizeof(*tm));
3520
Thierry Fournier93127942016-01-20 18:49:45 +01003521 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3522 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3523 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3524 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3525 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3526 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3527 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3528
3529 /* year = 2DIGIT
3530 *
3531 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3532 * two-digit year, MUST interpret a timestamp that appears to be more
3533 * than 50 years in the future as representing the most recent year in
3534 * the past that had the same last two digits.
3535 */
3536 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3537
3538 /* expect SP */
3539 if (!parse_expect_char(&date, &len, ' ')) {
3540 /* Maybe we have the date with 4 digits. */
3541 RET0_UNLESS(parse_2digit(&date, &len, &year));
3542 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3543 /* expect SP */
3544 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3545 } else {
3546 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3547 * tm_year is the number of year since 1900, so for +1900, we
3548 * do nothing, and for +2000, we add 100.
3549 */
3550 if (tm->tm_year <= 60)
3551 tm->tm_year += 100;
3552 }
3553
3554 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3555 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3556 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3557 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003558
3559 return 1;
3560}
3561
3562/* From RFC7231
3563 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3564 *
3565 * asctime-date = day-name SP date3 SP time-of-day SP year
3566 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3567 * ; e.g., Jun 2
3568 *
3569 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3570 * whitespace in an HTTP-date beyond that specifically included as SP in
3571 * the grammar.
3572 */
3573int parse_asctime_date(const char *date, int len, struct tm *tm)
3574{
David Carlier327298c2016-11-20 10:42:38 +00003575 /* tm_gmtoff, if present, ought to be zero'ed */
3576 memset(tm, 0, sizeof(*tm));
3577
Thierry Fournier93127942016-01-20 18:49:45 +01003578 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3579 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3580 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3581 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3582
3583 /* expect SP and 1DIGIT or 2DIGIT */
3584 if (parse_expect_char(&date, &len, ' '))
3585 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3586 else
3587 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3588
3589 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3590 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3591 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3592 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3593 tm->tm_year -= 1900;
3594 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003595 return 1;
3596}
3597
3598/* From RFC7231
3599 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3600 *
3601 * HTTP-date = IMF-fixdate / obs-date
3602 * obs-date = rfc850-date / asctime-date
3603 *
3604 * parses an HTTP date in the RFC format and is accepted
3605 * alternatives. <date> is the strinf containing the date,
3606 * len is the len of the string. <tm> is filled with the
3607 * parsed time. We must considers this time as GMT.
3608 */
3609int parse_http_date(const char *date, int len, struct tm *tm)
3610{
3611 if (parse_imf_date(date, len, tm))
3612 return 1;
3613
3614 if (parse_rfc850_date(date, len, tm))
3615 return 1;
3616
3617 if (parse_asctime_date(date, len, tm))
3618 return 1;
3619
3620 return 0;
3621}
3622
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003623/* Dynamically allocates a string of the proper length to hold the formatted
3624 * output. NULL is returned on error. The caller is responsible for freeing the
3625 * memory area using free(). The resulting string is returned in <out> if the
3626 * pointer is not NULL. A previous version of <out> might be used to build the
3627 * new string, and it will be freed before returning if it is not NULL, which
3628 * makes it possible to build complex strings from iterative calls without
3629 * having to care about freeing intermediate values, as in the example below :
3630 *
3631 * memprintf(&err, "invalid argument: '%s'", arg);
3632 * ...
3633 * memprintf(&err, "parser said : <%s>\n", *err);
3634 * ...
3635 * free(*err);
3636 *
3637 * This means that <err> must be initialized to NULL before first invocation.
3638 * The return value also holds the allocated string, which eases error checking
3639 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003640 * passed instead and it will be ignored. The returned message will then also
3641 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003642 *
3643 * It is also convenient to use it without any free except the last one :
3644 * err = NULL;
3645 * if (!fct1(err)) report(*err);
3646 * if (!fct2(err)) report(*err);
3647 * if (!fct3(err)) report(*err);
3648 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003649 *
3650 * memprintf relies on memvprintf. This last version can be called from any
3651 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003652 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003653char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003654{
3655 va_list args;
3656 char *ret = NULL;
3657 int allocated = 0;
3658 int needed = 0;
3659
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003660 if (!out)
3661 return NULL;
3662
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003663 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003664 char buf1;
3665
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003666 /* vsnprintf() will return the required length even when the
3667 * target buffer is NULL. We do this in a loop just in case
3668 * intermediate evaluations get wrong.
3669 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003670 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003671 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003672 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003673 if (needed < allocated) {
3674 /* Note: on Solaris 8, the first iteration always
3675 * returns -1 if allocated is zero, so we force a
3676 * retry.
3677 */
3678 if (!allocated)
3679 needed = 0;
3680 else
3681 break;
3682 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003683
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003684 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003685 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003686 } while (ret);
3687
3688 if (needed < 0) {
3689 /* an error was encountered */
3690 free(ret);
3691 ret = NULL;
3692 }
3693
3694 if (out) {
3695 free(*out);
3696 *out = ret;
3697 }
3698
3699 return ret;
3700}
William Lallemand421f5b52012-02-06 18:15:57 +01003701
Christopher Faulet93a518f2017-10-24 11:25:33 +02003702char *memprintf(char **out, const char *format, ...)
3703{
3704 va_list args;
3705 char *ret = NULL;
3706
3707 va_start(args, format);
3708 ret = memvprintf(out, format, args);
3709 va_end(args);
3710
3711 return ret;
3712}
3713
Willy Tarreau21c705b2012-09-14 11:40:36 +02003714/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3715 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003716 * freed by the caller. It also supports being passed a NULL which results in the same
3717 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003718 * Example of use :
3719 * parse(cmd, &err); (callee: memprintf(&err, ...))
3720 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3721 * free(err);
3722 */
3723char *indent_msg(char **out, int level)
3724{
3725 char *ret, *in, *p;
3726 int needed = 0;
3727 int lf = 0;
3728 int lastlf = 0;
3729 int len;
3730
Willy Tarreau70eec382012-10-10 08:56:47 +02003731 if (!out || !*out)
3732 return NULL;
3733
Willy Tarreau21c705b2012-09-14 11:40:36 +02003734 in = *out - 1;
3735 while ((in = strchr(in + 1, '\n')) != NULL) {
3736 lastlf = in - *out;
3737 lf++;
3738 }
3739
3740 if (!lf) /* single line, no LF, return it as-is */
3741 return *out;
3742
3743 len = strlen(*out);
3744
3745 if (lf == 1 && lastlf == len - 1) {
3746 /* single line, LF at end, strip it and return as-is */
3747 (*out)[lastlf] = 0;
3748 return *out;
3749 }
3750
3751 /* OK now we have at least one LF, we need to process the whole string
3752 * as a multi-line string. What we'll do :
3753 * - prefix with an LF if there is none
3754 * - add <level> spaces before each line
3755 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3756 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3757 */
3758
3759 needed = 1 + level * (lf + 1) + len + 1;
3760 p = ret = malloc(needed);
3761 in = *out;
3762
3763 /* skip initial LFs */
3764 while (*in == '\n')
3765 in++;
3766
3767 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3768 while (*in) {
3769 *p++ = '\n';
3770 memset(p, ' ', level);
3771 p += level;
3772 do {
3773 *p++ = *in++;
3774 } while (*in && *in != '\n');
3775 if (*in)
3776 in++;
3777 }
3778 *p = 0;
3779
3780 free(*out);
3781 *out = ret;
3782
3783 return ret;
3784}
3785
Willy Tarreaua2c99112019-08-21 13:17:37 +02003786/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3787 * and end of lines replaced with <eol> if not 0. The first line to indent has
3788 * to be indicated in <first> (starts at zero), so that it is possible to skip
3789 * indenting the first line if it has to be appended after an existing message.
3790 * Empty strings are never indented, and NULL strings are considered empty both
3791 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3792 * character, non-zero otherwise.
3793 */
3794int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3795{
3796 int bol, lf;
3797 int pfxlen = pfx ? strlen(pfx) : 0;
3798
3799 if (!in)
3800 return 0;
3801
3802 bol = 1;
3803 lf = 0;
3804 while (*in) {
3805 if (bol && pfxlen) {
3806 if (first > 0)
3807 first--;
3808 else
3809 b_putblk(out, pfx, pfxlen);
3810 bol = 0;
3811 }
3812
3813 lf = (*in == '\n');
3814 bol |= lf;
3815 b_putchr(out, (lf && eol) ? eol : *in);
3816 in++;
3817 }
3818 return lf;
3819}
3820
Willy Tarreau9d22e562019-03-29 18:49:09 +01003821/* removes environment variable <name> from the environment as found in
3822 * environ. This is only provided as an alternative for systems without
3823 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003824 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003825 * <name> and to replace the matching pointers with the last pointer of
3826 * the array (since variables are not ordered).
3827 * It always returns 0 (success).
3828 */
3829int my_unsetenv(const char *name)
3830{
3831 extern char **environ;
3832 char **p = environ;
3833 int vars;
3834 int next;
3835 int len;
3836
3837 len = strlen(name);
3838 for (vars = 0; p[vars]; vars++)
3839 ;
3840 next = 0;
3841 while (next < vars) {
3842 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3843 next++;
3844 continue;
3845 }
3846 if (next < vars - 1)
3847 p[next] = p[vars - 1];
3848 p[--vars] = NULL;
3849 }
3850 return 0;
3851}
3852
Willy Tarreaudad36a32013-03-11 01:20:04 +01003853/* Convert occurrences of environment variables in the input string to their
3854 * corresponding value. A variable is identified as a series of alphanumeric
3855 * characters or underscores following a '$' sign. The <in> string must be
3856 * free()able. NULL returns NULL. The resulting string might be reallocated if
3857 * some expansion is made. Variable names may also be enclosed into braces if
3858 * needed (eg: to concatenate alphanum characters).
3859 */
3860char *env_expand(char *in)
3861{
3862 char *txt_beg;
3863 char *out;
3864 char *txt_end;
3865 char *var_beg;
3866 char *var_end;
3867 char *value;
3868 char *next;
3869 int out_len;
3870 int val_len;
3871
3872 if (!in)
3873 return in;
3874
3875 value = out = NULL;
3876 out_len = 0;
3877
3878 txt_beg = in;
3879 do {
3880 /* look for next '$' sign in <in> */
3881 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3882
3883 if (!*txt_end && !out) /* end and no expansion performed */
3884 return in;
3885
3886 val_len = 0;
3887 next = txt_end;
3888 if (*txt_end == '$') {
3889 char save;
3890
3891 var_beg = txt_end + 1;
3892 if (*var_beg == '{')
3893 var_beg++;
3894
3895 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003896 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003897 var_end++;
3898 }
3899
3900 next = var_end;
3901 if (*var_end == '}' && (var_beg > txt_end + 1))
3902 next++;
3903
3904 /* get value of the variable name at this location */
3905 save = *var_end;
3906 *var_end = '\0';
3907 value = getenv(var_beg);
3908 *var_end = save;
3909 val_len = value ? strlen(value) : 0;
3910 }
3911
Hubert Verstraete831962e2016-06-28 22:44:26 +02003912 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003913 if (txt_end > txt_beg) {
3914 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3915 out_len += txt_end - txt_beg;
3916 }
3917 if (val_len) {
3918 memcpy(out + out_len, value, val_len);
3919 out_len += val_len;
3920 }
3921 out[out_len] = 0;
3922 txt_beg = next;
3923 } while (*txt_beg);
3924
3925 /* here we know that <out> was allocated and that we don't need <in> anymore */
3926 free(in);
3927 return out;
3928}
3929
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003930
3931/* same as strstr() but case-insensitive and with limit length */
3932const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3933{
3934 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003935 unsigned int slen, plen;
3936 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003937
3938 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3939 return NULL;
3940
3941 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3942 return str1;
3943
3944 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3945 return NULL;
3946
3947 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
Willy Tarreauf278eec2020-07-05 21:46:32 +02003948 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003949 start++;
3950 slen--;
3951 tmp1++;
3952
3953 if (tmp1 >= len_str1)
3954 return NULL;
3955
3956 /* if pattern longer than string */
3957 if (slen < plen)
3958 return NULL;
3959 }
3960
3961 sptr = start;
3962 pptr = (char *)str2;
3963
3964 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02003965 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003966 sptr++;
3967 pptr++;
3968 tmp2++;
3969
3970 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3971 return start;
3972 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3973 return NULL;
3974 }
3975 }
3976 return NULL;
3977}
3978
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003979/* This function read the next valid utf8 char.
3980 * <s> is the byte srray to be decode, <len> is its length.
3981 * The function returns decoded char encoded like this:
3982 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3983 * are the length read. The decoded character is stored in <c>.
3984 */
3985unsigned char utf8_next(const char *s, int len, unsigned int *c)
3986{
3987 const unsigned char *p = (unsigned char *)s;
3988 int dec;
3989 unsigned char code = UTF8_CODE_OK;
3990
3991 if (len < 1)
3992 return UTF8_CODE_OK;
3993
3994 /* Check the type of UTF8 sequence
3995 *
3996 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3997 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3998 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3999 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4000 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4001 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4002 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4003 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4004 */
4005 switch (*p) {
4006 case 0x00 ... 0x7f:
4007 *c = *p;
4008 return UTF8_CODE_OK | 1;
4009
4010 case 0x80 ... 0xbf:
4011 *c = *p;
4012 return UTF8_CODE_BADSEQ | 1;
4013
4014 case 0xc0 ... 0xdf:
4015 if (len < 2) {
4016 *c = *p;
4017 return UTF8_CODE_BADSEQ | 1;
4018 }
4019 *c = *p & 0x1f;
4020 dec = 1;
4021 break;
4022
4023 case 0xe0 ... 0xef:
4024 if (len < 3) {
4025 *c = *p;
4026 return UTF8_CODE_BADSEQ | 1;
4027 }
4028 *c = *p & 0x0f;
4029 dec = 2;
4030 break;
4031
4032 case 0xf0 ... 0xf7:
4033 if (len < 4) {
4034 *c = *p;
4035 return UTF8_CODE_BADSEQ | 1;
4036 }
4037 *c = *p & 0x07;
4038 dec = 3;
4039 break;
4040
4041 case 0xf8 ... 0xfb:
4042 if (len < 5) {
4043 *c = *p;
4044 return UTF8_CODE_BADSEQ | 1;
4045 }
4046 *c = *p & 0x03;
4047 dec = 4;
4048 break;
4049
4050 case 0xfc ... 0xfd:
4051 if (len < 6) {
4052 *c = *p;
4053 return UTF8_CODE_BADSEQ | 1;
4054 }
4055 *c = *p & 0x01;
4056 dec = 5;
4057 break;
4058
4059 case 0xfe ... 0xff:
4060 default:
4061 *c = *p;
4062 return UTF8_CODE_BADSEQ | 1;
4063 }
4064
4065 p++;
4066
4067 while (dec > 0) {
4068
4069 /* need 0x10 for the 2 first bits */
4070 if ( ( *p & 0xc0 ) != 0x80 )
4071 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4072
4073 /* add data at char */
4074 *c = ( *c << 6 ) | ( *p & 0x3f );
4075
4076 dec--;
4077 p++;
4078 }
4079
4080 /* Check ovelong encoding.
4081 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4082 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4083 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4084 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004085 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004086 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4087 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4088 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4089 code |= UTF8_CODE_OVERLONG;
4090
4091 /* Check invalid UTF8 range. */
4092 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4093 (*c >= 0xfffe && *c <= 0xffff))
4094 code |= UTF8_CODE_INVRANGE;
4095
4096 return code | ((p-(unsigned char *)s)&0x0f);
4097}
4098
Maxime de Roucydc887852016-05-13 23:52:54 +02004099/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4100 * On failure : return 0 and <err> filled with an error message.
4101 * The caller is responsible for freeing the <err> and <str> copy
4102 * memory area using free()
4103 */
4104int list_append_word(struct list *li, const char *str, char **err)
4105{
4106 struct wordlist *wl;
4107
4108 wl = calloc(1, sizeof(*wl));
4109 if (!wl) {
4110 memprintf(err, "out of memory");
4111 goto fail_wl;
4112 }
4113
4114 wl->s = strdup(str);
4115 if (!wl->s) {
4116 memprintf(err, "out of memory");
4117 goto fail_wl_s;
4118 }
4119
4120 LIST_ADDQ(li, &wl->list);
4121
4122 return 1;
4123
4124fail_wl_s:
4125 free(wl->s);
4126fail_wl:
4127 free(wl);
4128 return 0;
4129}
4130
Willy Tarreau37101052019-05-20 16:48:20 +02004131/* indicates if a memory location may safely be read or not. The trick consists
4132 * in performing a harmless syscall using this location as an input and letting
4133 * the operating system report whether it's OK or not. For this we have the
4134 * stat() syscall, which will return EFAULT when the memory location supposed
4135 * to contain the file name is not readable. If it is readable it will then
4136 * either return 0 if the area contains an existing file name, or -1 with
4137 * another code. This must not be abused, and some audit systems might detect
4138 * this as abnormal activity. It's used only for unsafe dumps.
4139 */
4140int may_access(const void *ptr)
4141{
4142 struct stat buf;
4143
4144 if (stat(ptr, &buf) == 0)
4145 return 1;
4146 if (errno == EFAULT)
4147 return 0;
4148 return 1;
4149}
4150
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004151/* print a string of text buffer to <out>. The format is :
4152 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4153 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4154 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4155 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004156int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004157{
4158 unsigned char c;
4159 int ptr = 0;
4160
4161 while (buf[ptr] && ptr < bsize) {
4162 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004163 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004164 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004165 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004166 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004167 }
4168 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004169 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004170 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004171 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004172 switch (c) {
4173 case ' ': c = ' '; break;
4174 case '\t': c = 't'; break;
4175 case '\n': c = 'n'; break;
4176 case '\r': c = 'r'; break;
4177 case '\e': c = 'e'; break;
4178 case '\\': c = '\\'; break;
4179 case '=': c = '='; break;
4180 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004181 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004182 }
4183 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004184 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004185 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004186 out->area[out->data++] = '\\';
4187 out->area[out->data++] = 'x';
4188 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4189 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004190 }
4191 ptr++;
4192 }
4193
4194 return ptr;
4195}
4196
4197/* print a buffer in hexa.
4198 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4199 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004200int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004201{
4202 unsigned char c;
4203 int ptr = 0;
4204
4205 while (ptr < bsize) {
4206 c = buf[ptr];
4207
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004208 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004209 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004210 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4211 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004212
4213 ptr++;
4214 }
4215 return ptr;
4216}
4217
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004218/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4219 * prepending each line with prefix <pfx>. The output is *not* initialized.
4220 * The output will not wrap pas the buffer's end so it is more optimal if the
4221 * caller makes sure the buffer is aligned first. A trailing zero will always
4222 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004223 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4224 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004225 */
Willy Tarreau37101052019-05-20 16:48:20 +02004226void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004227{
4228 const unsigned char *d = buf;
4229 int i, j, start;
4230
4231 d = (const unsigned char *)(((unsigned long)buf) & -16);
4232 start = ((unsigned long)buf) & 15;
4233
4234 for (i = 0; i < start + len; i += 16) {
4235 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4236
Willy Tarreau37101052019-05-20 16:48:20 +02004237 // 0: unchecked, 1: checked safe, 2: danger
4238 unsafe = !!unsafe;
4239 if (unsafe && !may_access(d + i))
4240 unsafe = 2;
4241
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004242 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004243 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004244 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004245 else if (unsafe > 1)
4246 chunk_strcat(out, "** ");
4247 else
4248 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004249
4250 if (j == 7)
4251 chunk_strcat(out, "- ");
4252 }
4253 chunk_strcat(out, " ");
4254 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004255 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004256 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004257 else if (unsafe > 1)
4258 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004259 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004260 chunk_appendf(out, "%c", d[i + j]);
4261 else
4262 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004263 }
4264 chunk_strcat(out, "\n");
4265 }
4266}
4267
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004268/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4269 * enclosed in brackets after the address itself, formatted on 14 chars
4270 * including the "0x" prefix. This is meant to be used as a prefix for code
4271 * areas. For example:
4272 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4273 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4274 * is emitted. A NULL <pfx> will be considered empty.
4275 */
4276void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4277{
4278 int ok = 0;
4279 int i;
4280
4281 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4282
4283 for (i = 0; i < n; i++) {
4284 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4285 ok = may_access(addr + i);
4286 if (ok)
4287 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4288 else
4289 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4290 }
4291}
4292
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004293/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4294 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4295 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4296 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4297 * lines are respected within the limit of 70 output chars. Lines that are
4298 * continuation of a previous truncated line begin with "+" instead of " "
4299 * after the offset. The new pointer is returned.
4300 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004301int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004302 int *line, int ptr)
4303{
4304 int end;
4305 unsigned char c;
4306
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004307 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004308 if (end > out->size)
4309 return ptr;
4310
4311 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4312
4313 while (ptr < len && ptr < bsize) {
4314 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004315 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004316 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004317 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004318 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004319 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004320 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004321 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004322 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004323 switch (c) {
4324 case '\t': c = 't'; break;
4325 case '\n': c = 'n'; break;
4326 case '\r': c = 'r'; break;
4327 case '\e': c = 'e'; break;
4328 case '\\': c = '\\'; break;
4329 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004330 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004331 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004332 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004333 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004334 out->area[out->data++] = '\\';
4335 out->area[out->data++] = 'x';
4336 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4337 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004338 }
4339 if (buf[ptr++] == '\n') {
4340 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004341 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004342 *line = ptr;
4343 return ptr;
4344 }
4345 }
4346 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004347 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004348 return ptr;
4349}
4350
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004351/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004352 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4353 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004354 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004355void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4356 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004357{
Willy Tarreau73459792017-04-11 07:58:08 +02004358 unsigned int i;
4359 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004360
4361 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4362 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004363 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004364 for (j = 0; j < 8; j++) {
4365 if (b + j >= 0 && b + j < len)
4366 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4367 else
4368 fprintf(out, " ");
4369 }
4370
4371 if (b + j >= 0 && b + j < len)
4372 fputc('-', out);
4373 else
4374 fputc(' ', out);
4375
4376 for (j = 8; j < 16; j++) {
4377 if (b + j >= 0 && b + j < len)
4378 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4379 else
4380 fprintf(out, " ");
4381 }
4382
4383 fprintf(out, " ");
4384 for (j = 0; j < 16; j++) {
4385 if (b + j >= 0 && b + j < len) {
4386 if (isprint((unsigned char)buf[b + j]))
4387 fputc((unsigned char)buf[b + j], out);
4388 else
4389 fputc('.', out);
4390 }
4391 else
4392 fputc(' ', out);
4393 }
4394 fputc('\n', out);
4395 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004396}
4397
Willy Tarreaubb869862020-04-16 10:52:41 +02004398/* Tries to report the executable path name on platforms supporting this. If
4399 * not found or not possible, returns NULL.
4400 */
4401const char *get_exec_path()
4402{
4403 const char *ret = NULL;
4404
4405#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4406 long execfn = getauxval(AT_EXECFN);
4407
4408 if (execfn && execfn != ENOENT)
4409 ret = (const char *)execfn;
4410#endif
4411 return ret;
4412}
4413
Baruch Siache1651b22020-07-24 07:52:20 +03004414#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004415/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4416 * also returns the symbol size in <size>, otherwise returns 0 there.
4417 */
4418static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4419{
4420 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004421#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004422 const ElfW(Sym) *sym;
4423
4424 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4425 if (ret)
4426 *size = sym ? sym->st_size : 0;
4427#else
4428 ret = dladdr(addr, dli);
4429 *size = 0;
4430#endif
4431 return ret;
4432}
4433#endif
4434
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004435/* Tries to append to buffer <buf> some indications about the symbol at address
4436 * <addr> using the following form:
4437 * lib:+0xoffset (unresolvable address from lib's base)
4438 * main+0xoffset (unresolvable address from main (+/-))
4439 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4440 * name (resolved exact exec address)
4441 * lib:name (resolved exact lib address)
4442 * name+0xoffset/0xsize (resolved address within exec symbol)
4443 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4444 *
4445 * The file name (lib or executable) is limited to what lies between the last
4446 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4447 * the output if not null. The file is not dumped when it's the same as the one
Baruch Siache1651b22020-07-24 07:52:20 +03004448 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004449 *
4450 * The symbol's base address is returned, or NULL when unresolved, in order to
4451 * allow the caller to match it against known ones.
4452 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004453const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004454{
4455 const struct {
4456 const void *func;
4457 const char *name;
4458 } fcts[] = {
4459 { .func = process_stream, .name = "process_stream" },
4460 { .func = task_run_applet, .name = "task_run_applet" },
4461 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4462 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4463 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4464 { .func = listener_accept, .name = "listener_accept" },
4465 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4466 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4467#ifdef USE_LUA
4468 { .func = hlua_process_task, .name = "hlua_process_task" },
4469#endif
4470#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4471 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4472 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4473#endif
4474 };
4475
Baruch Siache1651b22020-07-24 07:52:20 +03004476#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004477 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004478 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004479 const char *fname, *p;
4480#endif
4481 int i;
4482
4483 if (pfx)
4484 chunk_appendf(buf, "%s", pfx);
4485
4486 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4487 if (addr == fcts[i].func) {
4488 chunk_appendf(buf, "%s", fcts[i].name);
4489 return addr;
4490 }
4491 }
4492
Baruch Siache1651b22020-07-24 07:52:20 +03004493#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004494 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004495 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004496 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004497
4498 /* 1. prefix the library name if it's not the same object as the one
4499 * that contains the main function. The name is picked between last '/'
4500 * and first following '.'.
4501 */
4502 if (!dladdr(main, &dli_main))
4503 dli_main.dli_fbase = NULL;
4504
4505 if (dli_main.dli_fbase != dli.dli_fbase) {
4506 fname = dli.dli_fname;
4507 p = strrchr(fname, '/');
4508 if (p++)
4509 fname = p;
4510 p = strchr(fname, '.');
4511 if (!p)
4512 p = fname + strlen(fname);
4513
4514 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4515 }
4516
4517 /* 2. symbol name */
4518 if (dli.dli_sname) {
4519 /* known, dump it and return symbol's address (exact or relative) */
4520 chunk_appendf(buf, "%s", dli.dli_sname);
4521 if (addr != dli.dli_saddr) {
4522 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004523 if (size)
4524 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004525 }
4526 return dli.dli_saddr;
4527 }
4528 else if (dli_main.dli_fbase != dli.dli_fbase) {
4529 /* unresolved symbol from a known library, report relative offset */
4530 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4531 return NULL;
4532 }
Baruch Siache1651b22020-07-24 07:52:20 +03004533#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004534 unknown:
4535 /* unresolved symbol from the main file, report relative offset to main */
4536 if ((void*)addr < (void*)main)
4537 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4538 else
4539 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4540 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004541}
4542
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004543/*
4544 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004545 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004546 *
4547 * First, initializes the value with <sz> as address to 0 and initializes the
4548 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4549 * address updating <sz> pointed value to the size of this array.
4550 *
4551 * Returns 1 if succeeded, 0 if not.
4552 */
4553int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4554{
4555 unsigned int *n;
4556 const char *s, *end;
4557
4558 s = str;
4559 *sz = 0;
4560 end = str + strlen(str);
4561 *nums = n = NULL;
4562
4563 while (1) {
4564 unsigned int r;
4565
4566 if (s >= end)
4567 break;
4568
4569 r = read_uint(&s, end);
4570 /* Expected characters after having read an uint: '\0' or '.',
4571 * if '.', must not be terminal.
4572 */
4573 if (*s != '\0'&& (*s++ != '.' || s == end))
4574 return 0;
4575
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004576 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004577 if (!n)
4578 return 0;
4579
4580 n[(*sz)++] = r;
4581 }
4582 *nums = n;
4583
4584 return 1;
4585}
4586
Willy Tarreau4d589e72019-08-23 19:02:26 +02004587
4588/* returns the number of bytes needed to encode <v> as a varint. An inline
4589 * version exists for use with constants (__varint_bytes()).
4590 */
4591int varint_bytes(uint64_t v)
4592{
4593 int len = 1;
4594
4595 if (v >= 240) {
4596 v = (v - 240) >> 4;
4597 while (1) {
4598 len++;
4599 if (v < 128)
4600 break;
4601 v = (v - 128) >> 7;
4602 }
4603 }
4604 return len;
4605}
4606
Willy Tarreau52bf8392020-03-08 00:42:37 +01004607
4608/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004609static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004610
4611/* This is a thread-safe implementation of xoroshiro128** described below:
4612 * http://prng.di.unimi.it/
4613 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4614 * supports fast jumps and passes all common quality tests. It is thread-safe,
4615 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4616 * local lock on other ones.
4617 */
4618uint64_t ha_random64()
4619{
4620 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004621 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4622 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004623
4624#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4625 static HA_SPINLOCK_T rand_lock;
4626
4627 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4628#endif
4629
4630 old[0] = ha_random_state[0];
4631 old[1] = ha_random_state[1];
4632
4633#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4634 do {
4635#endif
4636 result = rotl64(old[0] * 5, 7) * 9;
4637 new[1] = old[0] ^ old[1];
4638 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4639 new[1] = rotl64(new[1], 37); // c
4640
4641#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4642 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4643#else
4644 ha_random_state[0] = new[0];
4645 ha_random_state[1] = new[1];
4646#if defined(USE_THREAD)
4647 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4648#endif
4649#endif
4650 return result;
4651}
4652
4653/* seeds the random state using up to <len> bytes from <seed>, starting with
4654 * the first non-zero byte.
4655 */
4656void ha_random_seed(const unsigned char *seed, size_t len)
4657{
4658 size_t pos;
4659
4660 /* the seed must not be all zeroes, so we pre-fill it with alternating
4661 * bits and overwrite part of them with the block starting at the first
4662 * non-zero byte from the seed.
4663 */
4664 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4665
4666 for (pos = 0; pos < len; pos++)
4667 if (seed[pos] != 0)
4668 break;
4669
4670 if (pos == len)
4671 return;
4672
4673 seed += pos;
4674 len -= pos;
4675
4676 if (len > sizeof(ha_random_state))
4677 len = sizeof(ha_random_state);
4678
4679 memcpy(ha_random_state, seed, len);
4680}
4681
4682/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4683 * and is equivalent to calling ha_random64() as many times. It is used to
4684 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4685 * different generators (i.e. different processes after a fork). The <dist>
4686 * argument is the distance to jump to and is used in a loop so it rather not
4687 * be too large if the processing time is a concern.
4688 *
4689 * BEWARE: this function is NOT thread-safe and must not be called during
4690 * concurrent accesses to ha_random64().
4691 */
4692void ha_random_jump96(uint32_t dist)
4693{
4694 while (dist--) {
4695 uint64_t s0 = 0;
4696 uint64_t s1 = 0;
4697 int b;
4698
4699 for (b = 0; b < 64; b++) {
4700 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4701 s0 ^= ha_random_state[0];
4702 s1 ^= ha_random_state[1];
4703 }
4704 ha_random64();
4705 }
4706
4707 for (b = 0; b < 64; b++) {
4708 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4709 s0 ^= ha_random_state[0];
4710 s1 ^= ha_random_state[1];
4711 }
4712 ha_random64();
4713 }
4714 ha_random_state[0] = s0;
4715 ha_random_state[1] = s1;
4716 }
4717}
4718
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004719/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4720 * bytes large.
4721 */
4722void ha_generate_uuid(struct buffer *output)
4723{
4724 uint32_t rnd[4];
4725 uint64_t last;
4726
4727 last = ha_random64();
4728 rnd[0] = last;
4729 rnd[1] = last >> 32;
4730
4731 last = ha_random64();
4732 rnd[2] = last;
4733 rnd[3] = last >> 32;
4734
4735 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4736 rnd[0],
4737 rnd[1] & 0xFFFF,
4738 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4739 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4740 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4741}
4742
4743
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004744/* only used by parse_line() below. It supports writing in place provided that
4745 * <in> is updated to the next location before calling it. In that case, the
4746 * char at <in> may be overwritten.
4747 */
4748#define EMIT_CHAR(x) \
4749 do { \
4750 char __c = (char)(x); \
4751 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4752 err |= PARSE_ERR_OVERLAP; \
4753 if (outpos >= outmax) \
4754 err |= PARSE_ERR_TOOLARGE; \
4755 if (!err) \
4756 out[outpos] = __c; \
4757 outpos++; \
4758 } while (0)
4759
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004760/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004761 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4762 * extraneous ones are not emitted but <outlen> is updated so that the caller
4763 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4764 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004765 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4766 * it is guaranteed that at least one arg will point to the zero. It is safe
4767 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004768 *
4769 * <out> may overlap with <in> provided that it never goes further, in which
4770 * case the parser will accept to perform in-place parsing and unquoting/
4771 * unescaping but only if environment variables do not lead to expansion that
4772 * causes overlapping, otherwise the input string being destroyed, the error
4773 * will not be recoverable. Note that even during out-of-place <in> will
4774 * experience temporary modifications in-place for variable resolution and must
4775 * be writable, and will also receive zeroes to delimit words when using
4776 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4777 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4778 * starting point of the first invalid character sequence or unmatched
4779 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4780 * error reporting might be difficult since zeroes will have been inserted into
4781 * the string. One solution for the caller may consist in replacing all args
4782 * delimiters with spaces in this case.
4783 */
4784uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4785{
4786 char *quote = NULL;
4787 char *brace = NULL;
4788 unsigned char hex1, hex2;
4789 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004790 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004791 size_t outpos = 0;
4792 int squote = 0;
4793 int dquote = 0;
4794 int arg = 0;
4795 uint32_t err = 0;
4796
4797 *nbargs = 0;
4798 *outlen = 0;
4799
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004800 /* argsmax may be -1 here, protecting args[] from any write */
4801 if (arg < argsmax)
4802 args[arg] = out;
4803
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004804 while (1) {
4805 if (*in >= '-' && *in != '\\') {
4806 /* speedup: directly send all regular chars starting
4807 * with '-', '.', '/', alnum etc...
4808 */
4809 EMIT_CHAR(*in++);
4810 continue;
4811 }
4812 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4813 /* end of line */
4814 break;
4815 }
4816 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4817 /* comment */
4818 break;
4819 }
4820 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4821 if (dquote) {
4822 dquote = 0;
4823 quote = NULL;
4824 }
4825 else {
4826 dquote = 1;
4827 quote = in;
4828 }
4829 in++;
4830 continue;
4831 }
4832 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4833 if (squote) {
4834 squote = 0;
4835 quote = NULL;
4836 }
4837 else {
4838 squote = 1;
4839 quote = in;
4840 }
4841 in++;
4842 continue;
4843 }
4844 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4845 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4846 * C equivalent value but only when they have a special meaning and within
4847 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4848 */
4849 char tosend = *in;
4850
4851 switch (in[1]) {
4852 case ' ':
4853 case '\\':
4854 tosend = in[1];
4855 in++;
4856 break;
4857
4858 case 't':
4859 tosend = '\t';
4860 in++;
4861 break;
4862
4863 case 'n':
4864 tosend = '\n';
4865 in++;
4866 break;
4867
4868 case 'r':
4869 tosend = '\r';
4870 in++;
4871 break;
4872
4873 case '#':
4874 /* escaping of "#" only if comments are supported */
4875 if (opts & PARSE_OPT_SHARP)
4876 in++;
4877 tosend = *in;
4878 break;
4879
4880 case '\'':
4881 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4882 if (opts & PARSE_OPT_SQUOTE && !squote)
4883 in++;
4884 tosend = *in;
4885 break;
4886
4887 case '"':
4888 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4889 if (opts & PARSE_OPT_DQUOTE && !squote)
4890 in++;
4891 tosend = *in;
4892 break;
4893
4894 case '$':
4895 /* escaping of '$' only inside double quotes and only if env supported */
4896 if (opts & PARSE_OPT_ENV && dquote)
4897 in++;
4898 tosend = *in;
4899 break;
4900
4901 case 'x':
4902 if (!ishex(in[2]) || !ishex(in[3])) {
4903 /* invalid or incomplete hex sequence */
4904 err |= PARSE_ERR_HEX;
4905 if (errptr)
4906 *errptr = in;
4907 goto leave;
4908 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02004909 hex1 = toupper((unsigned char)in[2]) - '0';
4910 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004911 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
4912 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
4913 tosend = (hex1 << 4) + hex2;
4914 in += 3;
4915 break;
4916
4917 default:
4918 /* other combinations are not escape sequences */
4919 break;
4920 }
4921
4922 in++;
4923 EMIT_CHAR(tosend);
4924 }
4925 else if (isspace((unsigned char)*in) && !squote && !dquote) {
4926 /* a non-escaped space is an argument separator */
4927 while (isspace((unsigned char)*in))
4928 in++;
4929 EMIT_CHAR(0);
4930 arg++;
4931 if (arg < argsmax)
4932 args[arg] = out + outpos;
4933 else
4934 err |= PARSE_ERR_TOOMANY;
4935 }
4936 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
4937 /* environment variables are evaluated anywhere, or only
4938 * inside double quotes if they are supported.
4939 */
4940 char *var_name;
4941 char save_char;
4942 char *value;
4943
4944 in++;
4945
4946 if (*in == '{')
4947 brace = in++;
4948
4949 if (!isalpha((unsigned char)*in) && *in != '_') {
4950 /* unacceptable character in variable name */
4951 err |= PARSE_ERR_VARNAME;
4952 if (errptr)
4953 *errptr = in;
4954 goto leave;
4955 }
4956
4957 var_name = in;
4958 while (isalnum((unsigned char)*in) || *in == '_')
4959 in++;
4960
4961 save_char = *in;
4962 *in = '\0';
4963 value = getenv(var_name);
4964 *in = save_char;
4965
4966 if (brace) {
4967 if (*in != '}') {
4968 /* unmatched brace */
4969 err |= PARSE_ERR_BRACE;
4970 if (errptr)
4971 *errptr = brace;
4972 goto leave;
4973 }
4974 in++;
4975 brace = NULL;
4976 }
4977
4978 if (value) {
4979 while (*value)
4980 EMIT_CHAR(*value++);
4981 }
4982 }
4983 else {
4984 /* any other regular char */
4985 EMIT_CHAR(*in++);
4986 }
4987 }
4988
4989 /* end of output string */
4990 EMIT_CHAR(0);
4991 arg++;
4992
4993 if (quote) {
4994 /* unmatched quote */
4995 err |= PARSE_ERR_QUOTE;
4996 if (errptr)
4997 *errptr = quote;
4998 goto leave;
4999 }
5000 leave:
5001 *nbargs = arg;
5002 *outlen = outpos;
5003
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005004 /* empty all trailing args by making them point to the trailing zero,
5005 * at least the last one in any case.
5006 */
5007 if (arg > argsmax)
5008 arg = argsmax;
5009
5010 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005011 args[arg++] = out + outpos - 1;
5012
5013 return err;
5014}
5015#undef EMIT_CHAR
5016
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005017/* This is used to sanitize an input line that's about to be used for error reporting.
5018 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5019 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5020 * If non-printable chars are present in the output. It returns the new offset <pos>
5021 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5022 * be at least 6 to support two "..." otherwise the result is undefined. The line
5023 * itself must have at least 7 chars allocated for the same reason.
5024 */
5025size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5026{
5027 size_t shift = 0;
5028 char *out = line;
5029 char *in = line;
5030 char *end = line + width;
5031
5032 if (pos >= width) {
5033 /* if we have to shift, we'll be out of context, so let's
5034 * try to put <pos> at the center of width.
5035 */
5036 shift = pos - width / 2;
5037 in += shift + 3;
5038 end = out + width - 3;
5039 out[0] = out[1] = out[2] = '.';
5040 out += 3;
5041 }
5042
5043 while (out < end && *in) {
5044 if (isspace((unsigned char)*in))
5045 *out++ = ' ';
5046 else if (isprint((unsigned char)*in))
5047 *out++ = *in;
5048 else
5049 *out++ = '?';
5050 in++;
5051 }
5052
5053 if (end < line + width) {
5054 out[0] = out[1] = out[2] = '.';
5055 out += 3;
5056 }
5057
5058 *out++ = 0;
5059 return pos - shift;
5060}
5061
Willy Tarreaubaaee002006-06-26 02:48:02 +02005062/*
5063 * Local variables:
5064 * c-indent-level: 8
5065 * c-basic-offset: 8
5066 * End:
5067 */