blob: e543fd6cd3a5bd94b4d14de62d6def1c4e70adfe [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 Tarreaucd3a55912020-09-04 15:30:46 +0200858 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
859 * still honored so it is possible for the caller to know whether a resolution
860 * failed by clearing this flag and checking if <fqdn> was filled, indicating
861 * 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 Tarreaua93e5c72020-09-15 14:01:16 +0200866 *
867 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
868 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100869 */
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200870struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd, char **err, const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100871{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100872 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100873 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100874 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100875 char *port1, *port2;
876 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200877 int abstract = 0;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200878 int is_udp = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200879 int new_fd = -1;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100880
881 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200882 if (fqdn)
883 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884
Willy Tarreaudad36a32013-03-11 01:20:04 +0100885 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100886 if (str2 == NULL) {
887 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100888 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100889 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200890
Willy Tarreau9f69f462015-09-08 16:01:25 +0200891 if (!*str2) {
892 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
893 goto out;
894 }
895
Willy Tarreau24709282013-03-10 21:32:12 +0100896 memset(&ss, 0, sizeof(ss));
897
898 if (strncmp(str2, "unix@", 5) == 0) {
899 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200900 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100901 ss.ss_family = AF_UNIX;
902 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200903 else if (strncmp(str2, "abns@", 5) == 0) {
904 str2 += 5;
905 abstract = 1;
906 ss.ss_family = AF_UNIX;
907 }
Willy Tarreau24709282013-03-10 21:32:12 +0100908 else if (strncmp(str2, "ipv4@", 5) == 0) {
909 str2 += 5;
910 ss.ss_family = AF_INET;
911 }
912 else if (strncmp(str2, "ipv6@", 5) == 0) {
913 str2 += 5;
914 ss.ss_family = AF_INET6;
915 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200916 else if (strncmp(str2, "udp4@", 5) == 0) {
917 str2 += 5;
918 ss.ss_family = AF_INET;
919 is_udp = 1;
920 }
921 else if (strncmp(str2, "udp6@", 5) == 0) {
922 str2 += 5;
923 ss.ss_family = AF_INET6;
924 is_udp = 1;
925 }
926 else if (strncmp(str2, "udp@", 4) == 0) {
927 str2 += 4;
928 ss.ss_family = AF_UNSPEC;
929 is_udp = 1;
930 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200931 else if (strncmp(str2, "fd@", 3) == 0) {
932 str2 += 3;
933 ss.ss_family = AF_CUST_EXISTING_FD;
934 }
935 else if (strncmp(str2, "sockpair@", 9) == 0) {
936 str2 += 9;
937 ss.ss_family = AF_CUST_SOCKPAIR;
938 }
Willy Tarreau24709282013-03-10 21:32:12 +0100939 else if (*str2 == '/') {
940 ss.ss_family = AF_UNIX;
941 }
942 else
943 ss.ss_family = AF_UNSPEC;
944
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200945 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200946 struct sockaddr_storage ss2;
947 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200948 char *endptr;
949
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200950 new_fd = strtol(str2, &endptr, 10);
951 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200952 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
953 goto out;
954 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200955
Willy Tarreaua215be22020-09-16 10:14:16 +0200956 /* just verify that it's a socket */
957 addr_len = sizeof(ss2);
958 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
959 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
960 goto out;
961 }
962
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200963 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
964 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200965 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200966 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100967 char *endptr;
968
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200969 new_fd = strtol(str2, &endptr, 10);
970 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100971 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100972 goto out;
973 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200974
Willy Tarreau6edc7222020-09-15 17:41:56 +0200975 if (opts & PA_O_SOCKET_FD) {
976 socklen_t addr_len;
977 int type;
978
979 addr_len = sizeof(ss);
980 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
981 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
982 goto out;
983 }
984
985 addr_len = sizeof(type);
986 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
987 (type == SOCK_STREAM) != !!(opts & PA_O_STREAM)) {
988 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
989 goto out;
990 }
991
992 porta = portl = porth = get_host_port(&ss);
993 } else if (opts & PA_O_RAW_FD) {
994 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
995 ((struct sockaddr_in *)&ss)->sin_port = 0;
996 } else {
997 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
998 goto out;
999 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001000 }
1001 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001002 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001003 int prefix_path_len;
1004 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001005 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001006
1007 /* complete unix socket path name during startup or soft-restart is
1008 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1009 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001010 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001011 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001012 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001013
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001014 adr_len = strlen(str2);
1015 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001016 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1017 goto out;
1018 }
1019
Willy Tarreauccfccef2014-05-10 01:49:15 +02001020 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001021 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001022 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001023 memcpy(un->sun_path, pfx, prefix_path_len);
1024 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001025 }
Willy Tarreau24709282013-03-10 21:32:12 +01001026 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001027 char *end = str2 + strlen(str2);
1028 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001029
mildisff5d5102015-10-26 18:50:08 +01001030 /* search for : or ] whatever comes first */
1031 for (chr = end-1; chr > str2; chr--) {
1032 if (*chr == ']' || *chr == ':')
1033 break;
1034 }
1035
1036 if (*chr == ':') {
1037 /* Found a colon before a closing-bracket, must be a port separator.
1038 * This guarantee backward compatibility.
1039 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001040 if (!(opts & PA_O_PORT_OK)) {
1041 memprintf(err, "port specification not permitted here in '%s'", str);
1042 goto out;
1043 }
mildisff5d5102015-10-26 18:50:08 +01001044 *chr++ = '\0';
1045 port1 = chr;
1046 }
1047 else {
1048 /* Either no colon and no closing-bracket
1049 * or directly ending with a closing-bracket.
1050 * However, no port.
1051 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001052 if (opts & PA_O_PORT_MAND) {
1053 memprintf(err, "missing port specification in '%s'", str);
1054 goto out;
1055 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001056 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001057 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001058
Willy Tarreau90807112020-02-25 08:16:33 +01001059 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001060 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001061 if (port2) {
1062 if (!(opts & PA_O_PORT_RANGE)) {
1063 memprintf(err, "port range not permitted here in '%s'", str);
1064 goto out;
1065 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001066 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001067 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001068 else
1069 port2 = port1;
1070 portl = atoi(port1);
1071 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001072
1073 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1074 memprintf(err, "invalid port '%s'", port1);
1075 goto out;
1076 }
1077
1078 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1079 memprintf(err, "invalid port '%s'", port2);
1080 goto out;
1081 }
1082
1083 if (portl > porth) {
1084 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1085 goto out;
1086 }
1087
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001088 porta = portl;
1089 }
1090 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001091 if (!(opts & PA_O_PORT_OFS)) {
1092 memprintf(err, "port offset not permitted here in '%s'", str);
1093 goto out;
1094 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001095 portl = atoi(port1 + 1);
1096 porta = -portl;
1097 }
1098 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001099 if (!(opts & PA_O_PORT_OFS)) {
1100 memprintf(err, "port offset not permitted here in '%s'", str);
1101 goto out;
1102 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001103 porth = atoi(port1 + 1);
1104 porta = porth;
1105 }
1106 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001107 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001108 goto out;
1109 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001110 else if (opts & PA_O_PORT_MAND) {
1111 memprintf(err, "missing port specification in '%s'", str);
1112 goto out;
1113 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001114
1115 /* first try to parse the IP without resolving. If it fails, it
1116 * tells us we need to keep a copy of the FQDN to resolve later
1117 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001118 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001119 */
1120 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001121 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1122 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001123 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1124 goto out;
1125 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001126
Willy Tarreauceccdd72016-11-02 22:27:10 +01001127 if (fqdn) {
1128 if (str2 != back)
1129 memmove(back, str2, strlen(str2) + 1);
1130 *fqdn = back;
1131 back = NULL;
1132 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001133 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001134 set_host_port(&ss, porta);
Emeric Brun3835c0d2020-07-07 09:46:09 +02001135 if (is_udp) {
1136 if (ss.ss_family == AF_INET6)
1137 ss.ss_family = AF_CUST_UDP6;
1138 else
1139 ss.ss_family = AF_CUST_UDP4;
1140 }
1141
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001142 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001143
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001144 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001145 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001146 if (port)
1147 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001148 if (low)
1149 *low = portl;
1150 if (high)
1151 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001152 if (fd)
1153 *fd = new_fd;
Willy Tarreau24709282013-03-10 21:32:12 +01001154 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001155 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001156}
1157
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001158/* converts <str> to a struct in_addr containing a network mask. It can be
1159 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001160 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001161 */
1162int str2mask(const char *str, struct in_addr *mask)
1163{
1164 if (strchr(str, '.') != NULL) { /* dotted notation */
1165 if (!inet_pton(AF_INET, str, mask))
1166 return 0;
1167 }
1168 else { /* mask length */
1169 char *err;
1170 unsigned long len = strtol(str, &err, 10);
1171
1172 if (!*str || (err && *err) || (unsigned)len > 32)
1173 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001174
1175 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001176 }
1177 return 1;
1178}
1179
Tim Duesterhus47185172018-01-25 16:24:49 +01001180/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001181 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001182 * if the conversion succeeds otherwise zero.
1183 */
1184int str2mask6(const char *str, struct in6_addr *mask)
1185{
1186 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1187 if (!inet_pton(AF_INET6, str, mask))
1188 return 0;
1189 }
1190 else { /* mask length */
1191 char *err;
1192 unsigned long len = strtol(str, &err, 10);
1193
1194 if (!*str || (err && *err) || (unsigned)len > 128)
1195 return 0;
1196
1197 len2mask6(len, mask);
1198 }
1199 return 1;
1200}
1201
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001202/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1203 * succeeds otherwise zero.
1204 */
1205int cidr2dotted(int cidr, struct in_addr *mask) {
1206
1207 if (cidr < 0 || cidr > 32)
1208 return 0;
1209
1210 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1211 return 1;
1212}
1213
Thierry Fournier70473a52016-02-17 17:12:14 +01001214/* Convert mask from bit length form to in_addr form.
1215 * This function never fails.
1216 */
1217void len2mask4(int len, struct in_addr *addr)
1218{
1219 if (len >= 32) {
1220 addr->s_addr = 0xffffffff;
1221 return;
1222 }
1223 if (len <= 0) {
1224 addr->s_addr = 0x00000000;
1225 return;
1226 }
1227 addr->s_addr = 0xffffffff << (32 - len);
1228 addr->s_addr = htonl(addr->s_addr);
1229}
1230
1231/* Convert mask from bit length form to in6_addr form.
1232 * This function never fails.
1233 */
1234void len2mask6(int len, struct in6_addr *addr)
1235{
1236 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1237 len -= 32;
1238 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1239 len -= 32;
1240 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1241 len -= 32;
1242 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1243}
1244
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001245/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001246 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001247 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001248 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001249 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1250 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001251int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001252{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001253 __label__ out_free, out_err;
1254 char *c, *s;
1255 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001256
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001257 s = strdup(str);
1258 if (!s)
1259 return 0;
1260
Willy Tarreaubaaee002006-06-26 02:48:02 +02001261 memset(mask, 0, sizeof(*mask));
1262 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001263
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001264 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001265 *c++ = '\0';
1266 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001267 if (!str2mask(c, mask))
1268 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001269 }
1270 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001271 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001272 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001273 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001274 struct hostent *he;
1275
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001276 if (!resolve)
1277 goto out_err;
1278
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001279 if ((he = gethostbyname(s)) == NULL) {
1280 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001281 }
1282 else
1283 *addr = *(struct in_addr *) *(he->h_addr_list);
1284 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001285
1286 ret_val = 1;
1287 out_free:
1288 free(s);
1289 return ret_val;
1290 out_err:
1291 ret_val = 0;
1292 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001293}
1294
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001295
1296/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001297 * converts <str> to two struct in6_addr* which must be pre-allocated.
1298 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001299 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001300 * Returns 1 if OK, 0 if error.
1301 */
1302int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1303{
1304 char *c, *s;
1305 int ret_val = 0;
1306 char *err;
1307 unsigned long len = 128;
1308
1309 s = strdup(str);
1310 if (!s)
1311 return 0;
1312
1313 memset(mask, 0, sizeof(*mask));
1314 memset(addr, 0, sizeof(*addr));
1315
1316 if ((c = strrchr(s, '/')) != NULL) {
1317 *c++ = '\0'; /* c points to the mask */
1318 if (!*c)
1319 goto out_free;
1320
1321 len = strtoul(c, &err, 10);
1322 if ((err && *err) || (unsigned)len > 128)
1323 goto out_free;
1324 }
1325 *mask = len; /* OK we have a valid mask in <len> */
1326
1327 if (!inet_pton(AF_INET6, s, addr))
1328 goto out_free;
1329
1330 ret_val = 1;
1331 out_free:
1332 free(s);
1333 return ret_val;
1334}
1335
1336
1337/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001338 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001339 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001340int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001341{
1342 int saw_digit, octets, ch;
1343 u_char tmp[4], *tp;
1344 const char *cp = addr;
1345
1346 saw_digit = 0;
1347 octets = 0;
1348 *(tp = tmp) = 0;
1349
1350 while (*addr) {
1351 unsigned char digit = (ch = *addr++) - '0';
1352 if (digit > 9 && ch != '.')
1353 break;
1354 if (digit <= 9) {
1355 u_int new = *tp * 10 + digit;
1356 if (new > 255)
1357 return 0;
1358 *tp = new;
1359 if (!saw_digit) {
1360 if (++octets > 4)
1361 return 0;
1362 saw_digit = 1;
1363 }
1364 } else if (ch == '.' && saw_digit) {
1365 if (octets == 4)
1366 return 0;
1367 *++tp = 0;
1368 saw_digit = 0;
1369 } else
1370 return 0;
1371 }
1372
1373 if (octets < 4)
1374 return 0;
1375
1376 memcpy(&dst->s_addr, tmp, 4);
1377 return addr-cp-1;
1378}
1379
1380/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001381 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001382 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001383 * the hostname. Actually only http and https are supported. <out> can be NULL.
1384 * This function returns the consumed length. It is useful if you parse complete
1385 * url like http://host:port/path, because the consumed length corresponds to
1386 * the first character of the path. If the conversion fails, it returns -1.
1387 *
1388 * This function tries to resolve the DNS name if haproxy is in starting mode.
1389 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001390 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001391int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001392{
1393 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001394 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001395 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001396 unsigned long long int http_code = 0;
1397 int default_port;
1398 struct hostent *he;
1399 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001400
1401 /* Firstly, try to find :// pattern */
1402 while (curr < url+ulen && url_code != 0x3a2f2f) {
1403 url_code = ((url_code & 0xffff) << 8);
1404 url_code += (unsigned char)*curr++;
1405 }
1406
1407 /* Secondly, if :// pattern is found, verify parsed stuff
1408 * before pattern is matching our http pattern.
1409 * If so parse ip address and port in uri.
1410 *
1411 * WARNING: Current code doesn't support dynamic async dns resolver.
1412 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001413 if (url_code != 0x3a2f2f)
1414 return -1;
1415
1416 /* Copy scheme, and utrn to lower case. */
1417 while (cp < curr - 3)
1418 http_code = (http_code << 8) + *cp++;
1419 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001420
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001421 /* HTTP or HTTPS url matching */
1422 if (http_code == 0x2020202068747470ULL) {
1423 default_port = 80;
1424 if (out)
1425 out->scheme = SCH_HTTP;
1426 }
1427 else if (http_code == 0x2020206874747073ULL) {
1428 default_port = 443;
1429 if (out)
1430 out->scheme = SCH_HTTPS;
1431 }
1432 else
1433 return -1;
1434
1435 /* If the next char is '[', the host address is IPv6. */
1436 if (*curr == '[') {
1437 curr++;
1438
1439 /* Check trash size */
1440 if (trash.size < ulen)
1441 return -1;
1442
1443 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001444 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001445 for (end = curr;
1446 end < url + ulen && *end != ']';
1447 end++, p++)
1448 *p = *end;
1449 if (*end != ']')
1450 return -1;
1451 *p = '\0';
1452
1453 /* Update out. */
1454 if (out) {
1455 out->host = curr;
1456 out->host_len = end - curr;
1457 }
1458
1459 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001460 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001461 return -1;
1462 end++;
1463
1464 /* Decode port. */
1465 if (*end == ':') {
1466 end++;
1467 default_port = read_uint(&end, url + ulen);
1468 }
1469 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1470 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1471 return end - url;
1472 }
1473 else {
1474 /* We are looking for IP address. If you want to parse and
1475 * resolve hostname found in url, you can use str2sa_range(), but
1476 * be warned this can slow down global daemon performances
1477 * while handling lagging dns responses.
1478 */
1479 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1480 if (ret) {
1481 /* Update out. */
1482 if (out) {
1483 out->host = curr;
1484 out->host_len = ret;
1485 }
1486
1487 curr += ret;
1488
1489 /* Decode port. */
1490 if (*curr == ':') {
1491 curr++;
1492 default_port = read_uint(&curr, url + ulen);
1493 }
1494 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1495
1496 /* Set family. */
1497 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1498 return curr - url;
1499 }
1500 else if (global.mode & MODE_STARTING) {
1501 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1502 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001503 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001504
1505 /* look for : or / or end */
1506 for (end = curr;
1507 end < url + ulen && *end != '/' && *end != ':';
1508 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001509 memcpy(trash.area, curr, end - curr);
1510 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001511
1512 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001513 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001514 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001515 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001516
1517 /* Update out. */
1518 if (out) {
1519 out->host = curr;
1520 out->host_len = end - curr;
1521 }
1522
1523 /* Decode port. */
1524 if (*end == ':') {
1525 end++;
1526 default_port = read_uint(&end, url + ulen);
1527 }
1528
1529 /* Copy IP address, set port and family. */
1530 switch (he->h_addrtype) {
1531 case AF_INET:
1532 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1533 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1534 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1535 return end - url;
1536
1537 case AF_INET6:
1538 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1539 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1540 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1541 return end - url;
1542 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001543 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001544 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001545 return -1;
1546}
1547
Willy Tarreau631f01c2011-09-05 00:36:48 +02001548/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1549 * address family is returned so that it's easy for the caller to adapt to the
1550 * output format. Zero is returned if the address family is not supported. -1
1551 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1552 * supported.
1553 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001554int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001555{
1556
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001557 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001558
1559 if (size < 5)
1560 return 0;
1561 *str = '\0';
1562
1563 switch (addr->ss_family) {
1564 case AF_INET:
1565 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1566 break;
1567 case AF_INET6:
1568 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1569 break;
1570 case AF_UNIX:
1571 memcpy(str, "unix", 5);
1572 return addr->ss_family;
1573 default:
1574 return 0;
1575 }
1576
1577 if (inet_ntop(addr->ss_family, ptr, str, size))
1578 return addr->ss_family;
1579
1580 /* failed */
1581 return -1;
1582}
1583
Simon Horman75ab8bd2014-06-16 09:39:41 +09001584/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1585 * address family is returned so that it's easy for the caller to adapt to the
1586 * output format. Zero is returned if the address family is not supported. -1
1587 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1588 * supported.
1589 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001590int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001591{
1592
1593 uint16_t port;
1594
1595
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001596 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001597 return 0;
1598 *str = '\0';
1599
1600 switch (addr->ss_family) {
1601 case AF_INET:
1602 port = ((struct sockaddr_in *)addr)->sin_port;
1603 break;
1604 case AF_INET6:
1605 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1606 break;
1607 case AF_UNIX:
1608 memcpy(str, "unix", 5);
1609 return addr->ss_family;
1610 default:
1611 return 0;
1612 }
1613
1614 snprintf(str, size, "%u", ntohs(port));
1615 return addr->ss_family;
1616}
1617
Willy Tarreau16e01562016-08-09 16:46:18 +02001618/* check if the given address is local to the system or not. It will return
1619 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1620 * it is. We don't want to iterate over all interfaces for this (and it is not
1621 * portable). So instead we try to bind in UDP to this address on a free non
1622 * privileged port and to connect to the same address, port 0 (connect doesn't
1623 * care). If it succeeds, we own the address. Note that non-inet addresses are
1624 * considered local since they're most likely AF_UNIX.
1625 */
1626int addr_is_local(const struct netns_entry *ns,
1627 const struct sockaddr_storage *orig)
1628{
1629 struct sockaddr_storage addr;
1630 int result;
1631 int fd;
1632
1633 if (!is_inet_addr(orig))
1634 return 1;
1635
1636 memcpy(&addr, orig, sizeof(addr));
1637 set_host_port(&addr, 0);
1638
1639 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1640 if (fd < 0)
1641 return -1;
1642
1643 result = -1;
1644 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1645 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1646 result = 0; // fail, non-local address
1647 else
1648 result = 1; // success, local address
1649 }
1650 else {
1651 if (errno == EADDRNOTAVAIL)
1652 result = 0; // definitely not local :-)
1653 }
1654 close(fd);
1655
1656 return result;
1657}
1658
Willy Tarreaubaaee002006-06-26 02:48:02 +02001659/* will try to encode the string <string> replacing all characters tagged in
1660 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1661 * prefixed by <escape>, and will store the result between <start> (included)
1662 * and <stop> (excluded), and will always terminate the string with a '\0'
1663 * before <stop>. The position of the '\0' is returned if the conversion
1664 * completes. If bytes are missing between <start> and <stop>, then the
1665 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1666 * cannot even be stored so we return <start> without writing the 0.
1667 * The input string must also be zero-terminated.
1668 */
1669const char hextab[16] = "0123456789ABCDEF";
1670char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001671 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001672 const char *string)
1673{
1674 if (start < stop) {
1675 stop--; /* reserve one byte for the final '\0' */
1676 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001677 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001678 *start++ = *string;
1679 else {
1680 if (start + 3 >= stop)
1681 break;
1682 *start++ = escape;
1683 *start++ = hextab[(*string >> 4) & 15];
1684 *start++ = hextab[*string & 15];
1685 }
1686 string++;
1687 }
1688 *start = '\0';
1689 }
1690 return start;
1691}
1692
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001693/*
1694 * Same behavior as encode_string() above, except that it encodes chunk
1695 * <chunk> instead of a string.
1696 */
1697char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001698 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001699 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001700{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001701 char *str = chunk->area;
1702 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001703
1704 if (start < stop) {
1705 stop--; /* reserve one byte for the final '\0' */
1706 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001707 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001708 *start++ = *str;
1709 else {
1710 if (start + 3 >= stop)
1711 break;
1712 *start++ = escape;
1713 *start++ = hextab[(*str >> 4) & 15];
1714 *start++ = hextab[*str & 15];
1715 }
1716 str++;
1717 }
1718 *start = '\0';
1719 }
1720 return start;
1721}
1722
Dragan Dosen0edd1092016-02-12 13:23:02 +01001723/*
1724 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001725 * character. The input <string> must be zero-terminated. The result will
1726 * be stored between <start> (included) and <stop> (excluded). This
1727 * function will always try to terminate the resulting string with a '\0'
1728 * before <stop>, and will return its position if the conversion
1729 * completes.
1730 */
1731char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001732 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001733 const char *string)
1734{
1735 if (start < stop) {
1736 stop--; /* reserve one byte for the final '\0' */
1737 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001738 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001739 *start++ = *string;
1740 else {
1741 if (start + 2 >= stop)
1742 break;
1743 *start++ = escape;
1744 *start++ = *string;
1745 }
1746 string++;
1747 }
1748 *start = '\0';
1749 }
1750 return start;
1751}
1752
1753/*
1754 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001755 * character. <chunk> contains the input to be escaped. The result will be
1756 * stored between <start> (included) and <stop> (excluded). The function
1757 * will always try to terminate the resulting string with a '\0' before
1758 * <stop>, and will return its position if the conversion completes.
1759 */
1760char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001761 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001762 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001763{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001764 char *str = chunk->area;
1765 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001766
1767 if (start < stop) {
1768 stop--; /* reserve one byte for the final '\0' */
1769 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001770 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001771 *start++ = *str;
1772 else {
1773 if (start + 2 >= stop)
1774 break;
1775 *start++ = escape;
1776 *start++ = *str;
1777 }
1778 str++;
1779 }
1780 *start = '\0';
1781 }
1782 return start;
1783}
1784
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001785/* Check a string for using it in a CSV output format. If the string contains
1786 * one of the following four char <">, <,>, CR or LF, the string is
1787 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1788 * <str> is the input string to be escaped. The function assumes that
1789 * the input string is null-terminated.
1790 *
1791 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001792 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001793 * format.
1794 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001795 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001796 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001797 * If <quote> is 1, the converter puts the quotes only if any reserved character
1798 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001799 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001800 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001801 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001802 * The function returns the converted string on its output. If an error
1803 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001804 * for using the function directly as printf() argument.
1805 *
1806 * If the output buffer is too short to contain the input string, the result
1807 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001808 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001809 * This function appends the encoding to the existing output chunk, and it
1810 * guarantees that it starts immediately at the first available character of
1811 * the chunk. Please use csv_enc() instead if you want to replace the output
1812 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001813 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001814const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001815{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001816 char *end = output->area + output->size;
1817 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001818 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001819
Willy Tarreaub631c292016-01-08 10:04:08 +01001820 if (quote == 1) {
1821 /* automatic quoting: first verify if we'll have to quote the string */
1822 if (!strpbrk(str, "\n\r,\""))
1823 quote = 0;
1824 }
1825
1826 if (quote)
1827 *ptr++ = '"';
1828
Willy Tarreau898529b2016-01-06 18:07:04 +01001829 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1830 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001831 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001832 ptr++;
1833 if (ptr >= end - 2) {
1834 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001835 break;
1836 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001837 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001838 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001839 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001840 str++;
1841 }
1842
Willy Tarreaub631c292016-01-08 10:04:08 +01001843 if (quote)
1844 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001845
Willy Tarreau898529b2016-01-06 18:07:04 +01001846 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001847 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001848 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001849}
1850
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001851/* Decode an URL-encoded string in-place. The resulting string might
1852 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001853 * aborted, the string is truncated before the issue and a negative value is
1854 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001855 * If the 'in_form' argument is non-nul the string is assumed to be part of
1856 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1857 * turned to a space. If it's zero, this will only be done after a question
1858 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001859 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001860int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001861{
1862 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001863 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001864
1865 in = string;
1866 out = string;
1867 while (*in) {
1868 switch (*in) {
1869 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001870 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001871 break;
1872 case '%' :
1873 if (!ishex(in[1]) || !ishex(in[2]))
1874 goto end;
1875 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1876 in += 2;
1877 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001878 case '?':
1879 in_form = 1;
1880 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001881 default:
1882 *out++ = *in;
1883 break;
1884 }
1885 in++;
1886 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001887 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001888 end:
1889 *out = 0;
1890 return ret;
1891}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001892
Willy Tarreau6911fa42007-03-04 18:06:08 +01001893unsigned int str2ui(const char *s)
1894{
1895 return __str2ui(s);
1896}
1897
1898unsigned int str2uic(const char *s)
1899{
1900 return __str2uic(s);
1901}
1902
1903unsigned int strl2ui(const char *s, int len)
1904{
1905 return __strl2ui(s, len);
1906}
1907
1908unsigned int strl2uic(const char *s, int len)
1909{
1910 return __strl2uic(s, len);
1911}
1912
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001913unsigned int read_uint(const char **s, const char *end)
1914{
1915 return __read_uint(s, end);
1916}
1917
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001918/* This function reads an unsigned integer from the string pointed to by <s> and
1919 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1920 * function automatically stops at <end>. If the number overflows, the 2^64-1
1921 * value is returned.
1922 */
1923unsigned long long int read_uint64(const char **s, const char *end)
1924{
1925 const char *ptr = *s;
1926 unsigned long long int i = 0, tmp;
1927 unsigned int j;
1928
1929 while (ptr < end) {
1930
1931 /* read next char */
1932 j = *ptr - '0';
1933 if (j > 9)
1934 goto read_uint64_end;
1935
1936 /* add char to the number and check overflow. */
1937 tmp = i * 10;
1938 if (tmp / 10 != i) {
1939 i = ULLONG_MAX;
1940 goto read_uint64_eat;
1941 }
1942 if (ULLONG_MAX - tmp < j) {
1943 i = ULLONG_MAX;
1944 goto read_uint64_eat;
1945 }
1946 i = tmp + j;
1947 ptr++;
1948 }
1949read_uint64_eat:
1950 /* eat each numeric char */
1951 while (ptr < end) {
1952 if ((unsigned int)(*ptr - '0') > 9)
1953 break;
1954 ptr++;
1955 }
1956read_uint64_end:
1957 *s = ptr;
1958 return i;
1959}
1960
1961/* This function reads an integer from the string pointed to by <s> and returns
1962 * it. The <s> pointer is adjusted to point to the first unread char. The function
1963 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1964 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1965 * returned.
1966 */
1967long long int read_int64(const char **s, const char *end)
1968{
1969 unsigned long long int i = 0;
1970 int neg = 0;
1971
1972 /* Look for minus char. */
1973 if (**s == '-') {
1974 neg = 1;
1975 (*s)++;
1976 }
1977 else if (**s == '+')
1978 (*s)++;
1979
1980 /* convert as positive number. */
1981 i = read_uint64(s, end);
1982
1983 if (neg) {
1984 if (i > 0x8000000000000000ULL)
1985 return LLONG_MIN;
1986 return -i;
1987 }
1988 if (i > 0x7fffffffffffffffULL)
1989 return LLONG_MAX;
1990 return i;
1991}
1992
Willy Tarreau6911fa42007-03-04 18:06:08 +01001993/* This one is 7 times faster than strtol() on athlon with checks.
1994 * It returns the value of the number composed of all valid digits read,
1995 * and can process negative numbers too.
1996 */
1997int strl2ic(const char *s, int len)
1998{
1999 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002000 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002001
2002 if (len > 0) {
2003 if (*s != '-') {
2004 /* positive number */
2005 while (len-- > 0) {
2006 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002007 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002008 if (j > 9)
2009 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002010 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002011 }
2012 } else {
2013 /* negative number */
2014 s++;
2015 while (--len > 0) {
2016 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002017 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002018 if (j > 9)
2019 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002020 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002021 }
2022 }
2023 }
2024 return i;
2025}
2026
2027
2028/* This function reads exactly <len> chars from <s> and converts them to a
2029 * signed integer which it stores into <ret>. It accurately detects any error
2030 * (truncated string, invalid chars, overflows). It is meant to be used in
2031 * applications designed for hostile environments. It returns zero when the
2032 * number has successfully been converted, non-zero otherwise. When an error
2033 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2034 * faster than strtol().
2035 */
2036int strl2irc(const char *s, int len, int *ret)
2037{
2038 int i = 0;
2039 int j;
2040
2041 if (!len)
2042 return 1;
2043
2044 if (*s != '-') {
2045 /* positive number */
2046 while (len-- > 0) {
2047 j = (*s++) - '0';
2048 if (j > 9) return 1; /* invalid char */
2049 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2050 i = i * 10;
2051 if (i + j < i) return 1; /* check for addition overflow */
2052 i = i + j;
2053 }
2054 } else {
2055 /* negative number */
2056 s++;
2057 while (--len > 0) {
2058 j = (*s++) - '0';
2059 if (j > 9) return 1; /* invalid char */
2060 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2061 i = i * 10;
2062 if (i - j > i) return 1; /* check for subtract overflow */
2063 i = i - j;
2064 }
2065 }
2066 *ret = i;
2067 return 0;
2068}
2069
2070
2071/* This function reads exactly <len> chars from <s> and converts them to a
2072 * signed integer which it stores into <ret>. It accurately detects any error
2073 * (truncated string, invalid chars, overflows). It is meant to be used in
2074 * applications designed for hostile environments. It returns zero when the
2075 * number has successfully been converted, non-zero otherwise. When an error
2076 * is returned, the <ret> value is left untouched. It is about 3 times slower
2077 * than str2irc().
2078 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002079
2080int strl2llrc(const char *s, int len, long long *ret)
2081{
2082 long long i = 0;
2083 int j;
2084
2085 if (!len)
2086 return 1;
2087
2088 if (*s != '-') {
2089 /* positive number */
2090 while (len-- > 0) {
2091 j = (*s++) - '0';
2092 if (j > 9) return 1; /* invalid char */
2093 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2094 i = i * 10LL;
2095 if (i + j < i) return 1; /* check for addition overflow */
2096 i = i + j;
2097 }
2098 } else {
2099 /* negative number */
2100 s++;
2101 while (--len > 0) {
2102 j = (*s++) - '0';
2103 if (j > 9) return 1; /* invalid char */
2104 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2105 i = i * 10LL;
2106 if (i - j > i) return 1; /* check for subtract overflow */
2107 i = i - j;
2108 }
2109 }
2110 *ret = i;
2111 return 0;
2112}
2113
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002114/* This function is used with pat_parse_dotted_ver(). It converts a string
2115 * composed by two number separated by a dot. Each part must contain in 16 bits
2116 * because internally they will be represented as a 32-bit quantity stored in
2117 * a 64-bit integer. It returns zero when the number has successfully been
2118 * converted, non-zero otherwise. When an error is returned, the <ret> value
2119 * is left untouched.
2120 *
2121 * "1.3" -> 0x0000000000010003
2122 * "65535.65535" -> 0x00000000ffffffff
2123 */
2124int strl2llrc_dotted(const char *text, int len, long long *ret)
2125{
2126 const char *end = &text[len];
2127 const char *p;
2128 long long major, minor;
2129
2130 /* Look for dot. */
2131 for (p = text; p < end; p++)
2132 if (*p == '.')
2133 break;
2134
2135 /* Convert major. */
2136 if (strl2llrc(text, p - text, &major) != 0)
2137 return 1;
2138
2139 /* Check major. */
2140 if (major >= 65536)
2141 return 1;
2142
2143 /* Convert minor. */
2144 minor = 0;
2145 if (p < end)
2146 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2147 return 1;
2148
2149 /* Check minor. */
2150 if (minor >= 65536)
2151 return 1;
2152
2153 /* Compose value. */
2154 *ret = (major << 16) | (minor & 0xffff);
2155 return 0;
2156}
2157
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002158/* This function parses a time value optionally followed by a unit suffix among
2159 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2160 * expected by the caller. The computation does its best to avoid overflows.
2161 * The value is returned in <ret> if everything is fine, and a NULL is returned
2162 * by the function. In case of error, a pointer to the error is returned and
2163 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002164 * Values resulting in values larger than or equal to 2^31 after conversion are
2165 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2166 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002167 */
2168const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2169{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002170 unsigned long long imult, idiv;
2171 unsigned long long omult, odiv;
2172 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002173
2174 omult = odiv = 1;
2175
2176 switch (unit_flags & TIME_UNIT_MASK) {
2177 case TIME_UNIT_US: omult = 1000000; break;
2178 case TIME_UNIT_MS: omult = 1000; break;
2179 case TIME_UNIT_S: break;
2180 case TIME_UNIT_MIN: odiv = 60; break;
2181 case TIME_UNIT_HOUR: odiv = 3600; break;
2182 case TIME_UNIT_DAY: odiv = 86400; break;
2183 default: break;
2184 }
2185
2186 value = 0;
2187
2188 while (1) {
2189 unsigned int j;
2190
2191 j = *text - '0';
2192 if (j > 9)
2193 break;
2194 text++;
2195 value *= 10;
2196 value += j;
2197 }
2198
2199 imult = idiv = 1;
2200 switch (*text) {
2201 case '\0': /* no unit = default unit */
2202 imult = omult = idiv = odiv = 1;
2203 break;
2204 case 's': /* second = unscaled unit */
2205 break;
2206 case 'u': /* microsecond : "us" */
2207 if (text[1] == 's') {
2208 idiv = 1000000;
2209 text++;
2210 }
2211 break;
2212 case 'm': /* millisecond : "ms" or minute: "m" */
2213 if (text[1] == 's') {
2214 idiv = 1000;
2215 text++;
2216 } else
2217 imult = 60;
2218 break;
2219 case 'h': /* hour : "h" */
2220 imult = 3600;
2221 break;
2222 case 'd': /* day : "d" */
2223 imult = 86400;
2224 break;
2225 default:
2226 return text;
2227 break;
2228 }
2229
2230 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2231 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2232 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2233 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2234
Willy Tarreau9faebe32019-06-07 19:00:37 +02002235 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2236 if (result >= 0x80000000)
2237 return PARSE_TIME_OVER;
2238 if (!result && value)
2239 return PARSE_TIME_UNDER;
2240 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002241 return NULL;
2242}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002243
Emeric Brun39132b22010-01-04 14:57:24 +01002244/* this function converts the string starting at <text> to an unsigned int
2245 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002246 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002247 */
2248const char *parse_size_err(const char *text, unsigned *ret) {
2249 unsigned value = 0;
2250
2251 while (1) {
2252 unsigned int j;
2253
2254 j = *text - '0';
2255 if (j > 9)
2256 break;
2257 if (value > ~0U / 10)
2258 return text;
2259 value *= 10;
2260 if (value > (value + j))
2261 return text;
2262 value += j;
2263 text++;
2264 }
2265
2266 switch (*text) {
2267 case '\0':
2268 break;
2269 case 'K':
2270 case 'k':
2271 if (value > ~0U >> 10)
2272 return text;
2273 value = value << 10;
2274 break;
2275 case 'M':
2276 case 'm':
2277 if (value > ~0U >> 20)
2278 return text;
2279 value = value << 20;
2280 break;
2281 case 'G':
2282 case 'g':
2283 if (value > ~0U >> 30)
2284 return text;
2285 value = value << 30;
2286 break;
2287 default:
2288 return text;
2289 }
2290
Godbach58048a22015-01-28 17:36:16 +08002291 if (*text != '\0' && *++text != '\0')
2292 return text;
2293
Emeric Brun39132b22010-01-04 14:57:24 +01002294 *ret = value;
2295 return NULL;
2296}
2297
Willy Tarreau126d4062013-12-03 17:50:47 +01002298/*
2299 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002300 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002301 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002302 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002303 */
2304int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2305{
2306 int len;
2307 const char *p = source;
2308 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002309 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002310
2311 len = strlen(source);
2312 if (len % 2) {
2313 memprintf(err, "an even number of hex digit is expected");
2314 return 0;
2315 }
2316
2317 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002318
Willy Tarreau126d4062013-12-03 17:50:47 +01002319 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002320 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002321 if (!*binstr) {
2322 memprintf(err, "out of memory while loading string pattern");
2323 return 0;
2324 }
2325 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002326 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002327 else {
2328 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002329 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002330 len, *binstrlen);
2331 return 0;
2332 }
2333 alloc = 0;
2334 }
2335 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002336
2337 i = j = 0;
2338 while (j < len) {
2339 if (!ishex(p[i++]))
2340 goto bad_input;
2341 if (!ishex(p[i++]))
2342 goto bad_input;
2343 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2344 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002345 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002346
2347bad_input:
2348 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002349 if (alloc) {
2350 free(*binstr);
2351 *binstr = NULL;
2352 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002353 return 0;
2354}
2355
Willy Tarreau946ba592009-05-10 15:41:18 +02002356/* copies at most <n> characters from <src> and always terminates with '\0' */
2357char *my_strndup(const char *src, int n)
2358{
2359 int len = 0;
2360 char *ret;
2361
2362 while (len < n && src[len])
2363 len++;
2364
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002365 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002366 if (!ret)
2367 return ret;
2368 memcpy(ret, src, len);
2369 ret[len] = '\0';
2370 return ret;
2371}
2372
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002373/*
2374 * search needle in haystack
2375 * returns the pointer if found, returns NULL otherwise
2376 */
2377const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2378{
2379 const void *c = NULL;
2380 unsigned char f;
2381
2382 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2383 return NULL;
2384
2385 f = *(char *)needle;
2386 c = haystack;
2387 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2388 if ((haystacklen - (c - haystack)) < needlelen)
2389 return NULL;
2390
2391 if (memcmp(c, needle, needlelen) == 0)
2392 return c;
2393 ++c;
2394 }
2395 return NULL;
2396}
2397
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002398/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002399size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2400{
2401 size_t ret = 0;
2402
2403 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2404 str++;
2405 ret++;
2406 }
2407 return ret;
2408}
2409
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002410/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002411size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2412{
2413 size_t ret = 0;
2414
2415 while (ret < len) {
2416 if(memchr(reject, *((int *)str), rejectlen))
2417 return ret;
2418 str++;
2419 ret++;
2420 }
2421 return ret;
2422}
2423
Willy Tarreau482b00d2009-10-04 22:48:42 +02002424/* This function returns the first unused key greater than or equal to <key> in
2425 * ID tree <root>. Zero is returned if no place is found.
2426 */
2427unsigned int get_next_id(struct eb_root *root, unsigned int key)
2428{
2429 struct eb32_node *used;
2430
2431 do {
2432 used = eb32_lookup_ge(root, key);
2433 if (!used || used->key > key)
2434 return key; /* key is available */
2435 key++;
2436 } while (key);
2437 return key;
2438}
2439
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002440/* dump the full tree to <file> in DOT format for debugging purposes. Will
2441 * optionally highlight node <subj> if found, depending on operation <op> :
2442 * 0 : nothing
2443 * >0 : insertion, node/leaf are surrounded in red
2444 * <0 : removal, node/leaf are dashed with no background
2445 * Will optionally add "desc" as a label on the graph if set and non-null.
2446 */
2447void 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 +01002448{
2449 struct eb32sc_node *node;
2450 unsigned long scope = -1;
2451
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002452 fprintf(file, "digraph ebtree {\n");
2453
2454 if (desc && *desc) {
2455 fprintf(file,
2456 " fontname=\"fixed\";\n"
2457 " fontsize=8;\n"
2458 " label=\"%s\";\n", desc);
2459 }
2460
Willy Tarreaued3cda02017-11-15 15:04:05 +01002461 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002462 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2463 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002464 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2465 );
2466
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002467 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002468 (long)eb_root_to_node(root),
2469 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002470 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2471
2472 node = eb32sc_first(root, scope);
2473 while (node) {
2474 if (node->node.node_p) {
2475 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002476 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2477 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2478 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002479
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002480 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002481 (long)node,
2482 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002483 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002484
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002485 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002486 (long)node,
2487 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002488 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2489
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002490 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002491 (long)node,
2492 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002493 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2494 }
2495
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002496 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2497 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2498 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002499
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002500 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002501 (long)node,
2502 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002503 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002504 node = eb32sc_next(node, scope);
2505 }
2506 fprintf(file, "}\n");
2507}
2508
Willy Tarreau348238b2010-01-18 15:05:57 +01002509/* This function compares a sample word possibly followed by blanks to another
2510 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2511 * otherwise zero. This intends to be used when checking HTTP headers for some
2512 * values. Note that it validates a word followed only by blanks but does not
2513 * validate a word followed by blanks then other chars.
2514 */
2515int word_match(const char *sample, int slen, const char *word, int wlen)
2516{
2517 if (slen < wlen)
2518 return 0;
2519
2520 while (wlen) {
2521 char c = *sample ^ *word;
2522 if (c && c != ('A' ^ 'a'))
2523 return 0;
2524 sample++;
2525 word++;
2526 slen--;
2527 wlen--;
2528 }
2529
2530 while (slen) {
2531 if (*sample != ' ' && *sample != '\t')
2532 return 0;
2533 sample++;
2534 slen--;
2535 }
2536 return 1;
2537}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002538
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002539/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2540 * is particularly fast because it avoids expensive operations such as
2541 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002542 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002543 */
2544unsigned int inetaddr_host(const char *text)
2545{
2546 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2547 register unsigned int dig100, dig10, dig1;
2548 int s;
2549 const char *p, *d;
2550
2551 dig1 = dig10 = dig100 = ascii_zero;
2552 s = 24;
2553
2554 p = text;
2555 while (1) {
2556 if (((unsigned)(*p - '0')) <= 9) {
2557 p++;
2558 continue;
2559 }
2560
2561 /* here, we have a complete byte between <text> and <p> (exclusive) */
2562 if (p == text)
2563 goto end;
2564
2565 d = p - 1;
2566 dig1 |= (unsigned int)(*d << s);
2567 if (d == text)
2568 goto end;
2569
2570 d--;
2571 dig10 |= (unsigned int)(*d << s);
2572 if (d == text)
2573 goto end;
2574
2575 d--;
2576 dig100 |= (unsigned int)(*d << s);
2577 end:
2578 if (!s || *p != '.')
2579 break;
2580
2581 s -= 8;
2582 text = ++p;
2583 }
2584
2585 dig100 -= ascii_zero;
2586 dig10 -= ascii_zero;
2587 dig1 -= ascii_zero;
2588 return ((dig100 * 10) + dig10) * 10 + dig1;
2589}
2590
2591/*
2592 * Idem except the first unparsed character has to be passed in <stop>.
2593 */
2594unsigned int inetaddr_host_lim(const char *text, const char *stop)
2595{
2596 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2597 register unsigned int dig100, dig10, dig1;
2598 int s;
2599 const char *p, *d;
2600
2601 dig1 = dig10 = dig100 = ascii_zero;
2602 s = 24;
2603
2604 p = text;
2605 while (1) {
2606 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2607 p++;
2608 continue;
2609 }
2610
2611 /* here, we have a complete byte between <text> and <p> (exclusive) */
2612 if (p == text)
2613 goto end;
2614
2615 d = p - 1;
2616 dig1 |= (unsigned int)(*d << s);
2617 if (d == text)
2618 goto end;
2619
2620 d--;
2621 dig10 |= (unsigned int)(*d << s);
2622 if (d == text)
2623 goto end;
2624
2625 d--;
2626 dig100 |= (unsigned int)(*d << s);
2627 end:
2628 if (!s || p == stop || *p != '.')
2629 break;
2630
2631 s -= 8;
2632 text = ++p;
2633 }
2634
2635 dig100 -= ascii_zero;
2636 dig10 -= ascii_zero;
2637 dig1 -= ascii_zero;
2638 return ((dig100 * 10) + dig10) * 10 + dig1;
2639}
2640
2641/*
2642 * Idem except the pointer to first unparsed byte is returned into <ret> which
2643 * must not be NULL.
2644 */
Willy Tarreau74172752010-10-15 23:21:42 +02002645unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002646{
2647 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2648 register unsigned int dig100, dig10, dig1;
2649 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002650 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002651
2652 dig1 = dig10 = dig100 = ascii_zero;
2653 s = 24;
2654
2655 p = text;
2656 while (1) {
2657 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2658 p++;
2659 continue;
2660 }
2661
2662 /* here, we have a complete byte between <text> and <p> (exclusive) */
2663 if (p == text)
2664 goto end;
2665
2666 d = p - 1;
2667 dig1 |= (unsigned int)(*d << s);
2668 if (d == text)
2669 goto end;
2670
2671 d--;
2672 dig10 |= (unsigned int)(*d << s);
2673 if (d == text)
2674 goto end;
2675
2676 d--;
2677 dig100 |= (unsigned int)(*d << s);
2678 end:
2679 if (!s || p == stop || *p != '.')
2680 break;
2681
2682 s -= 8;
2683 text = ++p;
2684 }
2685
2686 *ret = p;
2687 dig100 -= ascii_zero;
2688 dig10 -= ascii_zero;
2689 dig1 -= ascii_zero;
2690 return ((dig100 * 10) + dig10) * 10 + dig1;
2691}
2692
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002693/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2694 * or the number of chars read in case of success. Maybe this could be replaced
2695 * by one of the functions above. Also, apparently this function does not support
2696 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002697 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002698 */
2699int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2700{
2701 const char *addr;
2702 int saw_digit, octets, ch;
2703 u_char tmp[4], *tp;
2704 const char *cp = buf;
2705
2706 saw_digit = 0;
2707 octets = 0;
2708 *(tp = tmp) = 0;
2709
2710 for (addr = buf; addr - buf < len; addr++) {
2711 unsigned char digit = (ch = *addr) - '0';
2712
2713 if (digit > 9 && ch != '.')
2714 break;
2715
2716 if (digit <= 9) {
2717 u_int new = *tp * 10 + digit;
2718
2719 if (new > 255)
2720 return 0;
2721
2722 *tp = new;
2723
2724 if (!saw_digit) {
2725 if (++octets > 4)
2726 return 0;
2727 saw_digit = 1;
2728 }
2729 } else if (ch == '.' && saw_digit) {
2730 if (octets == 4)
2731 return 0;
2732
2733 *++tp = 0;
2734 saw_digit = 0;
2735 } else
2736 return 0;
2737 }
2738
2739 if (octets < 4)
2740 return 0;
2741
2742 memcpy(&dst->s_addr, tmp, 4);
2743 return addr - cp;
2744}
2745
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002746/* This function converts the string in <buf> of the len <len> to
2747 * struct in6_addr <dst> which must be allocated by the caller.
2748 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002749 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002750 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002751int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2752{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002753 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002754 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002755
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002756 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002757 return 0;
2758
2759 memcpy(null_term_ip6, buf, len);
2760 null_term_ip6[len] = '\0';
2761
Willy Tarreau075415a2013-12-12 11:29:39 +01002762 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002763 return 0;
2764
Willy Tarreau075415a2013-12-12 11:29:39 +01002765 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002766 return 1;
2767}
2768
Willy Tarreauacf95772010-06-14 19:09:21 +02002769/* To be used to quote config arg positions. Returns the short string at <ptr>
2770 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2771 * if ptr is NULL or empty. The string is locally allocated.
2772 */
2773const char *quote_arg(const char *ptr)
2774{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002775 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002776 int i;
2777
2778 if (!ptr || !*ptr)
2779 return "end of line";
2780 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002781 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002782 val[i] = *ptr++;
2783 val[i++] = '\'';
2784 val[i] = '\0';
2785 return val;
2786}
2787
Willy Tarreau5b180202010-07-18 10:40:48 +02002788/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2789int get_std_op(const char *str)
2790{
2791 int ret = -1;
2792
2793 if (*str == 'e' && str[1] == 'q')
2794 ret = STD_OP_EQ;
2795 else if (*str == 'n' && str[1] == 'e')
2796 ret = STD_OP_NE;
2797 else if (*str == 'l') {
2798 if (str[1] == 'e') ret = STD_OP_LE;
2799 else if (str[1] == 't') ret = STD_OP_LT;
2800 }
2801 else if (*str == 'g') {
2802 if (str[1] == 'e') ret = STD_OP_GE;
2803 else if (str[1] == 't') ret = STD_OP_GT;
2804 }
2805
2806 if (ret == -1 || str[2] != '\0')
2807 return -1;
2808 return ret;
2809}
2810
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002811/* hash a 32-bit integer to another 32-bit integer */
2812unsigned int full_hash(unsigned int a)
2813{
2814 return __full_hash(a);
2815}
2816
Willy Tarreauf3241112019-02-26 09:56:22 +01002817/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2818 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2819 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2820 * a popcount variant and is described here :
2821 * https://graphics.stanford.edu/~seander/bithacks.html
2822 */
2823unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2824{
2825 unsigned long a, b, c, d;
2826 unsigned int s;
2827 unsigned int t;
2828
2829 a = m - ((m >> 1) & ~0UL/3);
2830 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2831 c = (b + (b >> 4)) & ~0UL/0x11;
2832 d = (c + (c >> 8)) & ~0UL/0x101;
2833
2834 r++; // make r be 1..64
2835
2836 t = 0;
2837 s = LONGBITS;
2838 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002839 unsigned long d2 = (d >> 16) >> 16;
2840 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002841 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2842 }
2843
2844 t = (d >> (s - 16)) & 0xff;
2845 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2846 t = (c >> (s - 8)) & 0xf;
2847 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2848 t = (b >> (s - 4)) & 0x7;
2849 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2850 t = (a >> (s - 2)) & 0x3;
2851 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2852 t = (m >> (s - 1)) & 0x1;
2853 s -= ((t - r) & 256) >> 8;
2854
2855 return s - 1;
2856}
2857
2858/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2859 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2860 * using mask_prep_rank_map() below.
2861 */
2862unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2863 unsigned long a, unsigned long b,
2864 unsigned long c, unsigned long d)
2865{
2866 unsigned int s;
2867 unsigned int t;
2868
2869 r++; // make r be 1..64
2870
2871 t = 0;
2872 s = LONGBITS;
2873 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002874 unsigned long d2 = (d >> 16) >> 16;
2875 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002876 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2877 }
2878
2879 t = (d >> (s - 16)) & 0xff;
2880 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2881 t = (c >> (s - 8)) & 0xf;
2882 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2883 t = (b >> (s - 4)) & 0x7;
2884 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2885 t = (a >> (s - 2)) & 0x3;
2886 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2887 t = (m >> (s - 1)) & 0x1;
2888 s -= ((t - r) & 256) >> 8;
2889
2890 return s - 1;
2891}
2892
2893/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2894 * above.
2895 */
2896void mask_prep_rank_map(unsigned long m,
2897 unsigned long *a, unsigned long *b,
2898 unsigned long *c, unsigned long *d)
2899{
2900 *a = m - ((m >> 1) & ~0UL/3);
2901 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2902 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2903 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2904}
2905
David du Colombier4f92d322011-03-24 11:09:31 +01002906/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002907 * otherwise zero. Note that <addr> may not necessarily be aligned
2908 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002909 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002910int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002911{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002912 struct in_addr addr_copy;
2913
2914 memcpy(&addr_copy, addr, sizeof(addr_copy));
2915 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002916}
2917
2918/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002919 * otherwise zero. Note that <addr> may not necessarily be aligned
2920 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002921 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002922int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002923{
2924 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002925 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002926
Willy Tarreaueec1d382016-07-13 11:59:39 +02002927 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002928 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002929 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002930 (((int *)net)[i] & ((int *)mask)[i]))
2931 return 0;
2932 return 1;
2933}
2934
2935/* RFC 4291 prefix */
2936const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2937 0x00, 0x00, 0x00, 0x00,
2938 0x00, 0x00, 0xFF, 0xFF };
2939
Joseph Herlant32b83272018-11-15 11:58:28 -08002940/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002941 * Input and output may overlap.
2942 */
David du Colombier4f92d322011-03-24 11:09:31 +01002943void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2944{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002945 struct in_addr tmp_addr;
2946
2947 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002948 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002949 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002950}
2951
Joseph Herlant32b83272018-11-15 11:58:28 -08002952/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002953 * Return true if conversion is possible and false otherwise.
2954 */
2955int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2956{
2957 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2958 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2959 sizeof(struct in_addr));
2960 return 1;
2961 }
2962
2963 return 0;
2964}
2965
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002966/* compare two struct sockaddr_storage and return:
2967 * 0 (true) if the addr is the same in both
2968 * 1 (false) if the addr is not the same in both
2969 * -1 (unable) if one of the addr is not AF_INET*
2970 */
2971int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2972{
2973 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2974 return -1;
2975
2976 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2977 return -1;
2978
2979 if (ss1->ss_family != ss2->ss_family)
2980 return 1;
2981
2982 switch (ss1->ss_family) {
2983 case AF_INET:
2984 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2985 &((struct sockaddr_in *)ss2)->sin_addr,
2986 sizeof(struct in_addr)) != 0;
2987 case AF_INET6:
2988 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2989 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2990 sizeof(struct in6_addr)) != 0;
2991 }
2992
2993 return 1;
2994}
2995
Baptiste Assmann08396c82016-01-31 00:27:17 +01002996/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002997 * The caller must allocate and clear <dest> before calling.
2998 * The source must be in either AF_INET or AF_INET6 family, or the destination
2999 * address will be undefined. If the destination address used to hold a port,
3000 * it is preserved, so that this function can be used to switch to another
3001 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003002 */
3003struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3004{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003005 int prev_port;
3006
3007 prev_port = get_net_port(dest);
3008 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003009 dest->ss_family = source->ss_family;
3010
3011 /* copy new addr and apply it */
3012 switch (source->ss_family) {
3013 case AF_INET:
3014 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003015 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003016 break;
3017 case AF_INET6:
3018 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 +01003019 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003020 break;
3021 }
3022
3023 return dest;
3024}
3025
William Lallemand421f5b52012-02-06 18:15:57 +01003026char *human_time(int t, short hz_div) {
3027 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3028 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003029 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003030 int cnt=2; // print two numbers
3031
3032 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003033 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003034 return rv;
3035 }
3036
3037 if (unlikely(hz_div > 1))
3038 t /= hz_div;
3039
3040 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003041 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003042 cnt--;
3043 }
3044
3045 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003046 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003047 cnt--;
3048 }
3049
3050 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003051 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003052 cnt--;
3053 }
3054
3055 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003056 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003057
3058 return rv;
3059}
3060
3061const char *monthname[12] = {
3062 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3063 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3064};
3065
3066/* date2str_log: write a date in the format :
3067 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3068 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3069 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3070 *
3071 * without using sprintf. return a pointer to the last char written (\0) or
3072 * NULL if there isn't enough space.
3073 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003074char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003075{
3076
3077 if (size < 25) /* the size is fixed: 24 chars + \0 */
3078 return NULL;
3079
3080 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003081 if (!dst)
3082 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003083 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003084
William Lallemand421f5b52012-02-06 18:15:57 +01003085 memcpy(dst, monthname[tm->tm_mon], 3); // month
3086 dst += 3;
3087 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003088
William Lallemand421f5b52012-02-06 18:15:57 +01003089 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003090 if (!dst)
3091 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003092 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003093
William Lallemand421f5b52012-02-06 18:15:57 +01003094 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003095 if (!dst)
3096 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003097 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003098
William Lallemand421f5b52012-02-06 18:15:57 +01003099 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003100 if (!dst)
3101 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003102 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003103
William Lallemand421f5b52012-02-06 18:15:57 +01003104 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003105 if (!dst)
3106 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003107 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003108
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003109 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003110 if (!dst)
3111 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003112 *dst = '\0';
3113
3114 return dst;
3115}
3116
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003117/* Base year used to compute leap years */
3118#define TM_YEAR_BASE 1900
3119
3120/* Return the difference in seconds between two times (leap seconds are ignored).
3121 * Retrieved from glibc 2.18 source code.
3122 */
3123static int my_tm_diff(const struct tm *a, const struct tm *b)
3124{
3125 /* Compute intervening leap days correctly even if year is negative.
3126 * Take care to avoid int overflow in leap day calculations,
3127 * but it's OK to assume that A and B are close to each other.
3128 */
3129 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3130 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3131 int a100 = a4 / 25 - (a4 % 25 < 0);
3132 int b100 = b4 / 25 - (b4 % 25 < 0);
3133 int a400 = a100 >> 2;
3134 int b400 = b100 >> 2;
3135 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3136 int years = a->tm_year - b->tm_year;
3137 int days = (365 * years + intervening_leap_days
3138 + (a->tm_yday - b->tm_yday));
3139 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3140 + (a->tm_min - b->tm_min))
3141 + (a->tm_sec - b->tm_sec));
3142}
3143
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003144/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003145 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003146 * The string returned has the same format as returned by strftime(... "%z", tm).
3147 * Offsets are kept in an internal cache for better performances.
3148 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003149const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003150{
3151 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003152 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003153
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003154 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003155 struct tm tm_gmt;
3156 int diff;
3157 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003158
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003159 /* Pretend DST not active if its status is unknown */
3160 if (isdst < 0)
3161 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003162
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003163 /* Fetch the offset and initialize it if needed */
3164 gmt_offset = gmt_offsets[isdst & 0x01];
3165 if (unlikely(!*gmt_offset)) {
3166 get_gmtime(t, &tm_gmt);
3167 diff = my_tm_diff(tm, &tm_gmt);
3168 if (diff < 0) {
3169 diff = -diff;
3170 *gmt_offset = '-';
3171 } else {
3172 *gmt_offset = '+';
3173 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003174 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003175 diff /= 60; /* Convert to minutes */
3176 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3177 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003178
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003179 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003180}
3181
William Lallemand421f5b52012-02-06 18:15:57 +01003182/* gmt2str_log: write a date in the format :
3183 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3184 * return a pointer to the last char written (\0) or
3185 * NULL if there isn't enough space.
3186 */
3187char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3188{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003189 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003190 return NULL;
3191
3192 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003193 if (!dst)
3194 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003195 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003196
William Lallemand421f5b52012-02-06 18:15:57 +01003197 memcpy(dst, monthname[tm->tm_mon], 3); // month
3198 dst += 3;
3199 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003200
William Lallemand421f5b52012-02-06 18:15:57 +01003201 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003202 if (!dst)
3203 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003204 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003205
William Lallemand421f5b52012-02-06 18:15:57 +01003206 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003207 if (!dst)
3208 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003209 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003210
William Lallemand421f5b52012-02-06 18:15:57 +01003211 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003212 if (!dst)
3213 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003214 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003215
William Lallemand421f5b52012-02-06 18:15:57 +01003216 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003217 if (!dst)
3218 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003219 *dst++ = ' ';
3220 *dst++ = '+';
3221 *dst++ = '0';
3222 *dst++ = '0';
3223 *dst++ = '0';
3224 *dst++ = '0';
3225 *dst = '\0';
3226
3227 return dst;
3228}
3229
Yuxans Yao4e25b012012-10-19 10:36:09 +08003230/* localdate2str_log: write a date in the format :
3231 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003232 * Both t and tm must represent the same time.
3233 * return a pointer to the last char written (\0) or
3234 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003235 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003236char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003237{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003238 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003239 if (size < 27) /* the size is fixed: 26 chars + \0 */
3240 return NULL;
3241
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003242 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003243
Yuxans Yao4e25b012012-10-19 10:36:09 +08003244 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003245 if (!dst)
3246 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003247 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003248
Yuxans Yao4e25b012012-10-19 10:36:09 +08003249 memcpy(dst, monthname[tm->tm_mon], 3); // month
3250 dst += 3;
3251 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003252
Yuxans Yao4e25b012012-10-19 10:36:09 +08003253 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003254 if (!dst)
3255 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003256 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003257
Yuxans Yao4e25b012012-10-19 10:36:09 +08003258 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003259 if (!dst)
3260 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003261 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003262
Yuxans Yao4e25b012012-10-19 10:36:09 +08003263 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003264 if (!dst)
3265 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003266 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003267
Yuxans Yao4e25b012012-10-19 10:36:09 +08003268 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003269 if (!dst)
3270 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003271 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003272
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003273 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003274 dst += 5;
3275 *dst = '\0';
3276
3277 return dst;
3278}
3279
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003280/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3281 * It is meant as a portable replacement for timegm() for use with valid inputs.
3282 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3283 */
3284time_t my_timegm(const struct tm *tm)
3285{
3286 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3287 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3288 * sum of the extra N days for elapsed months. The sum of all these N
3289 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3290 * in a 5-bit word. This means that with 60 bits we can represent a
3291 * matrix of all these values at once, which is fast and efficient to
3292 * access. The extra February day for leap years is not counted here.
3293 *
3294 * Jan : none = 0 (0)
3295 * Feb : Jan = 3 (3)
3296 * Mar : Jan..Feb = 3 (3 + 0)
3297 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3298 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3299 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3300 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3301 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3302 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3303 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3304 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3305 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3306 */
3307 uint64_t extra =
3308 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3309 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3310 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3311 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3312
3313 unsigned int y = tm->tm_year + 1900;
3314 unsigned int m = tm->tm_mon;
3315 unsigned long days = 0;
3316
3317 /* days since 1/1/1970 for full years */
3318 days += days_since_zero(y) - days_since_zero(1970);
3319
3320 /* days for full months in the current year */
3321 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3322
3323 /* count + 1 after March for leap years. A leap year is a year multiple
3324 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3325 * is leap, 1900 isn't, 1904 is.
3326 */
3327 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3328 days++;
3329
3330 days += tm->tm_mday - 1;
3331 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3332}
3333
Thierry Fournier93127942016-01-20 18:49:45 +01003334/* This function check a char. It returns true and updates
3335 * <date> and <len> pointer to the new position if the
3336 * character is found.
3337 */
3338static inline int parse_expect_char(const char **date, int *len, char c)
3339{
3340 if (*len < 1 || **date != c)
3341 return 0;
3342 (*len)--;
3343 (*date)++;
3344 return 1;
3345}
3346
3347/* This function expects a string <str> of len <l>. It return true and updates.
3348 * <date> and <len> if the string matches, otherwise, it returns false.
3349 */
3350static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3351{
3352 if (*len < l || strncmp(*date, str, l) != 0)
3353 return 0;
3354 (*len) -= l;
3355 (*date) += l;
3356 return 1;
3357}
3358
3359/* This macro converts 3 chars name in integer. */
3360#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3361
3362/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3363 * / %x54.75.65 ; "Tue", case-sensitive
3364 * / %x57.65.64 ; "Wed", case-sensitive
3365 * / %x54.68.75 ; "Thu", case-sensitive
3366 * / %x46.72.69 ; "Fri", case-sensitive
3367 * / %x53.61.74 ; "Sat", case-sensitive
3368 * / %x53.75.6E ; "Sun", case-sensitive
3369 *
3370 * This array must be alphabetically sorted
3371 */
3372static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3373{
3374 if (*len < 3)
3375 return 0;
3376 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3377 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3378 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3379 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3380 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3381 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3382 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3383 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3384 default: return 0;
3385 }
3386 *len -= 3;
3387 *date += 3;
3388 return 1;
3389}
3390
3391/* month = %x4A.61.6E ; "Jan", case-sensitive
3392 * / %x46.65.62 ; "Feb", case-sensitive
3393 * / %x4D.61.72 ; "Mar", case-sensitive
3394 * / %x41.70.72 ; "Apr", case-sensitive
3395 * / %x4D.61.79 ; "May", case-sensitive
3396 * / %x4A.75.6E ; "Jun", case-sensitive
3397 * / %x4A.75.6C ; "Jul", case-sensitive
3398 * / %x41.75.67 ; "Aug", case-sensitive
3399 * / %x53.65.70 ; "Sep", case-sensitive
3400 * / %x4F.63.74 ; "Oct", case-sensitive
3401 * / %x4E.6F.76 ; "Nov", case-sensitive
3402 * / %x44.65.63 ; "Dec", case-sensitive
3403 *
3404 * This array must be alphabetically sorted
3405 */
3406static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3407{
3408 if (*len < 3)
3409 return 0;
3410 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3411 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3412 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3413 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3414 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3415 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3416 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3417 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3418 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3419 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3420 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3421 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3422 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3423 default: return 0;
3424 }
3425 *len -= 3;
3426 *date += 3;
3427 return 1;
3428}
3429
3430/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3431 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3432 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3433 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3434 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3435 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3436 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3437 *
3438 * This array must be alphabetically sorted
3439 */
3440static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3441{
3442 if (*len < 6) /* Minimum length. */
3443 return 0;
3444 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3445 case STR2I3('M','o','n'):
3446 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3447 tm->tm_wday = 1;
3448 return 1;
3449 case STR2I3('T','u','e'):
3450 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3451 tm->tm_wday = 2;
3452 return 1;
3453 case STR2I3('W','e','d'):
3454 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3455 tm->tm_wday = 3;
3456 return 1;
3457 case STR2I3('T','h','u'):
3458 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3459 tm->tm_wday = 4;
3460 return 1;
3461 case STR2I3('F','r','i'):
3462 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3463 tm->tm_wday = 5;
3464 return 1;
3465 case STR2I3('S','a','t'):
3466 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3467 tm->tm_wday = 6;
3468 return 1;
3469 case STR2I3('S','u','n'):
3470 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3471 tm->tm_wday = 7;
3472 return 1;
3473 }
3474 return 0;
3475}
3476
3477/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3478static inline int parse_digit(const char **date, int *len, int *digit)
3479{
3480 if (*len < 1 || **date < '0' || **date > '9')
3481 return 0;
3482 *digit = (**date - '0');
3483 (*date)++;
3484 (*len)--;
3485 return 1;
3486}
3487
3488/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3489static inline int parse_2digit(const char **date, int *len, int *digit)
3490{
3491 int value;
3492
3493 RET0_UNLESS(parse_digit(date, len, &value));
3494 (*digit) = value * 10;
3495 RET0_UNLESS(parse_digit(date, len, &value));
3496 (*digit) += value;
3497
3498 return 1;
3499}
3500
3501/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3502static inline int parse_4digit(const char **date, int *len, int *digit)
3503{
3504 int value;
3505
3506 RET0_UNLESS(parse_digit(date, len, &value));
3507 (*digit) = value * 1000;
3508
3509 RET0_UNLESS(parse_digit(date, len, &value));
3510 (*digit) += value * 100;
3511
3512 RET0_UNLESS(parse_digit(date, len, &value));
3513 (*digit) += value * 10;
3514
3515 RET0_UNLESS(parse_digit(date, len, &value));
3516 (*digit) += value;
3517
3518 return 1;
3519}
3520
3521/* time-of-day = hour ":" minute ":" second
3522 * ; 00:00:00 - 23:59:60 (leap second)
3523 *
3524 * hour = 2DIGIT
3525 * minute = 2DIGIT
3526 * second = 2DIGIT
3527 */
3528static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3529{
3530 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3531 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3532 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3533 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3534 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3535 return 1;
3536}
3537
3538/* From RFC7231
3539 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3540 *
3541 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3542 * ; fixed length/zone/capitalization subset of the format
3543 * ; see Section 3.3 of [RFC5322]
3544 *
3545 *
3546 * date1 = day SP month SP year
3547 * ; e.g., 02 Jun 1982
3548 *
3549 * day = 2DIGIT
3550 * year = 4DIGIT
3551 *
3552 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3553 *
3554 * time-of-day = hour ":" minute ":" second
3555 * ; 00:00:00 - 23:59:60 (leap second)
3556 *
3557 * hour = 2DIGIT
3558 * minute = 2DIGIT
3559 * second = 2DIGIT
3560 *
3561 * DIGIT = decimal 0-9
3562 */
3563int parse_imf_date(const char *date, int len, struct tm *tm)
3564{
David Carlier327298c2016-11-20 10:42:38 +00003565 /* tm_gmtoff, if present, ought to be zero'ed */
3566 memset(tm, 0, sizeof(*tm));
3567
Thierry Fournier93127942016-01-20 18:49:45 +01003568 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3569 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3570 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3571 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3572 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3573 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3574 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3575 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3576 tm->tm_year -= 1900;
3577 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3578 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3579 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3580 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3581 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003582 return 1;
3583}
3584
3585/* From RFC7231
3586 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3587 *
3588 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3589 * date2 = day "-" month "-" 2DIGIT
3590 * ; e.g., 02-Jun-82
3591 *
3592 * day = 2DIGIT
3593 */
3594int parse_rfc850_date(const char *date, int len, struct tm *tm)
3595{
3596 int year;
3597
David Carlier327298c2016-11-20 10:42:38 +00003598 /* tm_gmtoff, if present, ought to be zero'ed */
3599 memset(tm, 0, sizeof(*tm));
3600
Thierry Fournier93127942016-01-20 18:49:45 +01003601 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3602 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3603 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3604 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3605 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3606 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3607 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3608
3609 /* year = 2DIGIT
3610 *
3611 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3612 * two-digit year, MUST interpret a timestamp that appears to be more
3613 * than 50 years in the future as representing the most recent year in
3614 * the past that had the same last two digits.
3615 */
3616 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3617
3618 /* expect SP */
3619 if (!parse_expect_char(&date, &len, ' ')) {
3620 /* Maybe we have the date with 4 digits. */
3621 RET0_UNLESS(parse_2digit(&date, &len, &year));
3622 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3623 /* expect SP */
3624 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3625 } else {
3626 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3627 * tm_year is the number of year since 1900, so for +1900, we
3628 * do nothing, and for +2000, we add 100.
3629 */
3630 if (tm->tm_year <= 60)
3631 tm->tm_year += 100;
3632 }
3633
3634 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3635 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3636 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3637 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003638
3639 return 1;
3640}
3641
3642/* From RFC7231
3643 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3644 *
3645 * asctime-date = day-name SP date3 SP time-of-day SP year
3646 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3647 * ; e.g., Jun 2
3648 *
3649 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3650 * whitespace in an HTTP-date beyond that specifically included as SP in
3651 * the grammar.
3652 */
3653int parse_asctime_date(const char *date, int len, struct tm *tm)
3654{
David Carlier327298c2016-11-20 10:42:38 +00003655 /* tm_gmtoff, if present, ought to be zero'ed */
3656 memset(tm, 0, sizeof(*tm));
3657
Thierry Fournier93127942016-01-20 18:49:45 +01003658 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3659 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3660 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3661 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3662
3663 /* expect SP and 1DIGIT or 2DIGIT */
3664 if (parse_expect_char(&date, &len, ' '))
3665 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3666 else
3667 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3668
3669 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3670 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3671 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3672 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3673 tm->tm_year -= 1900;
3674 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003675 return 1;
3676}
3677
3678/* From RFC7231
3679 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3680 *
3681 * HTTP-date = IMF-fixdate / obs-date
3682 * obs-date = rfc850-date / asctime-date
3683 *
3684 * parses an HTTP date in the RFC format and is accepted
3685 * alternatives. <date> is the strinf containing the date,
3686 * len is the len of the string. <tm> is filled with the
3687 * parsed time. We must considers this time as GMT.
3688 */
3689int parse_http_date(const char *date, int len, struct tm *tm)
3690{
3691 if (parse_imf_date(date, len, tm))
3692 return 1;
3693
3694 if (parse_rfc850_date(date, len, tm))
3695 return 1;
3696
3697 if (parse_asctime_date(date, len, tm))
3698 return 1;
3699
3700 return 0;
3701}
3702
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003703/* Dynamically allocates a string of the proper length to hold the formatted
3704 * output. NULL is returned on error. The caller is responsible for freeing the
3705 * memory area using free(). The resulting string is returned in <out> if the
3706 * pointer is not NULL. A previous version of <out> might be used to build the
3707 * new string, and it will be freed before returning if it is not NULL, which
3708 * makes it possible to build complex strings from iterative calls without
3709 * having to care about freeing intermediate values, as in the example below :
3710 *
3711 * memprintf(&err, "invalid argument: '%s'", arg);
3712 * ...
3713 * memprintf(&err, "parser said : <%s>\n", *err);
3714 * ...
3715 * free(*err);
3716 *
3717 * This means that <err> must be initialized to NULL before first invocation.
3718 * The return value also holds the allocated string, which eases error checking
3719 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003720 * passed instead and it will be ignored. The returned message will then also
3721 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003722 *
3723 * It is also convenient to use it without any free except the last one :
3724 * err = NULL;
3725 * if (!fct1(err)) report(*err);
3726 * if (!fct2(err)) report(*err);
3727 * if (!fct3(err)) report(*err);
3728 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003729 *
3730 * memprintf relies on memvprintf. This last version can be called from any
3731 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003732 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003733char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003734{
3735 va_list args;
3736 char *ret = NULL;
3737 int allocated = 0;
3738 int needed = 0;
3739
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003740 if (!out)
3741 return NULL;
3742
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003743 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003744 char buf1;
3745
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003746 /* vsnprintf() will return the required length even when the
3747 * target buffer is NULL. We do this in a loop just in case
3748 * intermediate evaluations get wrong.
3749 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003750 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003751 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003752 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003753 if (needed < allocated) {
3754 /* Note: on Solaris 8, the first iteration always
3755 * returns -1 if allocated is zero, so we force a
3756 * retry.
3757 */
3758 if (!allocated)
3759 needed = 0;
3760 else
3761 break;
3762 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003763
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003764 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003765 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003766 } while (ret);
3767
3768 if (needed < 0) {
3769 /* an error was encountered */
3770 free(ret);
3771 ret = NULL;
3772 }
3773
3774 if (out) {
3775 free(*out);
3776 *out = ret;
3777 }
3778
3779 return ret;
3780}
William Lallemand421f5b52012-02-06 18:15:57 +01003781
Christopher Faulet93a518f2017-10-24 11:25:33 +02003782char *memprintf(char **out, const char *format, ...)
3783{
3784 va_list args;
3785 char *ret = NULL;
3786
3787 va_start(args, format);
3788 ret = memvprintf(out, format, args);
3789 va_end(args);
3790
3791 return ret;
3792}
3793
Willy Tarreau21c705b2012-09-14 11:40:36 +02003794/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3795 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003796 * freed by the caller. It also supports being passed a NULL which results in the same
3797 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003798 * Example of use :
3799 * parse(cmd, &err); (callee: memprintf(&err, ...))
3800 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3801 * free(err);
3802 */
3803char *indent_msg(char **out, int level)
3804{
3805 char *ret, *in, *p;
3806 int needed = 0;
3807 int lf = 0;
3808 int lastlf = 0;
3809 int len;
3810
Willy Tarreau70eec382012-10-10 08:56:47 +02003811 if (!out || !*out)
3812 return NULL;
3813
Willy Tarreau21c705b2012-09-14 11:40:36 +02003814 in = *out - 1;
3815 while ((in = strchr(in + 1, '\n')) != NULL) {
3816 lastlf = in - *out;
3817 lf++;
3818 }
3819
3820 if (!lf) /* single line, no LF, return it as-is */
3821 return *out;
3822
3823 len = strlen(*out);
3824
3825 if (lf == 1 && lastlf == len - 1) {
3826 /* single line, LF at end, strip it and return as-is */
3827 (*out)[lastlf] = 0;
3828 return *out;
3829 }
3830
3831 /* OK now we have at least one LF, we need to process the whole string
3832 * as a multi-line string. What we'll do :
3833 * - prefix with an LF if there is none
3834 * - add <level> spaces before each line
3835 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3836 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3837 */
3838
3839 needed = 1 + level * (lf + 1) + len + 1;
3840 p = ret = malloc(needed);
3841 in = *out;
3842
3843 /* skip initial LFs */
3844 while (*in == '\n')
3845 in++;
3846
3847 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3848 while (*in) {
3849 *p++ = '\n';
3850 memset(p, ' ', level);
3851 p += level;
3852 do {
3853 *p++ = *in++;
3854 } while (*in && *in != '\n');
3855 if (*in)
3856 in++;
3857 }
3858 *p = 0;
3859
3860 free(*out);
3861 *out = ret;
3862
3863 return ret;
3864}
3865
Willy Tarreaua2c99112019-08-21 13:17:37 +02003866/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3867 * and end of lines replaced with <eol> if not 0. The first line to indent has
3868 * to be indicated in <first> (starts at zero), so that it is possible to skip
3869 * indenting the first line if it has to be appended after an existing message.
3870 * Empty strings are never indented, and NULL strings are considered empty both
3871 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3872 * character, non-zero otherwise.
3873 */
3874int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3875{
3876 int bol, lf;
3877 int pfxlen = pfx ? strlen(pfx) : 0;
3878
3879 if (!in)
3880 return 0;
3881
3882 bol = 1;
3883 lf = 0;
3884 while (*in) {
3885 if (bol && pfxlen) {
3886 if (first > 0)
3887 first--;
3888 else
3889 b_putblk(out, pfx, pfxlen);
3890 bol = 0;
3891 }
3892
3893 lf = (*in == '\n');
3894 bol |= lf;
3895 b_putchr(out, (lf && eol) ? eol : *in);
3896 in++;
3897 }
3898 return lf;
3899}
3900
Willy Tarreau9d22e562019-03-29 18:49:09 +01003901/* removes environment variable <name> from the environment as found in
3902 * environ. This is only provided as an alternative for systems without
3903 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003904 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003905 * <name> and to replace the matching pointers with the last pointer of
3906 * the array (since variables are not ordered).
3907 * It always returns 0 (success).
3908 */
3909int my_unsetenv(const char *name)
3910{
3911 extern char **environ;
3912 char **p = environ;
3913 int vars;
3914 int next;
3915 int len;
3916
3917 len = strlen(name);
3918 for (vars = 0; p[vars]; vars++)
3919 ;
3920 next = 0;
3921 while (next < vars) {
3922 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3923 next++;
3924 continue;
3925 }
3926 if (next < vars - 1)
3927 p[next] = p[vars - 1];
3928 p[--vars] = NULL;
3929 }
3930 return 0;
3931}
3932
Willy Tarreaudad36a32013-03-11 01:20:04 +01003933/* Convert occurrences of environment variables in the input string to their
3934 * corresponding value. A variable is identified as a series of alphanumeric
3935 * characters or underscores following a '$' sign. The <in> string must be
3936 * free()able. NULL returns NULL. The resulting string might be reallocated if
3937 * some expansion is made. Variable names may also be enclosed into braces if
3938 * needed (eg: to concatenate alphanum characters).
3939 */
3940char *env_expand(char *in)
3941{
3942 char *txt_beg;
3943 char *out;
3944 char *txt_end;
3945 char *var_beg;
3946 char *var_end;
3947 char *value;
3948 char *next;
3949 int out_len;
3950 int val_len;
3951
3952 if (!in)
3953 return in;
3954
3955 value = out = NULL;
3956 out_len = 0;
3957
3958 txt_beg = in;
3959 do {
3960 /* look for next '$' sign in <in> */
3961 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3962
3963 if (!*txt_end && !out) /* end and no expansion performed */
3964 return in;
3965
3966 val_len = 0;
3967 next = txt_end;
3968 if (*txt_end == '$') {
3969 char save;
3970
3971 var_beg = txt_end + 1;
3972 if (*var_beg == '{')
3973 var_beg++;
3974
3975 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003976 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003977 var_end++;
3978 }
3979
3980 next = var_end;
3981 if (*var_end == '}' && (var_beg > txt_end + 1))
3982 next++;
3983
3984 /* get value of the variable name at this location */
3985 save = *var_end;
3986 *var_end = '\0';
3987 value = getenv(var_beg);
3988 *var_end = save;
3989 val_len = value ? strlen(value) : 0;
3990 }
3991
Hubert Verstraete831962e2016-06-28 22:44:26 +02003992 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003993 if (txt_end > txt_beg) {
3994 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3995 out_len += txt_end - txt_beg;
3996 }
3997 if (val_len) {
3998 memcpy(out + out_len, value, val_len);
3999 out_len += val_len;
4000 }
4001 out[out_len] = 0;
4002 txt_beg = next;
4003 } while (*txt_beg);
4004
4005 /* here we know that <out> was allocated and that we don't need <in> anymore */
4006 free(in);
4007 return out;
4008}
4009
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004010
4011/* same as strstr() but case-insensitive and with limit length */
4012const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4013{
4014 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004015 unsigned int slen, plen;
4016 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004017
4018 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4019 return NULL;
4020
4021 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4022 return str1;
4023
4024 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4025 return NULL;
4026
4027 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 +02004028 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004029 start++;
4030 slen--;
4031 tmp1++;
4032
4033 if (tmp1 >= len_str1)
4034 return NULL;
4035
4036 /* if pattern longer than string */
4037 if (slen < plen)
4038 return NULL;
4039 }
4040
4041 sptr = start;
4042 pptr = (char *)str2;
4043
4044 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004045 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004046 sptr++;
4047 pptr++;
4048 tmp2++;
4049
4050 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4051 return start;
4052 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4053 return NULL;
4054 }
4055 }
4056 return NULL;
4057}
4058
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004059/* This function read the next valid utf8 char.
4060 * <s> is the byte srray to be decode, <len> is its length.
4061 * The function returns decoded char encoded like this:
4062 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4063 * are the length read. The decoded character is stored in <c>.
4064 */
4065unsigned char utf8_next(const char *s, int len, unsigned int *c)
4066{
4067 const unsigned char *p = (unsigned char *)s;
4068 int dec;
4069 unsigned char code = UTF8_CODE_OK;
4070
4071 if (len < 1)
4072 return UTF8_CODE_OK;
4073
4074 /* Check the type of UTF8 sequence
4075 *
4076 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4077 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4078 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4079 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4080 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4081 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4082 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4083 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4084 */
4085 switch (*p) {
4086 case 0x00 ... 0x7f:
4087 *c = *p;
4088 return UTF8_CODE_OK | 1;
4089
4090 case 0x80 ... 0xbf:
4091 *c = *p;
4092 return UTF8_CODE_BADSEQ | 1;
4093
4094 case 0xc0 ... 0xdf:
4095 if (len < 2) {
4096 *c = *p;
4097 return UTF8_CODE_BADSEQ | 1;
4098 }
4099 *c = *p & 0x1f;
4100 dec = 1;
4101 break;
4102
4103 case 0xe0 ... 0xef:
4104 if (len < 3) {
4105 *c = *p;
4106 return UTF8_CODE_BADSEQ | 1;
4107 }
4108 *c = *p & 0x0f;
4109 dec = 2;
4110 break;
4111
4112 case 0xf0 ... 0xf7:
4113 if (len < 4) {
4114 *c = *p;
4115 return UTF8_CODE_BADSEQ | 1;
4116 }
4117 *c = *p & 0x07;
4118 dec = 3;
4119 break;
4120
4121 case 0xf8 ... 0xfb:
4122 if (len < 5) {
4123 *c = *p;
4124 return UTF8_CODE_BADSEQ | 1;
4125 }
4126 *c = *p & 0x03;
4127 dec = 4;
4128 break;
4129
4130 case 0xfc ... 0xfd:
4131 if (len < 6) {
4132 *c = *p;
4133 return UTF8_CODE_BADSEQ | 1;
4134 }
4135 *c = *p & 0x01;
4136 dec = 5;
4137 break;
4138
4139 case 0xfe ... 0xff:
4140 default:
4141 *c = *p;
4142 return UTF8_CODE_BADSEQ | 1;
4143 }
4144
4145 p++;
4146
4147 while (dec > 0) {
4148
4149 /* need 0x10 for the 2 first bits */
4150 if ( ( *p & 0xc0 ) != 0x80 )
4151 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4152
4153 /* add data at char */
4154 *c = ( *c << 6 ) | ( *p & 0x3f );
4155
4156 dec--;
4157 p++;
4158 }
4159
4160 /* Check ovelong encoding.
4161 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4162 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4163 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4164 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004165 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004166 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4167 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4168 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4169 code |= UTF8_CODE_OVERLONG;
4170
4171 /* Check invalid UTF8 range. */
4172 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4173 (*c >= 0xfffe && *c <= 0xffff))
4174 code |= UTF8_CODE_INVRANGE;
4175
4176 return code | ((p-(unsigned char *)s)&0x0f);
4177}
4178
Maxime de Roucydc887852016-05-13 23:52:54 +02004179/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4180 * On failure : return 0 and <err> filled with an error message.
4181 * The caller is responsible for freeing the <err> and <str> copy
4182 * memory area using free()
4183 */
4184int list_append_word(struct list *li, const char *str, char **err)
4185{
4186 struct wordlist *wl;
4187
4188 wl = calloc(1, sizeof(*wl));
4189 if (!wl) {
4190 memprintf(err, "out of memory");
4191 goto fail_wl;
4192 }
4193
4194 wl->s = strdup(str);
4195 if (!wl->s) {
4196 memprintf(err, "out of memory");
4197 goto fail_wl_s;
4198 }
4199
4200 LIST_ADDQ(li, &wl->list);
4201
4202 return 1;
4203
4204fail_wl_s:
4205 free(wl->s);
4206fail_wl:
4207 free(wl);
4208 return 0;
4209}
4210
Willy Tarreau37101052019-05-20 16:48:20 +02004211/* indicates if a memory location may safely be read or not. The trick consists
4212 * in performing a harmless syscall using this location as an input and letting
4213 * the operating system report whether it's OK or not. For this we have the
4214 * stat() syscall, which will return EFAULT when the memory location supposed
4215 * to contain the file name is not readable. If it is readable it will then
4216 * either return 0 if the area contains an existing file name, or -1 with
4217 * another code. This must not be abused, and some audit systems might detect
4218 * this as abnormal activity. It's used only for unsafe dumps.
4219 */
4220int may_access(const void *ptr)
4221{
4222 struct stat buf;
4223
4224 if (stat(ptr, &buf) == 0)
4225 return 1;
4226 if (errno == EFAULT)
4227 return 0;
4228 return 1;
4229}
4230
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004231/* print a string of text buffer to <out>. The format is :
4232 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4233 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4234 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4235 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004236int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004237{
4238 unsigned char c;
4239 int ptr = 0;
4240
4241 while (buf[ptr] && ptr < bsize) {
4242 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004243 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004244 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004245 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004246 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004247 }
4248 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004249 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004250 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004251 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004252 switch (c) {
4253 case ' ': c = ' '; break;
4254 case '\t': c = 't'; break;
4255 case '\n': c = 'n'; break;
4256 case '\r': c = 'r'; break;
4257 case '\e': c = 'e'; break;
4258 case '\\': c = '\\'; break;
4259 case '=': c = '='; break;
4260 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004261 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004262 }
4263 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004264 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004265 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004266 out->area[out->data++] = '\\';
4267 out->area[out->data++] = 'x';
4268 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4269 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004270 }
4271 ptr++;
4272 }
4273
4274 return ptr;
4275}
4276
4277/* print a buffer in hexa.
4278 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4279 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004280int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004281{
4282 unsigned char c;
4283 int ptr = 0;
4284
4285 while (ptr < bsize) {
4286 c = buf[ptr];
4287
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004288 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004289 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004290 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4291 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004292
4293 ptr++;
4294 }
4295 return ptr;
4296}
4297
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004298/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4299 * prepending each line with prefix <pfx>. The output is *not* initialized.
4300 * The output will not wrap pas the buffer's end so it is more optimal if the
4301 * caller makes sure the buffer is aligned first. A trailing zero will always
4302 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004303 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4304 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004305 */
Willy Tarreau37101052019-05-20 16:48:20 +02004306void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004307{
4308 const unsigned char *d = buf;
4309 int i, j, start;
4310
4311 d = (const unsigned char *)(((unsigned long)buf) & -16);
4312 start = ((unsigned long)buf) & 15;
4313
4314 for (i = 0; i < start + len; i += 16) {
4315 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4316
Willy Tarreau37101052019-05-20 16:48:20 +02004317 // 0: unchecked, 1: checked safe, 2: danger
4318 unsafe = !!unsafe;
4319 if (unsafe && !may_access(d + i))
4320 unsafe = 2;
4321
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004322 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004323 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004324 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004325 else if (unsafe > 1)
4326 chunk_strcat(out, "** ");
4327 else
4328 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004329
4330 if (j == 7)
4331 chunk_strcat(out, "- ");
4332 }
4333 chunk_strcat(out, " ");
4334 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004335 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004336 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004337 else if (unsafe > 1)
4338 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004339 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004340 chunk_appendf(out, "%c", d[i + j]);
4341 else
4342 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004343 }
4344 chunk_strcat(out, "\n");
4345 }
4346}
4347
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004348/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4349 * enclosed in brackets after the address itself, formatted on 14 chars
4350 * including the "0x" prefix. This is meant to be used as a prefix for code
4351 * areas. For example:
4352 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4353 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4354 * is emitted. A NULL <pfx> will be considered empty.
4355 */
4356void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4357{
4358 int ok = 0;
4359 int i;
4360
4361 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4362
4363 for (i = 0; i < n; i++) {
4364 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4365 ok = may_access(addr + i);
4366 if (ok)
4367 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4368 else
4369 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4370 }
4371}
4372
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004373/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4374 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4375 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4376 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4377 * lines are respected within the limit of 70 output chars. Lines that are
4378 * continuation of a previous truncated line begin with "+" instead of " "
4379 * after the offset. The new pointer is returned.
4380 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004381int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004382 int *line, int ptr)
4383{
4384 int end;
4385 unsigned char c;
4386
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004387 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004388 if (end > out->size)
4389 return ptr;
4390
4391 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4392
4393 while (ptr < len && ptr < bsize) {
4394 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004395 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004396 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004397 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004398 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004399 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004400 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004401 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004402 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004403 switch (c) {
4404 case '\t': c = 't'; break;
4405 case '\n': c = 'n'; break;
4406 case '\r': c = 'r'; break;
4407 case '\e': c = 'e'; break;
4408 case '\\': c = '\\'; break;
4409 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004410 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004411 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004412 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004413 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004414 out->area[out->data++] = '\\';
4415 out->area[out->data++] = 'x';
4416 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4417 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004418 }
4419 if (buf[ptr++] == '\n') {
4420 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004421 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004422 *line = ptr;
4423 return ptr;
4424 }
4425 }
4426 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004427 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004428 return ptr;
4429}
4430
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004431/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004432 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4433 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004434 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004435void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4436 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004437{
Willy Tarreau73459792017-04-11 07:58:08 +02004438 unsigned int i;
4439 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004440
4441 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4442 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004443 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004444 for (j = 0; j < 8; j++) {
4445 if (b + j >= 0 && b + j < len)
4446 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4447 else
4448 fprintf(out, " ");
4449 }
4450
4451 if (b + j >= 0 && b + j < len)
4452 fputc('-', out);
4453 else
4454 fputc(' ', out);
4455
4456 for (j = 8; j < 16; j++) {
4457 if (b + j >= 0 && b + j < len)
4458 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4459 else
4460 fprintf(out, " ");
4461 }
4462
4463 fprintf(out, " ");
4464 for (j = 0; j < 16; j++) {
4465 if (b + j >= 0 && b + j < len) {
4466 if (isprint((unsigned char)buf[b + j]))
4467 fputc((unsigned char)buf[b + j], out);
4468 else
4469 fputc('.', out);
4470 }
4471 else
4472 fputc(' ', out);
4473 }
4474 fputc('\n', out);
4475 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004476}
4477
Willy Tarreaubb869862020-04-16 10:52:41 +02004478/* Tries to report the executable path name on platforms supporting this. If
4479 * not found or not possible, returns NULL.
4480 */
4481const char *get_exec_path()
4482{
4483 const char *ret = NULL;
4484
4485#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4486 long execfn = getauxval(AT_EXECFN);
4487
4488 if (execfn && execfn != ENOENT)
4489 ret = (const char *)execfn;
4490#endif
4491 return ret;
4492}
4493
Baruch Siache1651b22020-07-24 07:52:20 +03004494#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004495/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4496 * also returns the symbol size in <size>, otherwise returns 0 there.
4497 */
4498static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4499{
4500 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004501#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004502 const ElfW(Sym) *sym;
4503
4504 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4505 if (ret)
4506 *size = sym ? sym->st_size : 0;
4507#else
4508 ret = dladdr(addr, dli);
4509 *size = 0;
4510#endif
4511 return ret;
4512}
4513#endif
4514
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004515/* Tries to append to buffer <buf> some indications about the symbol at address
4516 * <addr> using the following form:
4517 * lib:+0xoffset (unresolvable address from lib's base)
4518 * main+0xoffset (unresolvable address from main (+/-))
4519 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4520 * name (resolved exact exec address)
4521 * lib:name (resolved exact lib address)
4522 * name+0xoffset/0xsize (resolved address within exec symbol)
4523 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4524 *
4525 * The file name (lib or executable) is limited to what lies between the last
4526 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4527 * 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 +03004528 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004529 *
4530 * The symbol's base address is returned, or NULL when unresolved, in order to
4531 * allow the caller to match it against known ones.
4532 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004533const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004534{
4535 const struct {
4536 const void *func;
4537 const char *name;
4538 } fcts[] = {
4539 { .func = process_stream, .name = "process_stream" },
4540 { .func = task_run_applet, .name = "task_run_applet" },
4541 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4542 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4543 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4544 { .func = listener_accept, .name = "listener_accept" },
4545 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4546 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4547#ifdef USE_LUA
4548 { .func = hlua_process_task, .name = "hlua_process_task" },
4549#endif
4550#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4551 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4552 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4553#endif
4554 };
4555
Baruch Siache1651b22020-07-24 07:52:20 +03004556#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004557 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004558 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004559 const char *fname, *p;
4560#endif
4561 int i;
4562
4563 if (pfx)
4564 chunk_appendf(buf, "%s", pfx);
4565
4566 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4567 if (addr == fcts[i].func) {
4568 chunk_appendf(buf, "%s", fcts[i].name);
4569 return addr;
4570 }
4571 }
4572
Baruch Siache1651b22020-07-24 07:52:20 +03004573#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004574 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004575 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004576 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004577
4578 /* 1. prefix the library name if it's not the same object as the one
4579 * that contains the main function. The name is picked between last '/'
4580 * and first following '.'.
4581 */
4582 if (!dladdr(main, &dli_main))
4583 dli_main.dli_fbase = NULL;
4584
4585 if (dli_main.dli_fbase != dli.dli_fbase) {
4586 fname = dli.dli_fname;
4587 p = strrchr(fname, '/');
4588 if (p++)
4589 fname = p;
4590 p = strchr(fname, '.');
4591 if (!p)
4592 p = fname + strlen(fname);
4593
4594 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4595 }
4596
4597 /* 2. symbol name */
4598 if (dli.dli_sname) {
4599 /* known, dump it and return symbol's address (exact or relative) */
4600 chunk_appendf(buf, "%s", dli.dli_sname);
4601 if (addr != dli.dli_saddr) {
4602 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004603 if (size)
4604 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004605 }
4606 return dli.dli_saddr;
4607 }
4608 else if (dli_main.dli_fbase != dli.dli_fbase) {
4609 /* unresolved symbol from a known library, report relative offset */
4610 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4611 return NULL;
4612 }
Baruch Siache1651b22020-07-24 07:52:20 +03004613#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004614 unknown:
4615 /* unresolved symbol from the main file, report relative offset to main */
4616 if ((void*)addr < (void*)main)
4617 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4618 else
4619 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4620 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004621}
4622
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004623/*
4624 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004625 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004626 *
4627 * First, initializes the value with <sz> as address to 0 and initializes the
4628 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4629 * address updating <sz> pointed value to the size of this array.
4630 *
4631 * Returns 1 if succeeded, 0 if not.
4632 */
4633int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4634{
4635 unsigned int *n;
4636 const char *s, *end;
4637
4638 s = str;
4639 *sz = 0;
4640 end = str + strlen(str);
4641 *nums = n = NULL;
4642
4643 while (1) {
4644 unsigned int r;
4645
4646 if (s >= end)
4647 break;
4648
4649 r = read_uint(&s, end);
4650 /* Expected characters after having read an uint: '\0' or '.',
4651 * if '.', must not be terminal.
4652 */
4653 if (*s != '\0'&& (*s++ != '.' || s == end))
4654 return 0;
4655
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004656 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004657 if (!n)
4658 return 0;
4659
4660 n[(*sz)++] = r;
4661 }
4662 *nums = n;
4663
4664 return 1;
4665}
4666
Willy Tarreau4d589e72019-08-23 19:02:26 +02004667
4668/* returns the number of bytes needed to encode <v> as a varint. An inline
4669 * version exists for use with constants (__varint_bytes()).
4670 */
4671int varint_bytes(uint64_t v)
4672{
4673 int len = 1;
4674
4675 if (v >= 240) {
4676 v = (v - 240) >> 4;
4677 while (1) {
4678 len++;
4679 if (v < 128)
4680 break;
4681 v = (v - 128) >> 7;
4682 }
4683 }
4684 return len;
4685}
4686
Willy Tarreau52bf8392020-03-08 00:42:37 +01004687
4688/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004689static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004690
4691/* This is a thread-safe implementation of xoroshiro128** described below:
4692 * http://prng.di.unimi.it/
4693 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4694 * supports fast jumps and passes all common quality tests. It is thread-safe,
4695 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4696 * local lock on other ones.
4697 */
4698uint64_t ha_random64()
4699{
4700 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004701 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4702 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004703
4704#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4705 static HA_SPINLOCK_T rand_lock;
4706
4707 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4708#endif
4709
4710 old[0] = ha_random_state[0];
4711 old[1] = ha_random_state[1];
4712
4713#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4714 do {
4715#endif
4716 result = rotl64(old[0] * 5, 7) * 9;
4717 new[1] = old[0] ^ old[1];
4718 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4719 new[1] = rotl64(new[1], 37); // c
4720
4721#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4722 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4723#else
4724 ha_random_state[0] = new[0];
4725 ha_random_state[1] = new[1];
4726#if defined(USE_THREAD)
4727 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4728#endif
4729#endif
4730 return result;
4731}
4732
4733/* seeds the random state using up to <len> bytes from <seed>, starting with
4734 * the first non-zero byte.
4735 */
4736void ha_random_seed(const unsigned char *seed, size_t len)
4737{
4738 size_t pos;
4739
4740 /* the seed must not be all zeroes, so we pre-fill it with alternating
4741 * bits and overwrite part of them with the block starting at the first
4742 * non-zero byte from the seed.
4743 */
4744 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4745
4746 for (pos = 0; pos < len; pos++)
4747 if (seed[pos] != 0)
4748 break;
4749
4750 if (pos == len)
4751 return;
4752
4753 seed += pos;
4754 len -= pos;
4755
4756 if (len > sizeof(ha_random_state))
4757 len = sizeof(ha_random_state);
4758
4759 memcpy(ha_random_state, seed, len);
4760}
4761
4762/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4763 * and is equivalent to calling ha_random64() as many times. It is used to
4764 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4765 * different generators (i.e. different processes after a fork). The <dist>
4766 * argument is the distance to jump to and is used in a loop so it rather not
4767 * be too large if the processing time is a concern.
4768 *
4769 * BEWARE: this function is NOT thread-safe and must not be called during
4770 * concurrent accesses to ha_random64().
4771 */
4772void ha_random_jump96(uint32_t dist)
4773{
4774 while (dist--) {
4775 uint64_t s0 = 0;
4776 uint64_t s1 = 0;
4777 int b;
4778
4779 for (b = 0; b < 64; b++) {
4780 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4781 s0 ^= ha_random_state[0];
4782 s1 ^= ha_random_state[1];
4783 }
4784 ha_random64();
4785 }
4786
4787 for (b = 0; b < 64; b++) {
4788 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4789 s0 ^= ha_random_state[0];
4790 s1 ^= ha_random_state[1];
4791 }
4792 ha_random64();
4793 }
4794 ha_random_state[0] = s0;
4795 ha_random_state[1] = s1;
4796 }
4797}
4798
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004799/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4800 * bytes large.
4801 */
4802void ha_generate_uuid(struct buffer *output)
4803{
4804 uint32_t rnd[4];
4805 uint64_t last;
4806
4807 last = ha_random64();
4808 rnd[0] = last;
4809 rnd[1] = last >> 32;
4810
4811 last = ha_random64();
4812 rnd[2] = last;
4813 rnd[3] = last >> 32;
4814
4815 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4816 rnd[0],
4817 rnd[1] & 0xFFFF,
4818 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4819 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4820 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4821}
4822
4823
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004824/* only used by parse_line() below. It supports writing in place provided that
4825 * <in> is updated to the next location before calling it. In that case, the
4826 * char at <in> may be overwritten.
4827 */
4828#define EMIT_CHAR(x) \
4829 do { \
4830 char __c = (char)(x); \
4831 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4832 err |= PARSE_ERR_OVERLAP; \
4833 if (outpos >= outmax) \
4834 err |= PARSE_ERR_TOOLARGE; \
4835 if (!err) \
4836 out[outpos] = __c; \
4837 outpos++; \
4838 } while (0)
4839
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004840/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004841 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4842 * extraneous ones are not emitted but <outlen> is updated so that the caller
4843 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4844 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004845 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4846 * it is guaranteed that at least one arg will point to the zero. It is safe
4847 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004848 *
4849 * <out> may overlap with <in> provided that it never goes further, in which
4850 * case the parser will accept to perform in-place parsing and unquoting/
4851 * unescaping but only if environment variables do not lead to expansion that
4852 * causes overlapping, otherwise the input string being destroyed, the error
4853 * will not be recoverable. Note that even during out-of-place <in> will
4854 * experience temporary modifications in-place for variable resolution and must
4855 * be writable, and will also receive zeroes to delimit words when using
4856 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4857 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4858 * starting point of the first invalid character sequence or unmatched
4859 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4860 * error reporting might be difficult since zeroes will have been inserted into
4861 * the string. One solution for the caller may consist in replacing all args
4862 * delimiters with spaces in this case.
4863 */
4864uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4865{
4866 char *quote = NULL;
4867 char *brace = NULL;
4868 unsigned char hex1, hex2;
4869 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004870 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004871 size_t outpos = 0;
4872 int squote = 0;
4873 int dquote = 0;
4874 int arg = 0;
4875 uint32_t err = 0;
4876
4877 *nbargs = 0;
4878 *outlen = 0;
4879
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004880 /* argsmax may be -1 here, protecting args[] from any write */
4881 if (arg < argsmax)
4882 args[arg] = out;
4883
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004884 while (1) {
4885 if (*in >= '-' && *in != '\\') {
4886 /* speedup: directly send all regular chars starting
4887 * with '-', '.', '/', alnum etc...
4888 */
4889 EMIT_CHAR(*in++);
4890 continue;
4891 }
4892 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4893 /* end of line */
4894 break;
4895 }
4896 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4897 /* comment */
4898 break;
4899 }
4900 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4901 if (dquote) {
4902 dquote = 0;
4903 quote = NULL;
4904 }
4905 else {
4906 dquote = 1;
4907 quote = in;
4908 }
4909 in++;
4910 continue;
4911 }
4912 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4913 if (squote) {
4914 squote = 0;
4915 quote = NULL;
4916 }
4917 else {
4918 squote = 1;
4919 quote = in;
4920 }
4921 in++;
4922 continue;
4923 }
4924 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4925 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4926 * C equivalent value but only when they have a special meaning and within
4927 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4928 */
4929 char tosend = *in;
4930
4931 switch (in[1]) {
4932 case ' ':
4933 case '\\':
4934 tosend = in[1];
4935 in++;
4936 break;
4937
4938 case 't':
4939 tosend = '\t';
4940 in++;
4941 break;
4942
4943 case 'n':
4944 tosend = '\n';
4945 in++;
4946 break;
4947
4948 case 'r':
4949 tosend = '\r';
4950 in++;
4951 break;
4952
4953 case '#':
4954 /* escaping of "#" only if comments are supported */
4955 if (opts & PARSE_OPT_SHARP)
4956 in++;
4957 tosend = *in;
4958 break;
4959
4960 case '\'':
4961 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4962 if (opts & PARSE_OPT_SQUOTE && !squote)
4963 in++;
4964 tosend = *in;
4965 break;
4966
4967 case '"':
4968 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4969 if (opts & PARSE_OPT_DQUOTE && !squote)
4970 in++;
4971 tosend = *in;
4972 break;
4973
4974 case '$':
4975 /* escaping of '$' only inside double quotes and only if env supported */
4976 if (opts & PARSE_OPT_ENV && dquote)
4977 in++;
4978 tosend = *in;
4979 break;
4980
4981 case 'x':
4982 if (!ishex(in[2]) || !ishex(in[3])) {
4983 /* invalid or incomplete hex sequence */
4984 err |= PARSE_ERR_HEX;
4985 if (errptr)
4986 *errptr = in;
4987 goto leave;
4988 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02004989 hex1 = toupper((unsigned char)in[2]) - '0';
4990 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004991 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
4992 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
4993 tosend = (hex1 << 4) + hex2;
4994 in += 3;
4995 break;
4996
4997 default:
4998 /* other combinations are not escape sequences */
4999 break;
5000 }
5001
5002 in++;
5003 EMIT_CHAR(tosend);
5004 }
5005 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5006 /* a non-escaped space is an argument separator */
5007 while (isspace((unsigned char)*in))
5008 in++;
5009 EMIT_CHAR(0);
5010 arg++;
5011 if (arg < argsmax)
5012 args[arg] = out + outpos;
5013 else
5014 err |= PARSE_ERR_TOOMANY;
5015 }
5016 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5017 /* environment variables are evaluated anywhere, or only
5018 * inside double quotes if they are supported.
5019 */
5020 char *var_name;
5021 char save_char;
5022 char *value;
5023
5024 in++;
5025
5026 if (*in == '{')
5027 brace = in++;
5028
5029 if (!isalpha((unsigned char)*in) && *in != '_') {
5030 /* unacceptable character in variable name */
5031 err |= PARSE_ERR_VARNAME;
5032 if (errptr)
5033 *errptr = in;
5034 goto leave;
5035 }
5036
5037 var_name = in;
5038 while (isalnum((unsigned char)*in) || *in == '_')
5039 in++;
5040
5041 save_char = *in;
5042 *in = '\0';
5043 value = getenv(var_name);
5044 *in = save_char;
5045
5046 if (brace) {
5047 if (*in != '}') {
5048 /* unmatched brace */
5049 err |= PARSE_ERR_BRACE;
5050 if (errptr)
5051 *errptr = brace;
5052 goto leave;
5053 }
5054 in++;
5055 brace = NULL;
5056 }
5057
5058 if (value) {
5059 while (*value)
5060 EMIT_CHAR(*value++);
5061 }
5062 }
5063 else {
5064 /* any other regular char */
5065 EMIT_CHAR(*in++);
5066 }
5067 }
5068
5069 /* end of output string */
5070 EMIT_CHAR(0);
5071 arg++;
5072
5073 if (quote) {
5074 /* unmatched quote */
5075 err |= PARSE_ERR_QUOTE;
5076 if (errptr)
5077 *errptr = quote;
5078 goto leave;
5079 }
5080 leave:
5081 *nbargs = arg;
5082 *outlen = outpos;
5083
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005084 /* empty all trailing args by making them point to the trailing zero,
5085 * at least the last one in any case.
5086 */
5087 if (arg > argsmax)
5088 arg = argsmax;
5089
5090 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005091 args[arg++] = out + outpos - 1;
5092
5093 return err;
5094}
5095#undef EMIT_CHAR
5096
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005097/* This is used to sanitize an input line that's about to be used for error reporting.
5098 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5099 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5100 * If non-printable chars are present in the output. It returns the new offset <pos>
5101 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5102 * be at least 6 to support two "..." otherwise the result is undefined. The line
5103 * itself must have at least 7 chars allocated for the same reason.
5104 */
5105size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5106{
5107 size_t shift = 0;
5108 char *out = line;
5109 char *in = line;
5110 char *end = line + width;
5111
5112 if (pos >= width) {
5113 /* if we have to shift, we'll be out of context, so let's
5114 * try to put <pos> at the center of width.
5115 */
5116 shift = pos - width / 2;
5117 in += shift + 3;
5118 end = out + width - 3;
5119 out[0] = out[1] = out[2] = '.';
5120 out += 3;
5121 }
5122
5123 while (out < end && *in) {
5124 if (isspace((unsigned char)*in))
5125 *out++ = ' ';
5126 else if (isprint((unsigned char)*in))
5127 *out++ = *in;
5128 else
5129 *out++ = '?';
5130 in++;
5131 }
5132
5133 if (end < line + width) {
5134 out[0] = out[1] = out[2] = '.';
5135 out += 3;
5136 }
5137
5138 *out++ = 0;
5139 return pos - shift;
5140}
5141
Willy Tarreaubaaee002006-06-26 02:48:02 +02005142/*
5143 * Local variables:
5144 * c-indent-level: 8
5145 * c-basic-offset: 8
5146 * End:
5147 */