blob: 1f4fedaaaaf483bbec5e689cb212261734b44d3e [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
devnexen@gmail.comc4e52322021-08-17 12:55:49 +010019#if defined(__FreeBSD__)
20#include <elf.h>
21#include <dlfcn.h>
22extern void *__elf_aux_vector;
23#endif
24
David Carlierbd2cced2021-08-17 08:44:25 +010025#if defined(__NetBSD__)
26#include <sys/exec_elf.h>
27#include <dlfcn.h>
28#endif
29
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010030#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020033#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020034#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035#include <stdlib.h>
36#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010037#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020038#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010039#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020040#include <sys/stat.h>
41#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010042#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020043#include <netinet/in.h>
44#include <arpa/inet.h>
45
David Carlier43a56852022-03-04 15:50:48 +000046#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreau30053062020-08-20 16:39:14 +020047#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau0dc9e6d2022-08-01 11:55:57 +020052#include <import/ebmbtree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020053
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020054#include <haproxy/api.h>
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +020055#include <haproxy/applet.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020056#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020057#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020058#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020059#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020060#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020061#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010062#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020063#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010064#include <haproxy/resolvers.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020065#include <haproxy/sc_strm.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010066#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020067#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020068#include <haproxy/ssl_utils.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020069#include <haproxy/stconn.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020070#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020071#include <haproxy/tools.h>
Willy Tarreau08093cc2022-11-24 08:09:12 +010072#include <haproxy/xxhash.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010073
Thierry Fournier93127942016-01-20 18:49:45 +010074/* This macro returns false if the test __x is false. Many
75 * of the following parsing function must be abort the processing
76 * if it returns 0, so this macro is useful for writing light code.
77 */
78#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
79
Erwan Le Goas9c766372022-09-14 17:40:24 +020080/* Define the number of line of hash_word */
Erwan Le Goas5eef1582022-09-29 10:25:31 +020081#define NB_L_HASH_WORD 15
Erwan Le Goas9c766372022-09-14 17:40:24 +020082
Willy Tarreau08093cc2022-11-24 08:09:12 +010083/* return the hash of a string and length for a given key. All keys are valid. */
84#define HA_ANON(key, str, len) (XXH32(str, len, key) & 0xFFFFFF)
85
Willy Tarreau56adcf22012-12-23 18:00:29 +010086/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020087 * 2^64-1 = 18446744073709551615 or
88 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020089 *
90 * The HTML version needs room for adding the 25 characters
91 * '<span class="rls"></span>' around digits at positions 3N+1 in order
92 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020093 */
Christopher Faulet99bca652017-11-14 16:47:26 +010094THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
95THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020096
Willy Tarreau588297f2014-06-16 15:16:40 +020097/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
98 * to quote strings larger than a max configuration line.
99 */
Christopher Faulet99bca652017-11-14 16:47:26 +0100100THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
101THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +0200102
Willy Tarreau06e69b52021-03-02 14:01:35 +0100103/* thread-local PRNG state. It's modified to start from a different sequence
104 * on all threads upon startup. It must not be used or anything beyond getting
105 * statistical values as it's 100% predictable.
106 */
107THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
108
Willy Tarreau5b3cd952022-07-18 13:58:17 +0200109/* set to true if this is a static build */
110int build_is_static = 0;
111
Erwan Le Goas9c766372022-09-14 17:40:24 +0200112/* A global static table to store hashed words */
113static THREAD_LOCAL char hash_word[NB_L_HASH_WORD][20];
114static THREAD_LOCAL int index_hash = 0;
115
Willy Tarreaubaaee002006-06-26 02:48:02 +0200116/*
William Lallemande7340ec2012-01-24 11:15:39 +0100117 * unsigned long long ASCII representation
118 *
119 * return the last char '\0' or NULL if no enough
120 * space in dst
121 */
122char *ulltoa(unsigned long long n, char *dst, size_t size)
123{
124 int i = 0;
125 char *res;
126
127 switch(n) {
128 case 1ULL ... 9ULL:
129 i = 0;
130 break;
131
132 case 10ULL ... 99ULL:
133 i = 1;
134 break;
135
136 case 100ULL ... 999ULL:
137 i = 2;
138 break;
139
140 case 1000ULL ... 9999ULL:
141 i = 3;
142 break;
143
144 case 10000ULL ... 99999ULL:
145 i = 4;
146 break;
147
148 case 100000ULL ... 999999ULL:
149 i = 5;
150 break;
151
152 case 1000000ULL ... 9999999ULL:
153 i = 6;
154 break;
155
156 case 10000000ULL ... 99999999ULL:
157 i = 7;
158 break;
159
160 case 100000000ULL ... 999999999ULL:
161 i = 8;
162 break;
163
164 case 1000000000ULL ... 9999999999ULL:
165 i = 9;
166 break;
167
168 case 10000000000ULL ... 99999999999ULL:
169 i = 10;
170 break;
171
172 case 100000000000ULL ... 999999999999ULL:
173 i = 11;
174 break;
175
176 case 1000000000000ULL ... 9999999999999ULL:
177 i = 12;
178 break;
179
180 case 10000000000000ULL ... 99999999999999ULL:
181 i = 13;
182 break;
183
184 case 100000000000000ULL ... 999999999999999ULL:
185 i = 14;
186 break;
187
188 case 1000000000000000ULL ... 9999999999999999ULL:
189 i = 15;
190 break;
191
192 case 10000000000000000ULL ... 99999999999999999ULL:
193 i = 16;
194 break;
195
196 case 100000000000000000ULL ... 999999999999999999ULL:
197 i = 17;
198 break;
199
200 case 1000000000000000000ULL ... 9999999999999999999ULL:
201 i = 18;
202 break;
203
204 case 10000000000000000000ULL ... ULLONG_MAX:
205 i = 19;
206 break;
207 }
208 if (i + 2 > size) // (i + 1) + '\0'
209 return NULL; // too long
210 res = dst + i + 1;
211 *res = '\0';
212 for (; i >= 0; i--) {
213 dst[i] = n % 10ULL + '0';
214 n /= 10ULL;
215 }
216 return res;
217}
218
219/*
220 * unsigned long ASCII representation
221 *
222 * return the last char '\0' or NULL if no enough
223 * space in dst
224 */
225char *ultoa_o(unsigned long n, char *dst, size_t size)
226{
227 int i = 0;
228 char *res;
229
230 switch (n) {
231 case 0U ... 9UL:
232 i = 0;
233 break;
234
235 case 10U ... 99UL:
236 i = 1;
237 break;
238
239 case 100U ... 999UL:
240 i = 2;
241 break;
242
243 case 1000U ... 9999UL:
244 i = 3;
245 break;
246
247 case 10000U ... 99999UL:
248 i = 4;
249 break;
250
251 case 100000U ... 999999UL:
252 i = 5;
253 break;
254
255 case 1000000U ... 9999999UL:
256 i = 6;
257 break;
258
259 case 10000000U ... 99999999UL:
260 i = 7;
261 break;
262
263 case 100000000U ... 999999999UL:
264 i = 8;
265 break;
266#if __WORDSIZE == 32
267
268 case 1000000000ULL ... ULONG_MAX:
269 i = 9;
270 break;
271
272#elif __WORDSIZE == 64
273
274 case 1000000000ULL ... 9999999999UL:
275 i = 9;
276 break;
277
278 case 10000000000ULL ... 99999999999UL:
279 i = 10;
280 break;
281
282 case 100000000000ULL ... 999999999999UL:
283 i = 11;
284 break;
285
286 case 1000000000000ULL ... 9999999999999UL:
287 i = 12;
288 break;
289
290 case 10000000000000ULL ... 99999999999999UL:
291 i = 13;
292 break;
293
294 case 100000000000000ULL ... 999999999999999UL:
295 i = 14;
296 break;
297
298 case 1000000000000000ULL ... 9999999999999999UL:
299 i = 15;
300 break;
301
302 case 10000000000000000ULL ... 99999999999999999UL:
303 i = 16;
304 break;
305
306 case 100000000000000000ULL ... 999999999999999999UL:
307 i = 17;
308 break;
309
310 case 1000000000000000000ULL ... 9999999999999999999UL:
311 i = 18;
312 break;
313
314 case 10000000000000000000ULL ... ULONG_MAX:
315 i = 19;
316 break;
317
318#endif
319 }
320 if (i + 2 > size) // (i + 1) + '\0'
321 return NULL; // too long
322 res = dst + i + 1;
323 *res = '\0';
324 for (; i >= 0; i--) {
325 dst[i] = n % 10U + '0';
326 n /= 10U;
327 }
328 return res;
329}
330
331/*
332 * signed long ASCII representation
333 *
334 * return the last char '\0' or NULL if no enough
335 * space in dst
336 */
337char *ltoa_o(long int n, char *dst, size_t size)
338{
339 char *pos = dst;
340
341 if (n < 0) {
342 if (size < 3)
343 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
344 *pos = '-';
345 pos++;
346 dst = ultoa_o(-n, pos, size - 1);
347 } else {
348 dst = ultoa_o(n, dst, size);
349 }
350 return dst;
351}
352
353/*
354 * signed long long ASCII representation
355 *
356 * return the last char '\0' or NULL if no enough
357 * space in dst
358 */
359char *lltoa(long long n, char *dst, size_t size)
360{
361 char *pos = dst;
362
363 if (n < 0) {
364 if (size < 3)
365 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
366 *pos = '-';
367 pos++;
368 dst = ulltoa(-n, pos, size - 1);
369 } else {
370 dst = ulltoa(n, dst, size);
371 }
372 return dst;
373}
374
375/*
376 * write a ascii representation of a unsigned into dst,
377 * return a pointer to the last character
378 * Pad the ascii representation with '0', using size.
379 */
380char *utoa_pad(unsigned int n, char *dst, size_t size)
381{
382 int i = 0;
383 char *ret;
384
385 switch(n) {
386 case 0U ... 9U:
387 i = 0;
388 break;
389
390 case 10U ... 99U:
391 i = 1;
392 break;
393
394 case 100U ... 999U:
395 i = 2;
396 break;
397
398 case 1000U ... 9999U:
399 i = 3;
400 break;
401
402 case 10000U ... 99999U:
403 i = 4;
404 break;
405
406 case 100000U ... 999999U:
407 i = 5;
408 break;
409
410 case 1000000U ... 9999999U:
411 i = 6;
412 break;
413
414 case 10000000U ... 99999999U:
415 i = 7;
416 break;
417
418 case 100000000U ... 999999999U:
419 i = 8;
420 break;
421
422 case 1000000000U ... 4294967295U:
423 i = 9;
424 break;
425 }
426 if (i + 2 > size) // (i + 1) + '\0'
427 return NULL; // too long
Aurelien DARRAGONe3177af2022-11-22 11:42:07 +0100428 i = size - 2; // padding - '\0'
William Lallemande7340ec2012-01-24 11:15:39 +0100429
430 ret = dst + i + 1;
431 *ret = '\0';
432 for (; i >= 0; i--) {
433 dst[i] = n % 10U + '0';
434 n /= 10U;
435 }
436 return ret;
437}
438
439/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200440 * copies at most <size-1> chars from <src> to <dst>. Last char is always
441 * set to 0, unless <size> is 0. The number of chars copied is returned
442 * (excluding the terminating zero).
443 * This code has been optimized for size and speed : on x86, it's 45 bytes
444 * long, uses only registers, and consumes only 4 cycles per char.
445 */
446int strlcpy2(char *dst, const char *src, int size)
447{
448 char *orig = dst;
449 if (size) {
450 while (--size && (*dst = *src)) {
451 src++; dst++;
452 }
453 *dst = 0;
454 }
455 return dst - orig;
456}
457
458/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200459 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200460 * the ascii representation for number 'n' in decimal.
461 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100462char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200463{
464 char *pos;
465
Willy Tarreau72d759c2007-10-25 12:14:10 +0200466 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200467 *pos-- = '\0';
468
469 do {
470 *pos-- = '0' + n % 10;
471 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200472 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200473 return pos + 1;
474}
475
Willy Tarreau91092e52007-10-25 16:58:42 +0200476/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200477 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200478 * the ascii representation for number 'n' in decimal.
479 */
480char *lltoa_r(long long int in, char *buffer, int size)
481{
482 char *pos;
483 int neg = 0;
484 unsigned long long int n;
485
486 pos = buffer + size - 1;
487 *pos-- = '\0';
488
489 if (in < 0) {
490 neg = 1;
491 n = -in;
492 }
493 else
494 n = in;
495
496 do {
497 *pos-- = '0' + n % 10;
498 n /= 10;
499 } while (n && pos >= buffer);
500 if (neg && pos > buffer)
501 *pos-- = '-';
502 return pos + 1;
503}
504
505/*
506 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200507 * the ascii representation for signed number 'n' in decimal.
508 */
509char *sltoa_r(long n, char *buffer, int size)
510{
511 char *pos;
512
513 if (n >= 0)
514 return ultoa_r(n, buffer, size);
515
516 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
517 *pos = '-';
518 return pos;
519}
520
521/*
522 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200523 * the ascii representation for number 'n' in decimal, formatted for
524 * HTML output with tags to create visual grouping by 3 digits. The
525 * output needs to support at least 171 characters.
526 */
527const char *ulltoh_r(unsigned long long n, char *buffer, int size)
528{
529 char *start;
530 int digit = 0;
531
532 start = buffer + size;
533 *--start = '\0';
534
535 do {
536 if (digit == 3 && start >= buffer + 7)
537 memcpy(start -= 7, "</span>", 7);
538
539 if (start >= buffer + 1) {
540 *--start = '0' + n % 10;
541 n /= 10;
542 }
543
544 if (digit == 3 && start >= buffer + 18)
545 memcpy(start -= 18, "<span class=\"rls\">", 18);
546
547 if (digit++ == 3)
548 digit = 1;
549 } while (n && start > buffer);
550 return start;
551}
552
553/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200554 * This function simply returns a locally allocated string containing the ascii
555 * representation for number 'n' in decimal, unless n is 0 in which case it
556 * returns the alternate string (or an empty string if the alternate string is
557 * NULL). It use is intended for limits reported in reports, where it's
558 * desirable not to display anything if there is no limit. Warning! it shares
559 * the same vector as ultoa_r().
560 */
561const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
562{
563 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
564}
565
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200566/* Trims the first "%f" float in a string to its minimum number of digits after
567 * the decimal point by trimming trailing zeroes, even dropping the decimal
568 * point if not needed. The string is in <buffer> of length <len>, and the
569 * number is expected to start at or after position <num_start> (the first
570 * point appearing there is considered). A NUL character is always placed at
571 * the end if some trimming occurs. The new buffer length is returned.
572 */
573size_t flt_trim(char *buffer, size_t num_start, size_t len)
574{
575 char *end = buffer + len;
576 char *p = buffer + num_start;
577 char *trim;
578
579 do {
580 if (p >= end)
581 return len;
582 trim = p++;
583 } while (*trim != '.');
584
585 /* For now <trim> is on the decimal point. Let's look for any other
586 * meaningful digit after it.
587 */
588 while (p < end) {
589 if (*p++ != '0')
590 trim = p;
591 }
592
593 if (trim < end)
594 *trim = 0;
595
596 return trim - buffer;
597}
598
Willy Tarreauae03d262021-05-08 07:35:00 +0200599/*
600 * This function simply returns a locally allocated string containing
601 * the ascii representation for number 'n' in decimal with useless trailing
602 * zeroes trimmed.
603 */
604char *ftoa_r(double n, char *buffer, int size)
605{
606 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
607 return buffer;
608}
609
Willy Tarreau588297f2014-06-16 15:16:40 +0200610/* returns a locally allocated string containing the quoted encoding of the
611 * input string. The output may be truncated to QSTR_SIZE chars, but it is
612 * guaranteed that the string will always be properly terminated. Quotes are
613 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
614 * always be at least 4 chars.
615 */
616const char *qstr(const char *str)
617{
618 char *ret = quoted_str[quoted_idx];
619 char *p, *end;
620
621 if (++quoted_idx >= NB_QSTR)
622 quoted_idx = 0;
623
624 p = ret;
625 end = ret + QSTR_SIZE;
626
627 *p++ = '"';
628
629 /* always keep 3 chars to support passing "" and the ending " */
630 while (*str && p < end - 3) {
631 if (*str == '"') {
632 *p++ = '"';
633 *p++ = '"';
634 }
635 else
636 *p++ = *str;
637 str++;
638 }
639 *p++ = '"';
640 return ret;
641}
642
Robert Tsai81ae1952007-12-05 10:47:29 +0100643/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200644 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
645 *
646 * It looks like this one would be a good candidate for inlining, but this is
647 * not interesting because it around 35 bytes long and often called multiple
648 * times within the same function.
649 */
650int ishex(char s)
651{
652 s -= '0';
653 if ((unsigned char)s <= 9)
654 return 1;
655 s -= 'A' - '0';
656 if ((unsigned char)s <= 5)
657 return 1;
658 s -= 'a' - 'A';
659 if ((unsigned char)s <= 5)
660 return 1;
661 return 0;
662}
663
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100664/* rounds <i> down to the closest value having max 2 digits */
665unsigned int round_2dig(unsigned int i)
666{
667 unsigned int mul = 1;
668
669 while (i >= 100) {
670 i /= 10;
671 mul *= 10;
672 }
673 return i * mul;
674}
675
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100676/*
677 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
678 * invalid character is found, a pointer to it is returned. If everything is
679 * fine, NULL is returned.
680 */
681const char *invalid_char(const char *name)
682{
683 if (!*name)
684 return name;
685
686 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100687 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100688 *name != '_' && *name != '-')
689 return name;
690 name++;
691 }
692 return NULL;
693}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200694
695/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200696 * Checks <name> for invalid characters. Valid chars are [_.-] and those
697 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200698 * If an invalid character is found, a pointer to it is returned.
699 * If everything is fine, NULL is returned.
700 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200701static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200702
703 if (!*name)
704 return name;
705
706 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100707 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200708 *name != '_' && *name != '-')
709 return name;
710
711 name++;
712 }
713
714 return NULL;
715}
716
717/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200718 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
719 * If an invalid character is found, a pointer to it is returned.
720 * If everything is fine, NULL is returned.
721 */
722const char *invalid_domainchar(const char *name) {
723 return __invalid_char(name, isalnum);
724}
725
726/*
727 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
728 * If an invalid character is found, a pointer to it is returned.
729 * If everything is fine, NULL is returned.
730 */
731const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200732 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200733}
734
735/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100736 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100737 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
738 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
739 * the function tries to guess the address family from the syntax. If the
740 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100741 * string is assumed to contain only an address, no port. The address can be a
742 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
743 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
744 * The return address will only have the address family and the address set,
745 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100746 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
747 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100748 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200749 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100750struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200751{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100752 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100753 /* max IPv6 length, including brackets and terminating NULL */
754 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100755 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100756
757 /* check IPv6 with square brackets */
758 if (str[0] == '[') {
759 size_t iplength = strlen(str);
760
761 if (iplength < 4) {
762 /* minimal size is 4 when using brackets "[::]" */
763 goto fail;
764 }
765 else if (iplength >= sizeof(tmpip)) {
766 /* IPv6 literal can not be larger than tmpip */
767 goto fail;
768 }
769 else {
770 if (str[iplength - 1] != ']') {
771 /* if address started with bracket, it should end with bracket */
772 goto fail;
773 }
774 else {
775 memcpy(tmpip, str + 1, iplength - 2);
776 tmpip[iplength - 2] = '\0';
777 str = tmpip;
778 }
779 }
780 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100781
Willy Tarreaufab5a432011-03-04 15:31:53 +0100782 /* Any IPv6 address */
783 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100784 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
785 sa->ss_family = AF_INET6;
786 else if (sa->ss_family != AF_INET6)
787 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100788 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100789 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100790 }
791
Willy Tarreau24709282013-03-10 21:32:12 +0100792 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100793 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100794 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
795 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100796 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100797 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100798 }
799
800 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100801 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
802 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100803 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100804 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100805 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100806 }
807
808 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100809 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
810 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100811 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100812 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100813 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100814 }
815
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100816 if (!resolve)
817 return NULL;
818
Emeric Brund30e9a12020-12-23 18:49:16 +0100819 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200820 return NULL;
821
David du Colombierd5f43282011-03-17 10:40:16 +0100822#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200823 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100824 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100825 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100826
827 memset(&result, 0, sizeof(result));
828 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100829 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100830 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200831 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100832 hints.ai_protocol = 0;
833
834 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100835 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
836 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100837 else if (sa->ss_family != result->ai_family) {
838 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100839 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100840 }
Willy Tarreau24709282013-03-10 21:32:12 +0100841
David du Colombierd5f43282011-03-17 10:40:16 +0100842 switch (result->ai_family) {
843 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100844 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100845 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100846 success = 1;
847 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100848 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100849 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100850 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100851 success = 1;
852 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100853 }
854 }
855
Sean Carey58ea0392013-02-15 23:39:18 +0100856 if (result)
857 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100858
859 if (success)
860 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100861 }
David du Colombierd5f43282011-03-17 10:40:16 +0100862#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200863 /* try to resolve an IPv4/IPv6 hostname */
864 he = gethostbyname(str);
865 if (he) {
866 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
867 sa->ss_family = he->h_addrtype;
868 else if (sa->ss_family != he->h_addrtype)
869 goto fail;
870
871 switch (sa->ss_family) {
872 case AF_INET:
873 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100874 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200875 return sa;
876 case AF_INET6:
877 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100878 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200879 return sa;
880 }
881 }
882
David du Colombierd5f43282011-03-17 10:40:16 +0100883 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100884 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100885 return NULL;
886}
887
888/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100889 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
890 * range or offset consisting in two integers that the caller will have to
891 * check to find the relevant input format. The following format are supported :
892 *
893 * String format | address | port | low | high
894 * addr | <addr> | 0 | 0 | 0
895 * addr: | <addr> | 0 | 0 | 0
896 * addr:port | <addr> | <port> | <port> | <port>
897 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
898 * addr:+port | <addr> | <port> | 0 | <port>
899 * addr:-port | <addr> |-<port> | <port> | 0
900 *
901 * The detection of a port range or increment by the caller is made by
902 * comparing <low> and <high>. If both are equal, then port 0 means no port
903 * was specified. The caller may pass NULL for <low> and <high> if it is not
904 * interested in retrieving port ranges.
905 *
906 * Note that <addr> above may also be :
907 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
908 * - "*" => family will be AF_INET and address will be INADDR_ANY
909 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
910 * - a host name => family and address will depend on host name resolving.
911 *
Willy Tarreau24709282013-03-10 21:32:12 +0100912 * A prefix may be passed in before the address above to force the family :
913 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
914 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
915 * - "unix@" => force address to be a path to a UNIX socket even if the
916 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200917 * - 'abns@' -> force address to belong to the abstract namespace (Linux
918 * only). These sockets are just like Unix sockets but without
919 * the need for an underlying file system. The address is a
920 * string. Technically it's like a Unix socket with a zero in
921 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100922 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100923 *
mildisff5d5102015-10-26 18:50:08 +0100924 * IPv6 addresses can be declared with or without square brackets. When using
925 * square brackets for IPv6 addresses, the port separator (colon) is optional.
926 * If not using square brackets, and in order to avoid any ambiguity with
927 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
928 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
929 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100930 *
931 * If <pfx> is non-null, it is used as a string prefix before any path-based
932 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100933 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200934 * if <fqdn> is non-null, it will be filled with :
935 * - a pointer to the FQDN of the server name to resolve if there's one, and
936 * that the caller will have to free(),
937 * - NULL if there was an explicit address that doesn't require resolution.
938 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200939 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
940 * still honored so it is possible for the caller to know whether a resolution
941 * failed by clearing this flag and checking if <fqdn> was filled, indicating
942 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200943 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100944 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200945 * the address when cast to sockaddr_in and the address family is
946 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200947 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200948 * The matching protocol will be set into <proto> if non-null.
949 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200950 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
951 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100952 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200953struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
954 struct protocol **proto, char **err,
955 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100956{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100957 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100958 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200959 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100960 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100961 char *port1, *port2;
962 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200963 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200964 int new_fd = -1;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200965 enum proto_type proto_type;
966 int ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100967
968 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200969 if (fqdn)
970 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200971
Willy Tarreaudad36a32013-03-11 01:20:04 +0100972 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100973 if (str2 == NULL) {
974 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100975 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100976 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200977
Willy Tarreau9f69f462015-09-08 16:01:25 +0200978 if (!*str2) {
979 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
980 goto out;
981 }
982
Willy Tarreau24709282013-03-10 21:32:12 +0100983 memset(&ss, 0, sizeof(ss));
984
Willy Tarreaue835bd82020-09-16 11:35:47 +0200985 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100986 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
Willy Tarreaue3b45182021-10-27 17:28:55 +0200987 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM))) {
988 proto_type = PROTO_TYPE_DGRAM;
989 ctrl_type = SOCK_DGRAM;
990 } else {
991 proto_type = PROTO_TYPE_STREAM;
992 ctrl_type = SOCK_STREAM;
993 }
Willy Tarreaue835bd82020-09-16 11:35:47 +0200994
995 if (strncmp(str2, "stream+", 7) == 0) {
996 str2 += 7;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200997 proto_type = PROTO_TYPE_STREAM;
998 ctrl_type = SOCK_STREAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200999 }
1000 else if (strncmp(str2, "dgram+", 6) == 0) {
1001 str2 += 6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001002 proto_type = PROTO_TYPE_DGRAM;
1003 ctrl_type = SOCK_DGRAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001004 }
1005
Willy Tarreau24709282013-03-10 21:32:12 +01001006 if (strncmp(str2, "unix@", 5) == 0) {
1007 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +02001008 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +01001009 ss.ss_family = AF_UNIX;
1010 }
Emeric Brunce325c42021-04-02 17:05:09 +02001011 else if (strncmp(str2, "uxdg@", 5) == 0) {
1012 str2 += 5;
1013 abstract = 0;
1014 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001015 proto_type = PROTO_TYPE_DGRAM;
1016 ctrl_type = SOCK_DGRAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001017 }
1018 else if (strncmp(str2, "uxst@", 5) == 0) {
1019 str2 += 5;
1020 abstract = 0;
1021 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001022 proto_type = PROTO_TYPE_STREAM;
1023 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001024 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001025 else if (strncmp(str2, "abns@", 5) == 0) {
1026 str2 += 5;
1027 abstract = 1;
1028 ss.ss_family = AF_UNIX;
1029 }
Emeric Brunce325c42021-04-02 17:05:09 +02001030 else if (strncmp(str2, "ip@", 3) == 0) {
1031 str2 += 3;
1032 ss.ss_family = AF_UNSPEC;
1033 }
Willy Tarreau24709282013-03-10 21:32:12 +01001034 else if (strncmp(str2, "ipv4@", 5) == 0) {
1035 str2 += 5;
1036 ss.ss_family = AF_INET;
1037 }
1038 else if (strncmp(str2, "ipv6@", 5) == 0) {
1039 str2 += 5;
1040 ss.ss_family = AF_INET6;
1041 }
Emeric Brunce325c42021-04-02 17:05:09 +02001042 else if (strncmp(str2, "tcp4@", 5) == 0) {
1043 str2 += 5;
1044 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001045 proto_type = PROTO_TYPE_STREAM;
1046 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001047 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001048 else if (strncmp(str2, "udp4@", 5) == 0) {
1049 str2 += 5;
1050 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001051 proto_type = PROTO_TYPE_DGRAM;
1052 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001053 }
Emeric Brunce325c42021-04-02 17:05:09 +02001054 else if (strncmp(str2, "tcp6@", 5) == 0) {
1055 str2 += 5;
1056 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001057 proto_type = PROTO_TYPE_STREAM;
1058 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001059 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001060 else if (strncmp(str2, "udp6@", 5) == 0) {
1061 str2 += 5;
1062 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001063 proto_type = PROTO_TYPE_DGRAM;
1064 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001065 }
Emeric Brunce325c42021-04-02 17:05:09 +02001066 else if (strncmp(str2, "tcp@", 4) == 0) {
1067 str2 += 4;
1068 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001069 proto_type = PROTO_TYPE_STREAM;
1070 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001071 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001072 else if (strncmp(str2, "udp@", 4) == 0) {
1073 str2 += 4;
1074 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001075 proto_type = PROTO_TYPE_DGRAM;
1076 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001077 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001078 else if (strncmp(str2, "quic4@", 6) == 0) {
1079 str2 += 6;
1080 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001081 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001082 ctrl_type = SOCK_STREAM;
1083 }
1084 else if (strncmp(str2, "quic6@", 6) == 0) {
1085 str2 += 6;
1086 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001087 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001088 ctrl_type = SOCK_STREAM;
1089 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001090 else if (strncmp(str2, "fd@", 3) == 0) {
1091 str2 += 3;
1092 ss.ss_family = AF_CUST_EXISTING_FD;
1093 }
1094 else if (strncmp(str2, "sockpair@", 9) == 0) {
1095 str2 += 9;
1096 ss.ss_family = AF_CUST_SOCKPAIR;
1097 }
Willy Tarreau24709282013-03-10 21:32:12 +01001098 else if (*str2 == '/') {
1099 ss.ss_family = AF_UNIX;
1100 }
1101 else
1102 ss.ss_family = AF_UNSPEC;
1103
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001104 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001105 struct sockaddr_storage ss2;
1106 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001107 char *endptr;
1108
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001109 new_fd = strtol(str2, &endptr, 10);
1110 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001111 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1112 goto out;
1113 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001114
Willy Tarreaua215be22020-09-16 10:14:16 +02001115 /* just verify that it's a socket */
1116 addr_len = sizeof(ss2);
1117 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1118 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1119 goto out;
1120 }
1121
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001122 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1123 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001124 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001125 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001126 char *endptr;
1127
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001128 new_fd = strtol(str2, &endptr, 10);
1129 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001130 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001131 goto out;
1132 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001133
Willy Tarreau6edc7222020-09-15 17:41:56 +02001134 if (opts & PA_O_SOCKET_FD) {
1135 socklen_t addr_len;
1136 int type;
1137
1138 addr_len = sizeof(ss);
1139 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1140 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1141 goto out;
1142 }
1143
1144 addr_len = sizeof(type);
1145 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue3b45182021-10-27 17:28:55 +02001146 (type == SOCK_STREAM) != (proto_type == PROTO_TYPE_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001147 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1148 goto out;
1149 }
1150
1151 porta = portl = porth = get_host_port(&ss);
1152 } else if (opts & PA_O_RAW_FD) {
1153 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1154 ((struct sockaddr_in *)&ss)->sin_port = 0;
1155 } else {
1156 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1157 goto out;
1158 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001159 }
1160 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001161 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001162 int prefix_path_len;
1163 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001164 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001165
1166 /* complete unix socket path name during startup or soft-restart is
1167 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1168 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001169 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001170 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001171 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001172
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001173 adr_len = strlen(str2);
1174 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001175 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1176 goto out;
1177 }
1178
Willy Tarreauccfccef2014-05-10 01:49:15 +02001179 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001180 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001181 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001182 memcpy(un->sun_path, pfx, prefix_path_len);
1183 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001184 }
Willy Tarreau24709282013-03-10 21:32:12 +01001185 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001186 char *end = str2 + strlen(str2);
1187 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001188
mildisff5d5102015-10-26 18:50:08 +01001189 /* search for : or ] whatever comes first */
1190 for (chr = end-1; chr > str2; chr--) {
1191 if (*chr == ']' || *chr == ':')
1192 break;
1193 }
1194
1195 if (*chr == ':') {
1196 /* Found a colon before a closing-bracket, must be a port separator.
1197 * This guarantee backward compatibility.
1198 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001199 if (!(opts & PA_O_PORT_OK)) {
1200 memprintf(err, "port specification not permitted here in '%s'", str);
1201 goto out;
1202 }
mildisff5d5102015-10-26 18:50:08 +01001203 *chr++ = '\0';
1204 port1 = chr;
1205 }
1206 else {
1207 /* Either no colon and no closing-bracket
1208 * or directly ending with a closing-bracket.
1209 * However, no port.
1210 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001211 if (opts & PA_O_PORT_MAND) {
1212 memprintf(err, "missing port specification in '%s'", str);
1213 goto out;
1214 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001215 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001216 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001217
Willy Tarreau90807112020-02-25 08:16:33 +01001218 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001219 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001220 if (port2) {
1221 if (!(opts & PA_O_PORT_RANGE)) {
1222 memprintf(err, "port range not permitted here in '%s'", str);
1223 goto out;
1224 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001225 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001226 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001227 else
1228 port2 = port1;
1229 portl = atoi(port1);
1230 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001231
1232 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1233 memprintf(err, "invalid port '%s'", port1);
1234 goto out;
1235 }
1236
1237 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1238 memprintf(err, "invalid port '%s'", port2);
1239 goto out;
1240 }
1241
1242 if (portl > porth) {
1243 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1244 goto out;
1245 }
1246
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001247 porta = portl;
1248 }
1249 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001250 if (!(opts & PA_O_PORT_OFS)) {
1251 memprintf(err, "port offset not permitted here in '%s'", str);
1252 goto out;
1253 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001254 portl = atoi(port1 + 1);
1255 porta = -portl;
1256 }
1257 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001258 if (!(opts & PA_O_PORT_OFS)) {
1259 memprintf(err, "port offset not permitted here in '%s'", str);
1260 goto out;
1261 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001262 porth = atoi(port1 + 1);
1263 porta = porth;
1264 }
1265 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001266 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001267 goto out;
1268 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001269 else if (opts & PA_O_PORT_MAND) {
1270 memprintf(err, "missing port specification in '%s'", str);
1271 goto out;
1272 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001273
1274 /* first try to parse the IP without resolving. If it fails, it
1275 * tells us we need to keep a copy of the FQDN to resolve later
1276 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001277 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001278 */
1279 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001280 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1281 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001282 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1283 goto out;
1284 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001285
Willy Tarreauceccdd72016-11-02 22:27:10 +01001286 if (fqdn) {
1287 if (str2 != back)
1288 memmove(back, str2, strlen(str2) + 1);
1289 *fqdn = back;
1290 back = NULL;
1291 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001292 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001293 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001294 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001295
Willy Tarreaue835bd82020-09-16 11:35:47 +02001296 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001297 memprintf(err, "stream-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001298 goto out;
1299 }
1300 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001301 memprintf(err, "dgram-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001302 goto out;
1303 }
1304
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001305 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001306 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001307 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1308 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001309 * in which case the address is not known yet (this is only
1310 * for servers actually).
1311 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001312 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreaue3b45182021-10-27 17:28:55 +02001313 proto_type,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001314 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001315
Emeric Brun26754902021-04-07 14:26:44 +02001316 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001317 memprintf(err, "unsupported %s protocol for %s family %d address '%s'%s",
Willy Tarreau2b049b82022-05-20 17:28:30 +02001318 (ctrl_type == SOCK_DGRAM) ? "datagram" : "stream",
1319 (proto_type == PROTO_TYPE_DGRAM) ? "datagram" : "stream",
1320 ss.ss_family,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001321 str,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001322#ifndef USE_QUIC
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001323 (ctrl_type == SOCK_STREAM && proto_type == PROTO_TYPE_DGRAM)
1324 ? "; QUIC is not compiled in if this is what you were looking for."
1325 : ""
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001326#else
1327 ""
1328#endif
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001329 );
Willy Tarreau5fc93282020-09-16 18:25:03 +02001330 goto out;
1331 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001332
1333 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1334 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1335 goto out;
1336 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001337 }
1338
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001339 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001340 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001341 if (port)
1342 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001343 if (low)
1344 *low = portl;
1345 if (high)
1346 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001347 if (fd)
1348 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001349 if (proto)
1350 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001351 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001352 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001353}
1354
Thayne McCombs92149f92020-11-20 01:28:26 -07001355/* converts <addr> and <port> into a string representation of the address and port. This is sort
1356 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1357 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1358 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1359 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1360 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1361 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1362 *
1363 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1364 */
1365char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1366{
1367 char buffer[INET6_ADDRSTRLEN];
1368 char *out = NULL;
1369 const void *ptr;
1370 const char *path;
1371
1372 switch (addr->ss_family) {
1373 case AF_INET:
1374 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1375 break;
1376 case AF_INET6:
1377 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1378 break;
1379 case AF_UNIX:
1380 path = ((struct sockaddr_un *)addr)->sun_path;
1381 if (path[0] == '\0') {
1382 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1383 return memprintf(&out, "abns@%.*s", max_length, path+1);
1384 } else {
1385 return strdup(path);
1386 }
1387 case AF_CUST_SOCKPAIR:
1388 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1389 default:
1390 return NULL;
1391 }
Tim Duesterhus22535a52022-05-23 09:30:49 +02001392 if (inet_ntop(addr->ss_family, ptr, buffer, sizeof(buffer)) == NULL) {
1393 BUG_ON(errno == ENOSPC);
1394 return NULL;
1395 }
Thayne McCombs92149f92020-11-20 01:28:26 -07001396 if (map_ports)
1397 return memprintf(&out, "%s:%+d", buffer, port);
1398 else
1399 return memprintf(&out, "%s:%d", buffer, port);
1400}
1401
1402
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001403/* converts <str> to a struct in_addr containing a network mask. It can be
1404 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001405 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001406 */
1407int str2mask(const char *str, struct in_addr *mask)
1408{
1409 if (strchr(str, '.') != NULL) { /* dotted notation */
1410 if (!inet_pton(AF_INET, str, mask))
1411 return 0;
1412 }
1413 else { /* mask length */
1414 char *err;
1415 unsigned long len = strtol(str, &err, 10);
1416
1417 if (!*str || (err && *err) || (unsigned)len > 32)
1418 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001419
1420 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001421 }
1422 return 1;
1423}
1424
Tim Duesterhus47185172018-01-25 16:24:49 +01001425/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001426 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001427 * if the conversion succeeds otherwise zero.
1428 */
1429int str2mask6(const char *str, struct in6_addr *mask)
1430{
1431 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1432 if (!inet_pton(AF_INET6, str, mask))
1433 return 0;
1434 }
1435 else { /* mask length */
1436 char *err;
1437 unsigned long len = strtol(str, &err, 10);
1438
1439 if (!*str || (err && *err) || (unsigned)len > 128)
1440 return 0;
1441
1442 len2mask6(len, mask);
1443 }
1444 return 1;
1445}
1446
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001447/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1448 * succeeds otherwise zero.
1449 */
1450int cidr2dotted(int cidr, struct in_addr *mask) {
1451
1452 if (cidr < 0 || cidr > 32)
1453 return 0;
1454
1455 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1456 return 1;
1457}
1458
Thierry Fournier70473a52016-02-17 17:12:14 +01001459/* Convert mask from bit length form to in_addr form.
1460 * This function never fails.
1461 */
1462void len2mask4(int len, struct in_addr *addr)
1463{
1464 if (len >= 32) {
1465 addr->s_addr = 0xffffffff;
1466 return;
1467 }
1468 if (len <= 0) {
1469 addr->s_addr = 0x00000000;
1470 return;
1471 }
1472 addr->s_addr = 0xffffffff << (32 - len);
1473 addr->s_addr = htonl(addr->s_addr);
1474}
1475
1476/* Convert mask from bit length form to in6_addr form.
1477 * This function never fails.
1478 */
1479void len2mask6(int len, struct in6_addr *addr)
1480{
1481 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1482 len -= 32;
1483 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1484 len -= 32;
1485 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1486 len -= 32;
1487 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1488}
1489
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001490/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001491 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001492 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001493 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001494 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1495 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001496int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001497{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001498 __label__ out_free, out_err;
1499 char *c, *s;
1500 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001501
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001502 s = strdup(str);
1503 if (!s)
1504 return 0;
1505
Willy Tarreaubaaee002006-06-26 02:48:02 +02001506 memset(mask, 0, sizeof(*mask));
1507 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001508
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001509 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001510 *c++ = '\0';
1511 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001512 if (!str2mask(c, mask))
1513 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001514 }
1515 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001516 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001517 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001518 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001519 struct hostent *he;
1520
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001521 if (!resolve)
1522 goto out_err;
1523
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001524 if ((he = gethostbyname(s)) == NULL) {
1525 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001526 }
1527 else
1528 *addr = *(struct in_addr *) *(he->h_addr_list);
1529 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001530
1531 ret_val = 1;
1532 out_free:
1533 free(s);
1534 return ret_val;
1535 out_err:
1536 ret_val = 0;
1537 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001538}
1539
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001540
1541/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001542 * converts <str> to two struct in6_addr* which must be pre-allocated.
1543 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001544 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001545 * Returns 1 if OK, 0 if error.
1546 */
1547int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1548{
1549 char *c, *s;
1550 int ret_val = 0;
1551 char *err;
1552 unsigned long len = 128;
1553
1554 s = strdup(str);
1555 if (!s)
1556 return 0;
1557
1558 memset(mask, 0, sizeof(*mask));
1559 memset(addr, 0, sizeof(*addr));
1560
1561 if ((c = strrchr(s, '/')) != NULL) {
1562 *c++ = '\0'; /* c points to the mask */
1563 if (!*c)
1564 goto out_free;
1565
1566 len = strtoul(c, &err, 10);
1567 if ((err && *err) || (unsigned)len > 128)
1568 goto out_free;
1569 }
1570 *mask = len; /* OK we have a valid mask in <len> */
1571
1572 if (!inet_pton(AF_INET6, s, addr))
1573 goto out_free;
1574
1575 ret_val = 1;
1576 out_free:
1577 free(s);
1578 return ret_val;
1579}
1580
1581
1582/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001583 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1584 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1585 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001586 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001587int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001588{
1589 int saw_digit, octets, ch;
1590 u_char tmp[4], *tp;
1591 const char *cp = addr;
1592
1593 saw_digit = 0;
1594 octets = 0;
1595 *(tp = tmp) = 0;
1596
1597 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001598 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001599 if (digit > 9 && ch != '.')
1600 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001601 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001602 if (digit <= 9) {
1603 u_int new = *tp * 10 + digit;
1604 if (new > 255)
1605 return 0;
1606 *tp = new;
1607 if (!saw_digit) {
1608 if (++octets > 4)
1609 return 0;
1610 saw_digit = 1;
1611 }
1612 } else if (ch == '.' && saw_digit) {
1613 if (octets == 4)
1614 return 0;
1615 *++tp = 0;
1616 saw_digit = 0;
1617 } else
1618 return 0;
1619 }
1620
1621 if (octets < 4)
1622 return 0;
1623
1624 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001625 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001626}
1627
1628/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001629 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001630 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001631 * the hostname. Actually only http and https are supported. <out> can be NULL.
1632 * This function returns the consumed length. It is useful if you parse complete
1633 * url like http://host:port/path, because the consumed length corresponds to
1634 * the first character of the path. If the conversion fails, it returns -1.
1635 *
1636 * This function tries to resolve the DNS name if haproxy is in starting mode.
1637 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001638 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001639int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001640{
1641 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001642 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001643 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001644 unsigned long long int http_code = 0;
1645 int default_port;
1646 struct hostent *he;
1647 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001648
1649 /* Firstly, try to find :// pattern */
1650 while (curr < url+ulen && url_code != 0x3a2f2f) {
1651 url_code = ((url_code & 0xffff) << 8);
1652 url_code += (unsigned char)*curr++;
1653 }
1654
1655 /* Secondly, if :// pattern is found, verify parsed stuff
1656 * before pattern is matching our http pattern.
1657 * If so parse ip address and port in uri.
1658 *
1659 * WARNING: Current code doesn't support dynamic async dns resolver.
1660 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001661 if (url_code != 0x3a2f2f)
1662 return -1;
1663
1664 /* Copy scheme, and utrn to lower case. */
1665 while (cp < curr - 3)
1666 http_code = (http_code << 8) + *cp++;
1667 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001668
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001669 /* HTTP or HTTPS url matching */
1670 if (http_code == 0x2020202068747470ULL) {
1671 default_port = 80;
1672 if (out)
1673 out->scheme = SCH_HTTP;
1674 }
1675 else if (http_code == 0x2020206874747073ULL) {
1676 default_port = 443;
1677 if (out)
1678 out->scheme = SCH_HTTPS;
1679 }
1680 else
1681 return -1;
1682
1683 /* If the next char is '[', the host address is IPv6. */
1684 if (*curr == '[') {
1685 curr++;
1686
1687 /* Check trash size */
1688 if (trash.size < ulen)
1689 return -1;
1690
1691 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001692 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001693 for (end = curr;
1694 end < url + ulen && *end != ']';
1695 end++, p++)
1696 *p = *end;
1697 if (*end != ']')
1698 return -1;
1699 *p = '\0';
1700
1701 /* Update out. */
1702 if (out) {
1703 out->host = curr;
1704 out->host_len = end - curr;
1705 }
1706
1707 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001708 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001709 return -1;
1710 end++;
1711
1712 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001713 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001714 end++;
1715 default_port = read_uint(&end, url + ulen);
1716 }
1717 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1718 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1719 return end - url;
1720 }
1721 else {
William Lallemand8a913742022-02-18 16:13:12 +01001722 /* we need to copy the string into the trash because url2ipv4
1723 * needs a \0 at the end of the string */
1724 if (trash.size < ulen)
1725 return -1;
1726
1727 memcpy(trash.area, curr, ulen - (curr - url));
1728 trash.area[ulen - (curr - url)] = '\0';
1729
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001730 /* We are looking for IP address. If you want to parse and
1731 * resolve hostname found in url, you can use str2sa_range(), but
1732 * be warned this can slow down global daemon performances
1733 * while handling lagging dns responses.
1734 */
William Lallemand8a913742022-02-18 16:13:12 +01001735 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001736 if (ret) {
1737 /* Update out. */
1738 if (out) {
1739 out->host = curr;
1740 out->host_len = ret;
1741 }
1742
William Lallemandb938b772022-03-24 21:59:03 +01001743 curr += ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001744
1745 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001746 if (curr < url + ulen && *curr == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001747 curr++;
1748 default_port = read_uint(&curr, url + ulen);
1749 }
1750 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1751
1752 /* Set family. */
1753 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1754 return curr - url;
1755 }
1756 else if (global.mode & MODE_STARTING) {
1757 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1758 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001759 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001760
1761 /* look for : or / or end */
1762 for (end = curr;
1763 end < url + ulen && *end != '/' && *end != ':';
1764 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001765 memcpy(trash.area, curr, end - curr);
1766 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001767
1768 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001769 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001770 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001771 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001772
1773 /* Update out. */
1774 if (out) {
1775 out->host = curr;
1776 out->host_len = end - curr;
1777 }
1778
1779 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001780 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001781 end++;
1782 default_port = read_uint(&end, url + ulen);
1783 }
1784
1785 /* Copy IP address, set port and family. */
1786 switch (he->h_addrtype) {
1787 case AF_INET:
1788 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1789 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1790 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1791 return end - url;
1792
1793 case AF_INET6:
1794 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1795 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1796 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1797 return end - url;
1798 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001799 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001800 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001801 return -1;
1802}
1803
Willy Tarreau631f01c2011-09-05 00:36:48 +02001804/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1805 * address family is returned so that it's easy for the caller to adapt to the
1806 * output format. Zero is returned if the address family is not supported. -1
1807 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1808 * supported.
1809 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001810int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001811{
1812
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001813 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001814
1815 if (size < 5)
1816 return 0;
1817 *str = '\0';
1818
1819 switch (addr->ss_family) {
1820 case AF_INET:
1821 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1822 break;
1823 case AF_INET6:
1824 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1825 break;
1826 case AF_UNIX:
1827 memcpy(str, "unix", 5);
1828 return addr->ss_family;
1829 default:
1830 return 0;
1831 }
1832
1833 if (inet_ntop(addr->ss_family, ptr, str, size))
1834 return addr->ss_family;
1835
1836 /* failed */
1837 return -1;
1838}
1839
Simon Horman75ab8bd2014-06-16 09:39:41 +09001840/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1841 * address family is returned so that it's easy for the caller to adapt to the
1842 * output format. Zero is returned if the address family is not supported. -1
1843 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1844 * supported.
1845 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001846int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001847{
1848
1849 uint16_t port;
1850
1851
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001852 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001853 return 0;
1854 *str = '\0';
1855
1856 switch (addr->ss_family) {
1857 case AF_INET:
1858 port = ((struct sockaddr_in *)addr)->sin_port;
1859 break;
1860 case AF_INET6:
1861 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1862 break;
1863 case AF_UNIX:
1864 memcpy(str, "unix", 5);
1865 return addr->ss_family;
1866 default:
1867 return 0;
1868 }
1869
1870 snprintf(str, size, "%u", ntohs(port));
1871 return addr->ss_family;
1872}
1873
Willy Tarreau16e01562016-08-09 16:46:18 +02001874/* check if the given address is local to the system or not. It will return
1875 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1876 * it is. We don't want to iterate over all interfaces for this (and it is not
1877 * portable). So instead we try to bind in UDP to this address on a free non
1878 * privileged port and to connect to the same address, port 0 (connect doesn't
1879 * care). If it succeeds, we own the address. Note that non-inet addresses are
1880 * considered local since they're most likely AF_UNIX.
1881 */
1882int addr_is_local(const struct netns_entry *ns,
1883 const struct sockaddr_storage *orig)
1884{
1885 struct sockaddr_storage addr;
1886 int result;
1887 int fd;
1888
1889 if (!is_inet_addr(orig))
1890 return 1;
1891
1892 memcpy(&addr, orig, sizeof(addr));
1893 set_host_port(&addr, 0);
1894
1895 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1896 if (fd < 0)
1897 return -1;
1898
1899 result = -1;
1900 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1901 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1902 result = 0; // fail, non-local address
1903 else
1904 result = 1; // success, local address
1905 }
1906 else {
1907 if (errno == EADDRNOTAVAIL)
1908 result = 0; // definitely not local :-)
1909 }
1910 close(fd);
1911
1912 return result;
1913}
1914
Willy Tarreaubaaee002006-06-26 02:48:02 +02001915/* will try to encode the string <string> replacing all characters tagged in
1916 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1917 * prefixed by <escape>, and will store the result between <start> (included)
1918 * and <stop> (excluded), and will always terminate the string with a '\0'
1919 * before <stop>. The position of the '\0' is returned if the conversion
1920 * completes. If bytes are missing between <start> and <stop>, then the
1921 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1922 * cannot even be stored so we return <start> without writing the 0.
1923 * The input string must also be zero-terminated.
1924 */
1925const char hextab[16] = "0123456789ABCDEF";
1926char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001927 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001928 const char *string)
1929{
1930 if (start < stop) {
1931 stop--; /* reserve one byte for the final '\0' */
1932 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001933 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001934 *start++ = *string;
1935 else {
1936 if (start + 3 >= stop)
1937 break;
1938 *start++ = escape;
1939 *start++ = hextab[(*string >> 4) & 15];
1940 *start++ = hextab[*string & 15];
1941 }
1942 string++;
1943 }
1944 *start = '\0';
1945 }
1946 return start;
1947}
1948
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001949/*
1950 * Same behavior as encode_string() above, except that it encodes chunk
1951 * <chunk> instead of a string.
1952 */
1953char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001954 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001955 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001956{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001957 char *str = chunk->area;
1958 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001959
1960 if (start < stop) {
1961 stop--; /* reserve one byte for the final '\0' */
1962 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001963 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001964 *start++ = *str;
1965 else {
1966 if (start + 3 >= stop)
1967 break;
1968 *start++ = escape;
1969 *start++ = hextab[(*str >> 4) & 15];
1970 *start++ = hextab[*str & 15];
1971 }
1972 str++;
1973 }
1974 *start = '\0';
1975 }
1976 return start;
1977}
1978
Dragan Dosen0edd1092016-02-12 13:23:02 +01001979/*
1980 * Tries to prefix characters tagged in the <map> with the <escape>
Aurelien DARRAGONc5bff8e2022-09-20 14:33:18 +02001981 * character. The input <string> is processed until string_stop
1982 * is reached or NULL-byte is encountered. The result will
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001983 * be stored between <start> (included) and <stop> (excluded). This
1984 * function will always try to terminate the resulting string with a '\0'
1985 * before <stop>, and will return its position if the conversion
1986 * completes.
1987 */
1988char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001989 const char escape, const long *map,
Aurelien DARRAGONc5bff8e2022-09-20 14:33:18 +02001990 const char *string, const char *string_stop)
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001991{
1992 if (start < stop) {
1993 stop--; /* reserve one byte for the final '\0' */
Aurelien DARRAGONc5bff8e2022-09-20 14:33:18 +02001994 while (start < stop && string < string_stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001995 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001996 *start++ = *string;
1997 else {
1998 if (start + 2 >= stop)
1999 break;
2000 *start++ = escape;
2001 *start++ = *string;
2002 }
2003 string++;
2004 }
2005 *start = '\0';
2006 }
2007 return start;
2008}
2009
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002010/* Check a string for using it in a CSV output format. If the string contains
2011 * one of the following four char <">, <,>, CR or LF, the string is
2012 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2013 * <str> is the input string to be escaped. The function assumes that
2014 * the input string is null-terminated.
2015 *
2016 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002017 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002018 * format.
2019 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002020 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002021 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002022 * If <quote> is 1, the converter puts the quotes only if any reserved character
2023 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002024 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002025 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002026 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002027 * The function returns the converted string on its output. If an error
2028 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002029 * for using the function directly as printf() argument.
2030 *
2031 * If the output buffer is too short to contain the input string, the result
2032 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002033 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002034 * This function appends the encoding to the existing output chunk, and it
2035 * guarantees that it starts immediately at the first available character of
2036 * the chunk. Please use csv_enc() instead if you want to replace the output
2037 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002038 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002039const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002040{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002041 char *end = output->area + output->size;
2042 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002043 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002044
Willy Tarreaub631c292016-01-08 10:04:08 +01002045 if (quote == 1) {
2046 /* automatic quoting: first verify if we'll have to quote the string */
2047 if (!strpbrk(str, "\n\r,\""))
2048 quote = 0;
2049 }
2050
2051 if (quote)
2052 *ptr++ = '"';
2053
Willy Tarreau898529b2016-01-06 18:07:04 +01002054 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2055 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002056 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002057 ptr++;
2058 if (ptr >= end - 2) {
2059 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002060 break;
2061 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002062 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002063 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002064 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002065 str++;
2066 }
2067
Willy Tarreaub631c292016-01-08 10:04:08 +01002068 if (quote)
2069 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002070
Willy Tarreau898529b2016-01-06 18:07:04 +01002071 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002072 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002073 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002074}
2075
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002076/* Decode an URL-encoded string in-place. The resulting string might
2077 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002078 * aborted, the string is truncated before the issue and a negative value is
2079 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002080 * If the 'in_form' argument is non-nul the string is assumed to be part of
2081 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2082 * turned to a space. If it's zero, this will only be done after a question
2083 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002084 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002085int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002086{
2087 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002088 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002089
2090 in = string;
2091 out = string;
2092 while (*in) {
2093 switch (*in) {
2094 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002095 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002096 break;
2097 case '%' :
2098 if (!ishex(in[1]) || !ishex(in[2]))
2099 goto end;
2100 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2101 in += 2;
2102 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002103 case '?':
2104 in_form = 1;
Willy Tarreau7de8de02022-11-14 07:20:09 +01002105 __fallthrough;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002106 default:
2107 *out++ = *in;
2108 break;
2109 }
2110 in++;
2111 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002112 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002113 end:
2114 *out = 0;
2115 return ret;
2116}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002117
Willy Tarreau6911fa42007-03-04 18:06:08 +01002118unsigned int str2ui(const char *s)
2119{
2120 return __str2ui(s);
2121}
2122
2123unsigned int str2uic(const char *s)
2124{
2125 return __str2uic(s);
2126}
2127
2128unsigned int strl2ui(const char *s, int len)
2129{
2130 return __strl2ui(s, len);
2131}
2132
2133unsigned int strl2uic(const char *s, int len)
2134{
2135 return __strl2uic(s, len);
2136}
2137
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002138unsigned int read_uint(const char **s, const char *end)
2139{
2140 return __read_uint(s, end);
2141}
2142
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002143/* This function reads an unsigned integer from the string pointed to by <s> and
2144 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2145 * function automatically stops at <end>. If the number overflows, the 2^64-1
2146 * value is returned.
2147 */
2148unsigned long long int read_uint64(const char **s, const char *end)
2149{
2150 const char *ptr = *s;
2151 unsigned long long int i = 0, tmp;
2152 unsigned int j;
2153
2154 while (ptr < end) {
2155
2156 /* read next char */
2157 j = *ptr - '0';
2158 if (j > 9)
2159 goto read_uint64_end;
2160
2161 /* add char to the number and check overflow. */
2162 tmp = i * 10;
2163 if (tmp / 10 != i) {
2164 i = ULLONG_MAX;
2165 goto read_uint64_eat;
2166 }
2167 if (ULLONG_MAX - tmp < j) {
2168 i = ULLONG_MAX;
2169 goto read_uint64_eat;
2170 }
2171 i = tmp + j;
2172 ptr++;
2173 }
2174read_uint64_eat:
2175 /* eat each numeric char */
2176 while (ptr < end) {
2177 if ((unsigned int)(*ptr - '0') > 9)
2178 break;
2179 ptr++;
2180 }
2181read_uint64_end:
2182 *s = ptr;
2183 return i;
2184}
2185
2186/* This function reads an integer from the string pointed to by <s> and returns
2187 * it. The <s> pointer is adjusted to point to the first unread char. The function
2188 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2189 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2190 * returned.
2191 */
2192long long int read_int64(const char **s, const char *end)
2193{
2194 unsigned long long int i = 0;
2195 int neg = 0;
2196
2197 /* Look for minus char. */
2198 if (**s == '-') {
2199 neg = 1;
2200 (*s)++;
2201 }
2202 else if (**s == '+')
2203 (*s)++;
2204
2205 /* convert as positive number. */
2206 i = read_uint64(s, end);
2207
2208 if (neg) {
2209 if (i > 0x8000000000000000ULL)
2210 return LLONG_MIN;
2211 return -i;
2212 }
2213 if (i > 0x7fffffffffffffffULL)
2214 return LLONG_MAX;
2215 return i;
2216}
2217
Willy Tarreau6911fa42007-03-04 18:06:08 +01002218/* This one is 7 times faster than strtol() on athlon with checks.
2219 * It returns the value of the number composed of all valid digits read,
2220 * and can process negative numbers too.
2221 */
2222int strl2ic(const char *s, int len)
2223{
2224 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002225 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002226
2227 if (len > 0) {
2228 if (*s != '-') {
2229 /* positive number */
2230 while (len-- > 0) {
2231 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002232 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002233 if (j > 9)
2234 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002235 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002236 }
2237 } else {
2238 /* negative number */
2239 s++;
2240 while (--len > 0) {
2241 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002242 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002243 if (j > 9)
2244 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002245 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002246 }
2247 }
2248 }
2249 return i;
2250}
2251
2252
2253/* This function reads exactly <len> chars from <s> and converts them to a
2254 * signed integer which it stores into <ret>. It accurately detects any error
2255 * (truncated string, invalid chars, overflows). It is meant to be used in
2256 * applications designed for hostile environments. It returns zero when the
2257 * number has successfully been converted, non-zero otherwise. When an error
2258 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2259 * faster than strtol().
2260 */
2261int strl2irc(const char *s, int len, int *ret)
2262{
2263 int i = 0;
2264 int j;
2265
2266 if (!len)
2267 return 1;
2268
2269 if (*s != '-') {
2270 /* positive number */
2271 while (len-- > 0) {
2272 j = (*s++) - '0';
2273 if (j > 9) return 1; /* invalid char */
2274 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2275 i = i * 10;
2276 if (i + j < i) return 1; /* check for addition overflow */
2277 i = i + j;
2278 }
2279 } else {
2280 /* negative number */
2281 s++;
2282 while (--len > 0) {
2283 j = (*s++) - '0';
2284 if (j > 9) return 1; /* invalid char */
2285 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2286 i = i * 10;
2287 if (i - j > i) return 1; /* check for subtract overflow */
2288 i = i - j;
2289 }
2290 }
2291 *ret = i;
2292 return 0;
2293}
2294
2295
2296/* This function reads exactly <len> chars from <s> and converts them to a
2297 * signed integer which it stores into <ret>. It accurately detects any error
2298 * (truncated string, invalid chars, overflows). It is meant to be used in
2299 * applications designed for hostile environments. It returns zero when the
2300 * number has successfully been converted, non-zero otherwise. When an error
2301 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002302 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002303 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002304
2305int strl2llrc(const char *s, int len, long long *ret)
2306{
2307 long long i = 0;
2308 int j;
2309
2310 if (!len)
2311 return 1;
2312
2313 if (*s != '-') {
2314 /* positive number */
2315 while (len-- > 0) {
2316 j = (*s++) - '0';
2317 if (j > 9) return 1; /* invalid char */
2318 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2319 i = i * 10LL;
2320 if (i + j < i) return 1; /* check for addition overflow */
2321 i = i + j;
2322 }
2323 } else {
2324 /* negative number */
2325 s++;
2326 while (--len > 0) {
2327 j = (*s++) - '0';
2328 if (j > 9) return 1; /* invalid char */
2329 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2330 i = i * 10LL;
2331 if (i - j > i) return 1; /* check for subtract overflow */
2332 i = i - j;
2333 }
2334 }
2335 *ret = i;
2336 return 0;
2337}
2338
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002339/* This function is used with pat_parse_dotted_ver(). It converts a string
2340 * composed by two number separated by a dot. Each part must contain in 16 bits
2341 * because internally they will be represented as a 32-bit quantity stored in
2342 * a 64-bit integer. It returns zero when the number has successfully been
2343 * converted, non-zero otherwise. When an error is returned, the <ret> value
2344 * is left untouched.
2345 *
2346 * "1.3" -> 0x0000000000010003
2347 * "65535.65535" -> 0x00000000ffffffff
2348 */
2349int strl2llrc_dotted(const char *text, int len, long long *ret)
2350{
2351 const char *end = &text[len];
2352 const char *p;
2353 long long major, minor;
2354
2355 /* Look for dot. */
2356 for (p = text; p < end; p++)
2357 if (*p == '.')
2358 break;
2359
2360 /* Convert major. */
2361 if (strl2llrc(text, p - text, &major) != 0)
2362 return 1;
2363
2364 /* Check major. */
2365 if (major >= 65536)
2366 return 1;
2367
2368 /* Convert minor. */
2369 minor = 0;
2370 if (p < end)
2371 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2372 return 1;
2373
2374 /* Check minor. */
2375 if (minor >= 65536)
2376 return 1;
2377
2378 /* Compose value. */
2379 *ret = (major << 16) | (minor & 0xffff);
2380 return 0;
2381}
2382
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002383/* This function parses a time value optionally followed by a unit suffix among
2384 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2385 * expected by the caller. The computation does its best to avoid overflows.
2386 * The value is returned in <ret> if everything is fine, and a NULL is returned
2387 * by the function. In case of error, a pointer to the error is returned and
2388 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002389 * Values resulting in values larger than or equal to 2^31 after conversion are
2390 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2391 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002392 */
2393const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2394{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002395 unsigned long long imult, idiv;
2396 unsigned long long omult, odiv;
2397 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002398 const char *str = text;
2399
2400 if (!isdigit((unsigned char)*text))
2401 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002402
2403 omult = odiv = 1;
2404
2405 switch (unit_flags & TIME_UNIT_MASK) {
2406 case TIME_UNIT_US: omult = 1000000; break;
2407 case TIME_UNIT_MS: omult = 1000; break;
2408 case TIME_UNIT_S: break;
2409 case TIME_UNIT_MIN: odiv = 60; break;
2410 case TIME_UNIT_HOUR: odiv = 3600; break;
2411 case TIME_UNIT_DAY: odiv = 86400; break;
2412 default: break;
2413 }
2414
2415 value = 0;
2416
2417 while (1) {
2418 unsigned int j;
2419
2420 j = *text - '0';
2421 if (j > 9)
2422 break;
2423 text++;
2424 value *= 10;
2425 value += j;
2426 }
2427
2428 imult = idiv = 1;
2429 switch (*text) {
2430 case '\0': /* no unit = default unit */
2431 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002432 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002433 case 's': /* second = unscaled unit */
2434 break;
2435 case 'u': /* microsecond : "us" */
2436 if (text[1] == 's') {
2437 idiv = 1000000;
2438 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002439 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002440 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002441 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002442 case 'm': /* millisecond : "ms" or minute: "m" */
2443 if (text[1] == 's') {
2444 idiv = 1000;
2445 text++;
2446 } else
2447 imult = 60;
2448 break;
2449 case 'h': /* hour : "h" */
2450 imult = 3600;
2451 break;
2452 case 'd': /* day : "d" */
2453 imult = 86400;
2454 break;
2455 default:
2456 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002457 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002458 if (*(++text) != '\0') {
2459 ha_warning("unexpected character '%c' after the timer value '%s', only "
2460 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2461 " This will be reported as an error in next versions.\n", *text, str);
2462 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002463
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002464 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002465 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2466 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2467 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2468 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2469
Willy Tarreau9faebe32019-06-07 19:00:37 +02002470 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2471 if (result >= 0x80000000)
2472 return PARSE_TIME_OVER;
2473 if (!result && value)
2474 return PARSE_TIME_UNDER;
2475 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002476 return NULL;
2477}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002478
Emeric Brun39132b22010-01-04 14:57:24 +01002479/* this function converts the string starting at <text> to an unsigned int
2480 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002481 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002482 */
2483const char *parse_size_err(const char *text, unsigned *ret) {
2484 unsigned value = 0;
2485
Christopher Faulet82635a02020-12-11 09:30:45 +01002486 if (!isdigit((unsigned char)*text))
2487 return text;
2488
Emeric Brun39132b22010-01-04 14:57:24 +01002489 while (1) {
2490 unsigned int j;
2491
2492 j = *text - '0';
2493 if (j > 9)
2494 break;
2495 if (value > ~0U / 10)
2496 return text;
2497 value *= 10;
2498 if (value > (value + j))
2499 return text;
2500 value += j;
2501 text++;
2502 }
2503
2504 switch (*text) {
2505 case '\0':
2506 break;
2507 case 'K':
2508 case 'k':
2509 if (value > ~0U >> 10)
2510 return text;
2511 value = value << 10;
2512 break;
2513 case 'M':
2514 case 'm':
2515 if (value > ~0U >> 20)
2516 return text;
2517 value = value << 20;
2518 break;
2519 case 'G':
2520 case 'g':
2521 if (value > ~0U >> 30)
2522 return text;
2523 value = value << 30;
2524 break;
2525 default:
2526 return text;
2527 }
2528
Godbach58048a22015-01-28 17:36:16 +08002529 if (*text != '\0' && *++text != '\0')
2530 return text;
2531
Emeric Brun39132b22010-01-04 14:57:24 +01002532 *ret = value;
2533 return NULL;
2534}
2535
Willy Tarreau126d4062013-12-03 17:50:47 +01002536/*
2537 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002538 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002539 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002540 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002541 */
2542int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2543{
2544 int len;
2545 const char *p = source;
2546 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002547 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002548
2549 len = strlen(source);
2550 if (len % 2) {
2551 memprintf(err, "an even number of hex digit is expected");
2552 return 0;
2553 }
2554
2555 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002556
Willy Tarreau126d4062013-12-03 17:50:47 +01002557 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002558 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002559 if (!*binstr) {
2560 memprintf(err, "out of memory while loading string pattern");
2561 return 0;
2562 }
2563 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002564 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002565 else {
2566 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002567 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002568 len, *binstrlen);
2569 return 0;
2570 }
2571 alloc = 0;
2572 }
2573 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002574
2575 i = j = 0;
2576 while (j < len) {
2577 if (!ishex(p[i++]))
2578 goto bad_input;
2579 if (!ishex(p[i++]))
2580 goto bad_input;
2581 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2582 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002583 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002584
2585bad_input:
2586 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002587 if (alloc)
2588 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002589 return 0;
2590}
2591
Willy Tarreau946ba592009-05-10 15:41:18 +02002592/* copies at most <n> characters from <src> and always terminates with '\0' */
2593char *my_strndup(const char *src, int n)
2594{
2595 int len = 0;
2596 char *ret;
2597
2598 while (len < n && src[len])
2599 len++;
2600
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002601 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002602 if (!ret)
2603 return ret;
2604 memcpy(ret, src, len);
2605 ret[len] = '\0';
2606 return ret;
2607}
2608
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002609/*
2610 * search needle in haystack
2611 * returns the pointer if found, returns NULL otherwise
2612 */
2613const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2614{
2615 const void *c = NULL;
2616 unsigned char f;
2617
2618 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2619 return NULL;
2620
2621 f = *(char *)needle;
2622 c = haystack;
2623 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2624 if ((haystacklen - (c - haystack)) < needlelen)
2625 return NULL;
2626
2627 if (memcmp(c, needle, needlelen) == 0)
2628 return c;
2629 ++c;
2630 }
2631 return NULL;
2632}
2633
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002634/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002635size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2636{
2637 size_t ret = 0;
2638
2639 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2640 str++;
2641 ret++;
2642 }
2643 return ret;
2644}
2645
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002646/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002647size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2648{
2649 size_t ret = 0;
2650
2651 while (ret < len) {
2652 if(memchr(reject, *((int *)str), rejectlen))
2653 return ret;
2654 str++;
2655 ret++;
2656 }
2657 return ret;
2658}
2659
Willy Tarreau482b00d2009-10-04 22:48:42 +02002660/* This function returns the first unused key greater than or equal to <key> in
2661 * ID tree <root>. Zero is returned if no place is found.
2662 */
2663unsigned int get_next_id(struct eb_root *root, unsigned int key)
2664{
2665 struct eb32_node *used;
2666
2667 do {
2668 used = eb32_lookup_ge(root, key);
2669 if (!used || used->key > key)
2670 return key; /* key is available */
2671 key++;
2672 } while (key);
2673 return key;
2674}
2675
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002676/* dump the full tree to <file> in DOT format for debugging purposes. Will
2677 * optionally highlight node <subj> if found, depending on operation <op> :
2678 * 0 : nothing
2679 * >0 : insertion, node/leaf are surrounded in red
2680 * <0 : removal, node/leaf are dashed with no background
2681 * Will optionally add "desc" as a label on the graph if set and non-null.
2682 */
2683void 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 +01002684{
2685 struct eb32sc_node *node;
2686 unsigned long scope = -1;
2687
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002688 fprintf(file, "digraph ebtree {\n");
2689
2690 if (desc && *desc) {
2691 fprintf(file,
2692 " fontname=\"fixed\";\n"
2693 " fontsize=8;\n"
2694 " label=\"%s\";\n", desc);
2695 }
2696
Willy Tarreaued3cda02017-11-15 15:04:05 +01002697 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002698 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2699 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002700 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2701 );
2702
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002703 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002704 (long)eb_root_to_node(root),
2705 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002706 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2707
2708 node = eb32sc_first(root, scope);
2709 while (node) {
2710 if (node->node.node_p) {
2711 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002712 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2713 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2714 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002715
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002716 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002717 (long)node,
2718 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002719 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002720
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002721 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002722 (long)node,
2723 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002724 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2725
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002726 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002727 (long)node,
2728 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002729 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2730 }
2731
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002732 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2733 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2734 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002735
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002736 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002737 (long)node,
2738 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002739 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002740 node = eb32sc_next(node, scope);
2741 }
2742 fprintf(file, "}\n");
2743}
2744
Willy Tarreau0dc9e6d2022-08-01 11:55:57 +02002745/* dump the full tree to <file> in DOT format for debugging purposes. Will
2746 * optionally highlight node <subj> if found, depending on operation <op> :
2747 * 0 : nothing
2748 * >0 : insertion, node/leaf are surrounded in red
2749 * <0 : removal, node/leaf are dashed with no background
2750 * Will optionally add "desc" as a label on the graph if set and non-null. The
2751 * key is printed as a u32 hex value. A full-sized hex dump would be better but
2752 * is left to be implemented.
2753 */
2754void ebmb_to_file(FILE *file, struct eb_root *root, const struct ebmb_node *subj, int op, const char *desc)
2755{
2756 struct ebmb_node *node;
2757
2758 fprintf(file, "digraph ebtree {\n");
2759
2760 if (desc && *desc) {
2761 fprintf(file,
2762 " fontname=\"fixed\";\n"
2763 " fontsize=8;\n"
2764 " label=\"%s\";\n", desc);
2765 }
2766
2767 fprintf(file,
2768 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2769 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
2770 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2771 );
2772
2773 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2774 (long)eb_root_to_node(root),
2775 (long)eb_root_to_node(eb_clrtag(root->b[0])),
2776 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2777
2778 node = ebmb_first(root);
2779 while (node) {
2780 if (node->node.node_p) {
2781 /* node part is used */
2782 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%#x\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2783 (long)node, (long)node, read_u32(node->key), node->node.bit,
2784 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2785
2786 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2787 (long)node,
2788 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
2789 eb_gettag(node->node.node_p) ? 'R' : 'L');
2790
2791 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2792 (long)node,
2793 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
2794 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2795
2796 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
2797 (long)node,
2798 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
2799 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2800 }
2801
2802 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%#x\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2803 (long)node, (long)node, read_u32(node->key), node->node.pfx,
2804 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2805
2806 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2807 (long)node,
2808 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
2809 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
2810 node = ebmb_next(node);
2811 }
2812 fprintf(file, "}\n");
2813}
2814
Willy Tarreau348238b2010-01-18 15:05:57 +01002815/* This function compares a sample word possibly followed by blanks to another
2816 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2817 * otherwise zero. This intends to be used when checking HTTP headers for some
2818 * values. Note that it validates a word followed only by blanks but does not
2819 * validate a word followed by blanks then other chars.
2820 */
2821int word_match(const char *sample, int slen, const char *word, int wlen)
2822{
2823 if (slen < wlen)
2824 return 0;
2825
2826 while (wlen) {
2827 char c = *sample ^ *word;
2828 if (c && c != ('A' ^ 'a'))
2829 return 0;
2830 sample++;
2831 word++;
2832 slen--;
2833 wlen--;
2834 }
2835
2836 while (slen) {
2837 if (*sample != ' ' && *sample != '\t')
2838 return 0;
2839 sample++;
2840 slen--;
2841 }
2842 return 1;
2843}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002844
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002845/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2846 * is particularly fast because it avoids expensive operations such as
2847 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002848 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002849 */
2850unsigned int inetaddr_host(const char *text)
2851{
2852 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2853 register unsigned int dig100, dig10, dig1;
2854 int s;
2855 const char *p, *d;
2856
2857 dig1 = dig10 = dig100 = ascii_zero;
2858 s = 24;
2859
2860 p = text;
2861 while (1) {
2862 if (((unsigned)(*p - '0')) <= 9) {
2863 p++;
2864 continue;
2865 }
2866
2867 /* here, we have a complete byte between <text> and <p> (exclusive) */
2868 if (p == text)
2869 goto end;
2870
2871 d = p - 1;
2872 dig1 |= (unsigned int)(*d << s);
2873 if (d == text)
2874 goto end;
2875
2876 d--;
2877 dig10 |= (unsigned int)(*d << s);
2878 if (d == text)
2879 goto end;
2880
2881 d--;
2882 dig100 |= (unsigned int)(*d << s);
2883 end:
2884 if (!s || *p != '.')
2885 break;
2886
2887 s -= 8;
2888 text = ++p;
2889 }
2890
2891 dig100 -= ascii_zero;
2892 dig10 -= ascii_zero;
2893 dig1 -= ascii_zero;
2894 return ((dig100 * 10) + dig10) * 10 + dig1;
2895}
2896
2897/*
2898 * Idem except the first unparsed character has to be passed in <stop>.
2899 */
2900unsigned int inetaddr_host_lim(const char *text, const char *stop)
2901{
2902 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2903 register unsigned int dig100, dig10, dig1;
2904 int s;
2905 const char *p, *d;
2906
2907 dig1 = dig10 = dig100 = ascii_zero;
2908 s = 24;
2909
2910 p = text;
2911 while (1) {
2912 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2913 p++;
2914 continue;
2915 }
2916
2917 /* here, we have a complete byte between <text> and <p> (exclusive) */
2918 if (p == text)
2919 goto end;
2920
2921 d = p - 1;
2922 dig1 |= (unsigned int)(*d << s);
2923 if (d == text)
2924 goto end;
2925
2926 d--;
2927 dig10 |= (unsigned int)(*d << s);
2928 if (d == text)
2929 goto end;
2930
2931 d--;
2932 dig100 |= (unsigned int)(*d << s);
2933 end:
2934 if (!s || p == stop || *p != '.')
2935 break;
2936
2937 s -= 8;
2938 text = ++p;
2939 }
2940
2941 dig100 -= ascii_zero;
2942 dig10 -= ascii_zero;
2943 dig1 -= ascii_zero;
2944 return ((dig100 * 10) + dig10) * 10 + dig1;
2945}
2946
2947/*
2948 * Idem except the pointer to first unparsed byte is returned into <ret> which
2949 * must not be NULL.
2950 */
Willy Tarreau74172752010-10-15 23:21:42 +02002951unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002952{
2953 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2954 register unsigned int dig100, dig10, dig1;
2955 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002956 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002957
2958 dig1 = dig10 = dig100 = ascii_zero;
2959 s = 24;
2960
2961 p = text;
2962 while (1) {
2963 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2964 p++;
2965 continue;
2966 }
2967
2968 /* here, we have a complete byte between <text> and <p> (exclusive) */
2969 if (p == text)
2970 goto end;
2971
2972 d = p - 1;
2973 dig1 |= (unsigned int)(*d << s);
2974 if (d == text)
2975 goto end;
2976
2977 d--;
2978 dig10 |= (unsigned int)(*d << s);
2979 if (d == text)
2980 goto end;
2981
2982 d--;
2983 dig100 |= (unsigned int)(*d << s);
2984 end:
2985 if (!s || p == stop || *p != '.')
2986 break;
2987
2988 s -= 8;
2989 text = ++p;
2990 }
2991
2992 *ret = p;
2993 dig100 -= ascii_zero;
2994 dig10 -= ascii_zero;
2995 dig1 -= ascii_zero;
2996 return ((dig100 * 10) + dig10) * 10 + dig1;
2997}
2998
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002999/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
3000 * or the number of chars read in case of success. Maybe this could be replaced
3001 * by one of the functions above. Also, apparently this function does not support
3002 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01003003 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02003004 */
3005int buf2ip(const char *buf, size_t len, struct in_addr *dst)
3006{
3007 const char *addr;
3008 int saw_digit, octets, ch;
3009 u_char tmp[4], *tp;
3010 const char *cp = buf;
3011
3012 saw_digit = 0;
3013 octets = 0;
3014 *(tp = tmp) = 0;
3015
3016 for (addr = buf; addr - buf < len; addr++) {
3017 unsigned char digit = (ch = *addr) - '0';
3018
3019 if (digit > 9 && ch != '.')
3020 break;
3021
3022 if (digit <= 9) {
3023 u_int new = *tp * 10 + digit;
3024
3025 if (new > 255)
3026 return 0;
3027
3028 *tp = new;
3029
3030 if (!saw_digit) {
3031 if (++octets > 4)
3032 return 0;
3033 saw_digit = 1;
3034 }
3035 } else if (ch == '.' && saw_digit) {
3036 if (octets == 4)
3037 return 0;
3038
3039 *++tp = 0;
3040 saw_digit = 0;
3041 } else
3042 return 0;
3043 }
3044
3045 if (octets < 4)
3046 return 0;
3047
3048 memcpy(&dst->s_addr, tmp, 4);
3049 return addr - cp;
3050}
3051
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003052/* This function converts the string in <buf> of the len <len> to
3053 * struct in6_addr <dst> which must be allocated by the caller.
3054 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01003055 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003056 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003057int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
3058{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003059 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01003060 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003061
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003062 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003063 return 0;
3064
3065 memcpy(null_term_ip6, buf, len);
3066 null_term_ip6[len] = '\0';
3067
Willy Tarreau075415a2013-12-12 11:29:39 +01003068 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003069 return 0;
3070
Willy Tarreau075415a2013-12-12 11:29:39 +01003071 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003072 return 1;
3073}
3074
Willy Tarreauacf95772010-06-14 19:09:21 +02003075/* To be used to quote config arg positions. Returns the short string at <ptr>
3076 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3077 * if ptr is NULL or empty. The string is locally allocated.
3078 */
3079const char *quote_arg(const char *ptr)
3080{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003081 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003082 int i;
3083
3084 if (!ptr || !*ptr)
3085 return "end of line";
3086 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003087 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003088 val[i] = *ptr++;
3089 val[i++] = '\'';
3090 val[i] = '\0';
3091 return val;
3092}
3093
Willy Tarreau5b180202010-07-18 10:40:48 +02003094/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3095int get_std_op(const char *str)
3096{
3097 int ret = -1;
3098
3099 if (*str == 'e' && str[1] == 'q')
3100 ret = STD_OP_EQ;
3101 else if (*str == 'n' && str[1] == 'e')
3102 ret = STD_OP_NE;
3103 else if (*str == 'l') {
3104 if (str[1] == 'e') ret = STD_OP_LE;
3105 else if (str[1] == 't') ret = STD_OP_LT;
3106 }
3107 else if (*str == 'g') {
3108 if (str[1] == 'e') ret = STD_OP_GE;
3109 else if (str[1] == 't') ret = STD_OP_GT;
3110 }
3111
3112 if (ret == -1 || str[2] != '\0')
3113 return -1;
3114 return ret;
3115}
3116
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003117/* hash a 32-bit integer to another 32-bit integer */
3118unsigned int full_hash(unsigned int a)
3119{
3120 return __full_hash(a);
3121}
3122
Willy Tarreauf3241112019-02-26 09:56:22 +01003123/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3124 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3125 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3126 * a popcount variant and is described here :
3127 * https://graphics.stanford.edu/~seander/bithacks.html
3128 */
3129unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3130{
3131 unsigned long a, b, c, d;
3132 unsigned int s;
3133 unsigned int t;
3134
3135 a = m - ((m >> 1) & ~0UL/3);
3136 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3137 c = (b + (b >> 4)) & ~0UL/0x11;
3138 d = (c + (c >> 8)) & ~0UL/0x101;
3139
3140 r++; // make r be 1..64
3141
3142 t = 0;
3143 s = LONGBITS;
3144 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003145 unsigned long d2 = (d >> 16) >> 16;
3146 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003147 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3148 }
3149
3150 t = (d >> (s - 16)) & 0xff;
3151 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3152 t = (c >> (s - 8)) & 0xf;
3153 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3154 t = (b >> (s - 4)) & 0x7;
3155 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3156 t = (a >> (s - 2)) & 0x3;
3157 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3158 t = (m >> (s - 1)) & 0x1;
3159 s -= ((t - r) & 256) >> 8;
3160
3161 return s - 1;
3162}
3163
3164/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3165 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3166 * using mask_prep_rank_map() below.
3167 */
3168unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3169 unsigned long a, unsigned long b,
3170 unsigned long c, unsigned long d)
3171{
3172 unsigned int s;
3173 unsigned int t;
3174
3175 r++; // make r be 1..64
3176
3177 t = 0;
3178 s = LONGBITS;
3179 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003180 unsigned long d2 = (d >> 16) >> 16;
3181 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003182 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3183 }
3184
3185 t = (d >> (s - 16)) & 0xff;
3186 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3187 t = (c >> (s - 8)) & 0xf;
3188 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3189 t = (b >> (s - 4)) & 0x7;
3190 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3191 t = (a >> (s - 2)) & 0x3;
3192 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3193 t = (m >> (s - 1)) & 0x1;
3194 s -= ((t - r) & 256) >> 8;
3195
3196 return s - 1;
3197}
3198
3199/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3200 * above.
3201 */
3202void mask_prep_rank_map(unsigned long m,
3203 unsigned long *a, unsigned long *b,
3204 unsigned long *c, unsigned long *d)
3205{
3206 *a = m - ((m >> 1) & ~0UL/3);
3207 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3208 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3209 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3210}
3211
Willy Tarreauc7a8a3c2022-06-21 20:19:54 +02003212/* Returns the position of one bit set in <v>, starting at position <bit>, and
3213 * searching in other halves if not found. This is intended to be used to
3214 * report the position of one bit set among several based on a counter or a
3215 * random generator while preserving a relatively good distribution so that
3216 * values made of holes in the middle do not see one of the bits around the
3217 * hole being returned much more often than the other one. It can be seen as a
3218 * disturbed ffsl() where the initial search starts at bit <bit>. The look up
3219 * is performed in O(logN) time for N bit words, yielding a bit among 64 in
3220 * about 16 cycles. Its usage differs from the rank find function in that the
3221 * bit passed doesn't need to be limited to the value's popcount, making the
3222 * function easier to use for random picking, and twice as fast. Passing value
3223 * 0 for <v> makes no sense and -1 is returned in this case.
3224 */
3225int one_among_mask(unsigned long v, int bit)
3226{
3227 /* note, these masks may be produced by ~0UL/((1UL<<scale)+1) but
3228 * that's more expensive.
3229 */
3230 static const unsigned long halves[] = {
3231 (unsigned long)0x5555555555555555ULL,
3232 (unsigned long)0x3333333333333333ULL,
3233 (unsigned long)0x0F0F0F0F0F0F0F0FULL,
3234 (unsigned long)0x00FF00FF00FF00FFULL,
3235 (unsigned long)0x0000FFFF0000FFFFULL,
3236 (unsigned long)0x00000000FFFFFFFFULL
3237 };
3238 unsigned long halfword = ~0UL;
3239 int scope = 0;
3240 int mirror;
3241 int scale;
3242
3243 if (!v)
3244 return -1;
3245
3246 /* we check if the exact bit is set or if it's present in a mirror
3247 * position based on the current scale we're checking, in which case
3248 * it's returned with its current (or mirrored) value. Otherwise we'll
3249 * make sure there's at least one bit in the half we're in, and will
3250 * scale down to a smaller scope and try again, until we find the
3251 * closest bit.
3252 */
3253 for (scale = (sizeof(long) > 4) ? 5 : 4; scale >= 0; scale--) {
3254 halfword >>= (1UL << scale);
3255 scope |= (1UL << scale);
3256 mirror = bit ^ (1UL << scale);
3257 if (v & ((1UL << bit) | (1UL << mirror)))
3258 return (v & (1UL << bit)) ? bit : mirror;
3259
3260 if (!((v >> (bit & scope)) & halves[scale] & halfword))
3261 bit = mirror;
3262 }
3263 return bit;
3264}
3265
David du Colombier4f92d322011-03-24 11:09:31 +01003266/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003267 * otherwise zero. Note that <addr> may not necessarily be aligned
3268 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003269 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003270int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003271{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003272 struct in_addr addr_copy;
3273
3274 memcpy(&addr_copy, addr, sizeof(addr_copy));
3275 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003276}
3277
3278/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003279 * otherwise zero. Note that <addr> may not necessarily be aligned
3280 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003281 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003282int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003283{
3284 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003285 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003286
Willy Tarreaueec1d382016-07-13 11:59:39 +02003287 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003288 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003289 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003290 (((int *)net)[i] & ((int *)mask)[i]))
3291 return 0;
3292 return 1;
3293}
3294
3295/* RFC 4291 prefix */
3296const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3297 0x00, 0x00, 0x00, 0x00,
3298 0x00, 0x00, 0xFF, 0xFF };
3299
Joseph Herlant32b83272018-11-15 11:58:28 -08003300/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003301 * Input and output may overlap.
3302 */
David du Colombier4f92d322011-03-24 11:09:31 +01003303void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3304{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003305 struct in_addr tmp_addr;
3306
3307 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003308 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003309 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003310}
3311
Joseph Herlant32b83272018-11-15 11:58:28 -08003312/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003313 * Return true if conversion is possible and false otherwise.
3314 */
3315int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3316{
3317 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3318 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3319 sizeof(struct in_addr));
3320 return 1;
3321 }
3322
3323 return 0;
3324}
3325
Amaury Denoyelle21e611d2022-12-01 17:46:45 +01003326/* compare two struct sockaddr_storage, including port if <check_port> is true,
3327 * and return:
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003328 * 0 (true) if the addr is the same in both
3329 * 1 (false) if the addr is not the same in both
3330 * -1 (unable) if one of the addr is not AF_INET*
3331 */
Amaury Denoyelle21e611d2022-12-01 17:46:45 +01003332int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2, int check_port)
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003333{
3334 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3335 return -1;
3336
3337 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3338 return -1;
3339
3340 if (ss1->ss_family != ss2->ss_family)
3341 return 1;
3342
3343 switch (ss1->ss_family) {
3344 case AF_INET:
Amaury Denoyelle21e611d2022-12-01 17:46:45 +01003345 return (memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003346 &((struct sockaddr_in *)ss2)->sin_addr,
Amaury Denoyelle21e611d2022-12-01 17:46:45 +01003347 sizeof(struct in_addr)) != 0) ||
3348 (check_port && get_net_port(ss1) != get_net_port(ss2));
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003349 case AF_INET6:
Amaury Denoyelle21e611d2022-12-01 17:46:45 +01003350 return (memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003351 &((struct sockaddr_in6 *)ss2)->sin6_addr,
Amaury Denoyelle21e611d2022-12-01 17:46:45 +01003352 sizeof(struct in6_addr)) != 0) ||
3353 (check_port && get_net_port(ss1) != get_net_port(ss2));
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003354 }
3355
3356 return 1;
3357}
3358
Christopher Faulet9553de72021-02-26 09:12:50 +01003359/* compare a struct sockaddr_storage to a struct net_addr and return :
3360 * 0 (true) if <addr> is matching <net>
3361 * 1 (false) if <addr> is not matching <net>
3362 * -1 (unable) if <addr> or <net> is not AF_INET*
3363 */
3364int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3365{
3366 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3367 return -1;
3368
3369 if ((net->family != AF_INET) && (net->family != AF_INET6))
3370 return -1;
3371
3372 if (addr->ss_family != net->family)
3373 return 1;
3374
3375 if (addr->ss_family == AF_INET &&
3376 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3377 return 0;
3378 else {
3379 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3380 const struct in6_addr *nip6 = &net->addr.v6.ip;
3381 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3382
3383 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3384 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3385 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3386 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3387 return 0;
3388 }
3389
3390 return 1;
3391}
3392
Baptiste Assmann08396c82016-01-31 00:27:17 +01003393/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003394 * The caller must allocate and clear <dest> before calling.
3395 * The source must be in either AF_INET or AF_INET6 family, or the destination
3396 * address will be undefined. If the destination address used to hold a port,
3397 * it is preserved, so that this function can be used to switch to another
3398 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003399 */
3400struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3401{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003402 int prev_port;
3403
3404 prev_port = get_net_port(dest);
3405 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003406 dest->ss_family = source->ss_family;
3407
3408 /* copy new addr and apply it */
3409 switch (source->ss_family) {
3410 case AF_INET:
3411 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003412 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003413 break;
3414 case AF_INET6:
3415 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 +01003416 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003417 break;
3418 }
3419
3420 return dest;
3421}
3422
William Lallemand421f5b52012-02-06 18:15:57 +01003423char *human_time(int t, short hz_div) {
3424 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3425 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003426 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003427 int cnt=2; // print two numbers
3428
3429 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003430 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003431 return rv;
3432 }
3433
3434 if (unlikely(hz_div > 1))
3435 t /= hz_div;
3436
3437 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003438 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003439 cnt--;
3440 }
3441
3442 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003443 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003444 cnt--;
3445 }
3446
3447 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003448 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003449 cnt--;
3450 }
3451
3452 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003453 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003454
3455 return rv;
3456}
3457
3458const char *monthname[12] = {
3459 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3460 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3461};
3462
3463/* date2str_log: write a date in the format :
3464 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3465 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3466 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3467 *
3468 * without using sprintf. return a pointer to the last char written (\0) or
3469 * NULL if there isn't enough space.
3470 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003471char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003472{
3473
3474 if (size < 25) /* the size is fixed: 24 chars + \0 */
3475 return NULL;
3476
3477 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003478 if (!dst)
3479 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003480 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003481
William Lallemand421f5b52012-02-06 18:15:57 +01003482 memcpy(dst, monthname[tm->tm_mon], 3); // month
3483 dst += 3;
3484 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003485
William Lallemand421f5b52012-02-06 18:15:57 +01003486 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003487 if (!dst)
3488 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003489 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003490
William Lallemand421f5b52012-02-06 18:15:57 +01003491 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003492 if (!dst)
3493 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003494 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003495
William Lallemand421f5b52012-02-06 18:15:57 +01003496 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003497 if (!dst)
3498 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003499 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003500
William Lallemand421f5b52012-02-06 18:15:57 +01003501 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003502 if (!dst)
3503 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003504 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003505
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003506 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003507 if (!dst)
3508 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003509 *dst = '\0';
3510
3511 return dst;
3512}
3513
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003514/* Base year used to compute leap years */
3515#define TM_YEAR_BASE 1900
3516
3517/* Return the difference in seconds between two times (leap seconds are ignored).
3518 * Retrieved from glibc 2.18 source code.
3519 */
3520static int my_tm_diff(const struct tm *a, const struct tm *b)
3521{
3522 /* Compute intervening leap days correctly even if year is negative.
3523 * Take care to avoid int overflow in leap day calculations,
3524 * but it's OK to assume that A and B are close to each other.
3525 */
3526 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3527 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3528 int a100 = a4 / 25 - (a4 % 25 < 0);
3529 int b100 = b4 / 25 - (b4 % 25 < 0);
3530 int a400 = a100 >> 2;
3531 int b400 = b100 >> 2;
3532 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3533 int years = a->tm_year - b->tm_year;
3534 int days = (365 * years + intervening_leap_days
3535 + (a->tm_yday - b->tm_yday));
3536 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3537 + (a->tm_min - b->tm_min))
3538 + (a->tm_sec - b->tm_sec));
3539}
3540
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003541/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003542 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003543 * The string returned has the same format as returned by strftime(... "%z", tm).
3544 * Offsets are kept in an internal cache for better performances.
3545 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003546const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003547{
3548 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003549 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003550
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003551 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003552 struct tm tm_gmt;
3553 int diff;
3554 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003555
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003556 /* Pretend DST not active if its status is unknown */
3557 if (isdst < 0)
3558 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003559
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003560 /* Fetch the offset and initialize it if needed */
3561 gmt_offset = gmt_offsets[isdst & 0x01];
3562 if (unlikely(!*gmt_offset)) {
3563 get_gmtime(t, &tm_gmt);
3564 diff = my_tm_diff(tm, &tm_gmt);
3565 if (diff < 0) {
3566 diff = -diff;
3567 *gmt_offset = '-';
3568 } else {
3569 *gmt_offset = '+';
3570 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003571 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003572 diff /= 60; /* Convert to minutes */
3573 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3574 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003575
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003576 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003577}
3578
William Lallemand421f5b52012-02-06 18:15:57 +01003579/* gmt2str_log: write a date in the format :
3580 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3581 * return a pointer to the last char written (\0) or
3582 * NULL if there isn't enough space.
3583 */
3584char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3585{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003586 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003587 return NULL;
3588
3589 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003590 if (!dst)
3591 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003592 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003593
William Lallemand421f5b52012-02-06 18:15:57 +01003594 memcpy(dst, monthname[tm->tm_mon], 3); // month
3595 dst += 3;
3596 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003597
William Lallemand421f5b52012-02-06 18:15:57 +01003598 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003599 if (!dst)
3600 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003601 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003602
William Lallemand421f5b52012-02-06 18:15:57 +01003603 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003604 if (!dst)
3605 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003606 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003607
William Lallemand421f5b52012-02-06 18:15:57 +01003608 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003609 if (!dst)
3610 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003611 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003612
William Lallemand421f5b52012-02-06 18:15:57 +01003613 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003614 if (!dst)
3615 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003616 *dst++ = ' ';
3617 *dst++ = '+';
3618 *dst++ = '0';
3619 *dst++ = '0';
3620 *dst++ = '0';
3621 *dst++ = '0';
3622 *dst = '\0';
3623
3624 return dst;
3625}
3626
Yuxans Yao4e25b012012-10-19 10:36:09 +08003627/* localdate2str_log: write a date in the format :
3628 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003629 * Both t and tm must represent the same time.
3630 * return a pointer to the last char written (\0) or
3631 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003632 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003633char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003634{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003635 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003636 if (size < 27) /* the size is fixed: 26 chars + \0 */
3637 return NULL;
3638
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003639 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003640
Yuxans Yao4e25b012012-10-19 10:36:09 +08003641 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003642 if (!dst)
3643 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003644 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003645
Yuxans Yao4e25b012012-10-19 10:36:09 +08003646 memcpy(dst, monthname[tm->tm_mon], 3); // month
3647 dst += 3;
3648 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003649
Yuxans Yao4e25b012012-10-19 10:36:09 +08003650 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003651 if (!dst)
3652 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003653 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003654
Yuxans Yao4e25b012012-10-19 10:36:09 +08003655 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003656 if (!dst)
3657 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003658 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003659
Yuxans Yao4e25b012012-10-19 10:36:09 +08003660 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003661 if (!dst)
3662 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003663 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003664
Yuxans Yao4e25b012012-10-19 10:36:09 +08003665 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003666 if (!dst)
3667 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003668 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003669
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003670 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003671 dst += 5;
3672 *dst = '\0';
3673
3674 return dst;
3675}
3676
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003677/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3678 * It is meant as a portable replacement for timegm() for use with valid inputs.
3679 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3680 */
3681time_t my_timegm(const struct tm *tm)
3682{
3683 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3684 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3685 * sum of the extra N days for elapsed months. The sum of all these N
3686 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3687 * in a 5-bit word. This means that with 60 bits we can represent a
3688 * matrix of all these values at once, which is fast and efficient to
3689 * access. The extra February day for leap years is not counted here.
3690 *
3691 * Jan : none = 0 (0)
3692 * Feb : Jan = 3 (3)
3693 * Mar : Jan..Feb = 3 (3 + 0)
3694 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3695 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3696 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3697 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3698 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3699 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3700 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3701 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3702 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3703 */
3704 uint64_t extra =
3705 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3706 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3707 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3708 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3709
3710 unsigned int y = tm->tm_year + 1900;
3711 unsigned int m = tm->tm_mon;
3712 unsigned long days = 0;
3713
3714 /* days since 1/1/1970 for full years */
3715 days += days_since_zero(y) - days_since_zero(1970);
3716
3717 /* days for full months in the current year */
3718 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3719
3720 /* count + 1 after March for leap years. A leap year is a year multiple
3721 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3722 * is leap, 1900 isn't, 1904 is.
3723 */
3724 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3725 days++;
3726
3727 days += tm->tm_mday - 1;
3728 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3729}
3730
Thierry Fournier93127942016-01-20 18:49:45 +01003731/* This function check a char. It returns true and updates
3732 * <date> and <len> pointer to the new position if the
3733 * character is found.
3734 */
3735static inline int parse_expect_char(const char **date, int *len, char c)
3736{
3737 if (*len < 1 || **date != c)
3738 return 0;
3739 (*len)--;
3740 (*date)++;
3741 return 1;
3742}
3743
3744/* This function expects a string <str> of len <l>. It return true and updates.
3745 * <date> and <len> if the string matches, otherwise, it returns false.
3746 */
3747static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3748{
3749 if (*len < l || strncmp(*date, str, l) != 0)
3750 return 0;
3751 (*len) -= l;
3752 (*date) += l;
3753 return 1;
3754}
3755
3756/* This macro converts 3 chars name in integer. */
3757#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3758
3759/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3760 * / %x54.75.65 ; "Tue", case-sensitive
3761 * / %x57.65.64 ; "Wed", case-sensitive
3762 * / %x54.68.75 ; "Thu", case-sensitive
3763 * / %x46.72.69 ; "Fri", case-sensitive
3764 * / %x53.61.74 ; "Sat", case-sensitive
3765 * / %x53.75.6E ; "Sun", case-sensitive
3766 *
3767 * This array must be alphabetically sorted
3768 */
3769static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3770{
3771 if (*len < 3)
3772 return 0;
3773 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3774 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3775 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3776 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3777 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3778 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3779 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3780 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3781 default: return 0;
3782 }
3783 *len -= 3;
3784 *date += 3;
3785 return 1;
3786}
3787
3788/* month = %x4A.61.6E ; "Jan", case-sensitive
3789 * / %x46.65.62 ; "Feb", case-sensitive
3790 * / %x4D.61.72 ; "Mar", case-sensitive
3791 * / %x41.70.72 ; "Apr", case-sensitive
3792 * / %x4D.61.79 ; "May", case-sensitive
3793 * / %x4A.75.6E ; "Jun", case-sensitive
3794 * / %x4A.75.6C ; "Jul", case-sensitive
3795 * / %x41.75.67 ; "Aug", case-sensitive
3796 * / %x53.65.70 ; "Sep", case-sensitive
3797 * / %x4F.63.74 ; "Oct", case-sensitive
3798 * / %x4E.6F.76 ; "Nov", case-sensitive
3799 * / %x44.65.63 ; "Dec", case-sensitive
3800 *
3801 * This array must be alphabetically sorted
3802 */
3803static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3804{
3805 if (*len < 3)
3806 return 0;
3807 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3808 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3809 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3810 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3811 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3812 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3813 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3814 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3815 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3816 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3817 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3818 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3819 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3820 default: return 0;
3821 }
3822 *len -= 3;
3823 *date += 3;
3824 return 1;
3825}
3826
3827/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3828 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3829 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3830 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3831 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3832 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3833 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3834 *
3835 * This array must be alphabetically sorted
3836 */
3837static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3838{
3839 if (*len < 6) /* Minimum length. */
3840 return 0;
3841 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3842 case STR2I3('M','o','n'):
3843 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3844 tm->tm_wday = 1;
3845 return 1;
3846 case STR2I3('T','u','e'):
3847 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3848 tm->tm_wday = 2;
3849 return 1;
3850 case STR2I3('W','e','d'):
3851 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3852 tm->tm_wday = 3;
3853 return 1;
3854 case STR2I3('T','h','u'):
3855 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3856 tm->tm_wday = 4;
3857 return 1;
3858 case STR2I3('F','r','i'):
3859 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3860 tm->tm_wday = 5;
3861 return 1;
3862 case STR2I3('S','a','t'):
3863 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3864 tm->tm_wday = 6;
3865 return 1;
3866 case STR2I3('S','u','n'):
3867 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3868 tm->tm_wday = 7;
3869 return 1;
3870 }
3871 return 0;
3872}
3873
3874/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3875static inline int parse_digit(const char **date, int *len, int *digit)
3876{
3877 if (*len < 1 || **date < '0' || **date > '9')
3878 return 0;
3879 *digit = (**date - '0');
3880 (*date)++;
3881 (*len)--;
3882 return 1;
3883}
3884
3885/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3886static inline int parse_2digit(const char **date, int *len, int *digit)
3887{
3888 int value;
3889
3890 RET0_UNLESS(parse_digit(date, len, &value));
3891 (*digit) = value * 10;
3892 RET0_UNLESS(parse_digit(date, len, &value));
3893 (*digit) += value;
3894
3895 return 1;
3896}
3897
3898/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3899static inline int parse_4digit(const char **date, int *len, int *digit)
3900{
3901 int value;
3902
3903 RET0_UNLESS(parse_digit(date, len, &value));
3904 (*digit) = value * 1000;
3905
3906 RET0_UNLESS(parse_digit(date, len, &value));
3907 (*digit) += value * 100;
3908
3909 RET0_UNLESS(parse_digit(date, len, &value));
3910 (*digit) += value * 10;
3911
3912 RET0_UNLESS(parse_digit(date, len, &value));
3913 (*digit) += value;
3914
3915 return 1;
3916}
3917
3918/* time-of-day = hour ":" minute ":" second
3919 * ; 00:00:00 - 23:59:60 (leap second)
3920 *
3921 * hour = 2DIGIT
3922 * minute = 2DIGIT
3923 * second = 2DIGIT
3924 */
3925static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3926{
3927 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3928 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3929 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3930 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3931 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3932 return 1;
3933}
3934
3935/* From RFC7231
3936 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3937 *
3938 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3939 * ; fixed length/zone/capitalization subset of the format
3940 * ; see Section 3.3 of [RFC5322]
3941 *
3942 *
3943 * date1 = day SP month SP year
3944 * ; e.g., 02 Jun 1982
3945 *
3946 * day = 2DIGIT
3947 * year = 4DIGIT
3948 *
3949 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3950 *
3951 * time-of-day = hour ":" minute ":" second
3952 * ; 00:00:00 - 23:59:60 (leap second)
3953 *
3954 * hour = 2DIGIT
3955 * minute = 2DIGIT
3956 * second = 2DIGIT
3957 *
3958 * DIGIT = decimal 0-9
3959 */
3960int parse_imf_date(const char *date, int len, struct tm *tm)
3961{
David Carlier327298c2016-11-20 10:42:38 +00003962 /* tm_gmtoff, if present, ought to be zero'ed */
3963 memset(tm, 0, sizeof(*tm));
3964
Thierry Fournier93127942016-01-20 18:49:45 +01003965 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3966 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3967 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3968 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3969 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3970 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3971 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3972 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3973 tm->tm_year -= 1900;
3974 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3975 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3976 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3977 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3978 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003979 return 1;
3980}
3981
3982/* From RFC7231
3983 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3984 *
3985 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3986 * date2 = day "-" month "-" 2DIGIT
3987 * ; e.g., 02-Jun-82
3988 *
3989 * day = 2DIGIT
3990 */
3991int parse_rfc850_date(const char *date, int len, struct tm *tm)
3992{
3993 int year;
3994
David Carlier327298c2016-11-20 10:42:38 +00003995 /* tm_gmtoff, if present, ought to be zero'ed */
3996 memset(tm, 0, sizeof(*tm));
3997
Thierry Fournier93127942016-01-20 18:49:45 +01003998 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3999 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
4000 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4001 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
4002 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
4003 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
4004 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
4005
4006 /* year = 2DIGIT
4007 *
4008 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
4009 * two-digit year, MUST interpret a timestamp that appears to be more
4010 * than 50 years in the future as representing the most recent year in
4011 * the past that had the same last two digits.
4012 */
4013 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
4014
4015 /* expect SP */
4016 if (!parse_expect_char(&date, &len, ' ')) {
4017 /* Maybe we have the date with 4 digits. */
4018 RET0_UNLESS(parse_2digit(&date, &len, &year));
4019 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
4020 /* expect SP */
4021 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
4022 } else {
4023 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
4024 * tm_year is the number of year since 1900, so for +1900, we
4025 * do nothing, and for +2000, we add 100.
4026 */
4027 if (tm->tm_year <= 60)
4028 tm->tm_year += 100;
4029 }
4030
4031 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4032 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4033 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
4034 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004035
4036 return 1;
4037}
4038
4039/* From RFC7231
4040 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4041 *
4042 * asctime-date = day-name SP date3 SP time-of-day SP year
4043 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
4044 * ; e.g., Jun 2
4045 *
4046 * HTTP-date is case sensitive. A sender MUST NOT generate additional
4047 * whitespace in an HTTP-date beyond that specifically included as SP in
4048 * the grammar.
4049 */
4050int parse_asctime_date(const char *date, int len, struct tm *tm)
4051{
David Carlier327298c2016-11-20 10:42:38 +00004052 /* tm_gmtoff, if present, ought to be zero'ed */
4053 memset(tm, 0, sizeof(*tm));
4054
Thierry Fournier93127942016-01-20 18:49:45 +01004055 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
4056 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4057 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
4058 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4059
4060 /* expect SP and 1DIGIT or 2DIGIT */
4061 if (parse_expect_char(&date, &len, ' '))
4062 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
4063 else
4064 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
4065
4066 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4067 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4068 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4069 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
4070 tm->tm_year -= 1900;
4071 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004072 return 1;
4073}
4074
4075/* From RFC7231
4076 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4077 *
4078 * HTTP-date = IMF-fixdate / obs-date
4079 * obs-date = rfc850-date / asctime-date
4080 *
4081 * parses an HTTP date in the RFC format and is accepted
4082 * alternatives. <date> is the strinf containing the date,
4083 * len is the len of the string. <tm> is filled with the
4084 * parsed time. We must considers this time as GMT.
4085 */
4086int parse_http_date(const char *date, int len, struct tm *tm)
4087{
4088 if (parse_imf_date(date, len, tm))
4089 return 1;
4090
4091 if (parse_rfc850_date(date, len, tm))
4092 return 1;
4093
4094 if (parse_asctime_date(date, len, tm))
4095 return 1;
4096
4097 return 0;
4098}
4099
Willy Tarreau4deeb102021-01-29 10:47:52 +01004100/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
4101 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
4102 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
4103 * surrounded by <pfx> and <sfx> respectively if not NULL.
4104 */
4105int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
4106{
4107 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
4108 const char *unit;
4109
4110 if (!pfx)
4111 pfx = "";
4112 if (!sfx)
4113 sfx = "";
4114
4115 do {
4116 unit = " - "; if (val <= 0.0) break;
4117 unit = "ns"; if (val < 1000.0) break;
4118 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
4119 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
4120 unit = "s "; val /= 1000.0; if (val < 60.0) break;
4121 unit = "m "; val /= 60.0; if (val < 60.0) break;
4122 unit = "h "; val /= 60.0; if (val < 24.0) break;
4123 unit = "d "; val /= 24.0; if (val < 365.0) break;
4124 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
4125 unit = " inf "; val = 0.0; break;
4126 } while (0);
4127
4128 if (val <= 0.0)
4129 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4130 else if (val < 10.0)
4131 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4132 else if (val < 100.0)
4133 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4134 else
4135 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4136}
4137
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004138/* Dynamically allocates a string of the proper length to hold the formatted
4139 * output. NULL is returned on error. The caller is responsible for freeing the
4140 * memory area using free(). The resulting string is returned in <out> if the
4141 * pointer is not NULL. A previous version of <out> might be used to build the
4142 * new string, and it will be freed before returning if it is not NULL, which
4143 * makes it possible to build complex strings from iterative calls without
4144 * having to care about freeing intermediate values, as in the example below :
4145 *
4146 * memprintf(&err, "invalid argument: '%s'", arg);
4147 * ...
4148 * memprintf(&err, "parser said : <%s>\n", *err);
4149 * ...
4150 * free(*err);
4151 *
4152 * This means that <err> must be initialized to NULL before first invocation.
4153 * The return value also holds the allocated string, which eases error checking
4154 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004155 * passed instead and it will be ignored. The returned message will then also
4156 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004157 *
4158 * It is also convenient to use it without any free except the last one :
4159 * err = NULL;
4160 * if (!fct1(err)) report(*err);
4161 * if (!fct2(err)) report(*err);
4162 * if (!fct3(err)) report(*err);
4163 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004164 *
4165 * memprintf relies on memvprintf. This last version can be called from any
4166 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004167 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004168char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004169{
4170 va_list args;
4171 char *ret = NULL;
4172 int allocated = 0;
4173 int needed = 0;
4174
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004175 if (!out)
4176 return NULL;
4177
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004178 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004179 char buf1;
4180
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004181 /* vsnprintf() will return the required length even when the
4182 * target buffer is NULL. We do this in a loop just in case
4183 * intermediate evaluations get wrong.
4184 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004185 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004186 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004187 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004188 if (needed < allocated) {
4189 /* Note: on Solaris 8, the first iteration always
4190 * returns -1 if allocated is zero, so we force a
4191 * retry.
4192 */
4193 if (!allocated)
4194 needed = 0;
4195 else
4196 break;
4197 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004198
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004199 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004200 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004201 } while (ret);
4202
4203 if (needed < 0) {
4204 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004205 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004206 }
4207
4208 if (out) {
4209 free(*out);
4210 *out = ret;
4211 }
4212
4213 return ret;
4214}
William Lallemand421f5b52012-02-06 18:15:57 +01004215
Christopher Faulet93a518f2017-10-24 11:25:33 +02004216char *memprintf(char **out, const char *format, ...)
4217{
4218 va_list args;
4219 char *ret = NULL;
4220
4221 va_start(args, format);
4222 ret = memvprintf(out, format, args);
4223 va_end(args);
4224
4225 return ret;
4226}
4227
Willy Tarreau21c705b2012-09-14 11:40:36 +02004228/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4229 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004230 * freed by the caller. It also supports being passed a NULL which results in the same
4231 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004232 * Example of use :
4233 * parse(cmd, &err); (callee: memprintf(&err, ...))
4234 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4235 * free(err);
4236 */
4237char *indent_msg(char **out, int level)
4238{
4239 char *ret, *in, *p;
4240 int needed = 0;
4241 int lf = 0;
4242 int lastlf = 0;
4243 int len;
4244
Willy Tarreau70eec382012-10-10 08:56:47 +02004245 if (!out || !*out)
4246 return NULL;
4247
Willy Tarreau21c705b2012-09-14 11:40:36 +02004248 in = *out - 1;
4249 while ((in = strchr(in + 1, '\n')) != NULL) {
4250 lastlf = in - *out;
4251 lf++;
4252 }
4253
4254 if (!lf) /* single line, no LF, return it as-is */
4255 return *out;
4256
4257 len = strlen(*out);
4258
4259 if (lf == 1 && lastlf == len - 1) {
4260 /* single line, LF at end, strip it and return as-is */
4261 (*out)[lastlf] = 0;
4262 return *out;
4263 }
4264
4265 /* OK now we have at least one LF, we need to process the whole string
4266 * as a multi-line string. What we'll do :
4267 * - prefix with an LF if there is none
4268 * - add <level> spaces before each line
4269 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4270 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4271 */
4272
4273 needed = 1 + level * (lf + 1) + len + 1;
4274 p = ret = malloc(needed);
4275 in = *out;
4276
4277 /* skip initial LFs */
4278 while (*in == '\n')
4279 in++;
4280
4281 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4282 while (*in) {
4283 *p++ = '\n';
4284 memset(p, ' ', level);
4285 p += level;
4286 do {
4287 *p++ = *in++;
4288 } while (*in && *in != '\n');
4289 if (*in)
4290 in++;
4291 }
4292 *p = 0;
4293
4294 free(*out);
4295 *out = ret;
4296
4297 return ret;
4298}
4299
Willy Tarreaua2c99112019-08-21 13:17:37 +02004300/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4301 * and end of lines replaced with <eol> if not 0. The first line to indent has
4302 * to be indicated in <first> (starts at zero), so that it is possible to skip
4303 * indenting the first line if it has to be appended after an existing message.
4304 * Empty strings are never indented, and NULL strings are considered empty both
4305 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4306 * character, non-zero otherwise.
4307 */
4308int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4309{
4310 int bol, lf;
4311 int pfxlen = pfx ? strlen(pfx) : 0;
4312
4313 if (!in)
4314 return 0;
4315
4316 bol = 1;
4317 lf = 0;
4318 while (*in) {
4319 if (bol && pfxlen) {
4320 if (first > 0)
4321 first--;
4322 else
4323 b_putblk(out, pfx, pfxlen);
4324 bol = 0;
4325 }
4326
4327 lf = (*in == '\n');
4328 bol |= lf;
4329 b_putchr(out, (lf && eol) ? eol : *in);
4330 in++;
4331 }
4332 return lf;
4333}
4334
Willy Tarreau9d22e562019-03-29 18:49:09 +01004335/* removes environment variable <name> from the environment as found in
4336 * environ. This is only provided as an alternative for systems without
4337 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004338 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004339 * <name> and to replace the matching pointers with the last pointer of
4340 * the array (since variables are not ordered).
4341 * It always returns 0 (success).
4342 */
4343int my_unsetenv(const char *name)
4344{
4345 extern char **environ;
4346 char **p = environ;
4347 int vars;
4348 int next;
4349 int len;
4350
4351 len = strlen(name);
4352 for (vars = 0; p[vars]; vars++)
4353 ;
4354 next = 0;
4355 while (next < vars) {
4356 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4357 next++;
4358 continue;
4359 }
4360 if (next < vars - 1)
4361 p[next] = p[vars - 1];
4362 p[--vars] = NULL;
4363 }
4364 return 0;
4365}
4366
Willy Tarreaudad36a32013-03-11 01:20:04 +01004367/* Convert occurrences of environment variables in the input string to their
4368 * corresponding value. A variable is identified as a series of alphanumeric
4369 * characters or underscores following a '$' sign. The <in> string must be
4370 * free()able. NULL returns NULL. The resulting string might be reallocated if
4371 * some expansion is made. Variable names may also be enclosed into braces if
4372 * needed (eg: to concatenate alphanum characters).
4373 */
4374char *env_expand(char *in)
4375{
4376 char *txt_beg;
4377 char *out;
4378 char *txt_end;
4379 char *var_beg;
4380 char *var_end;
4381 char *value;
4382 char *next;
4383 int out_len;
4384 int val_len;
4385
4386 if (!in)
4387 return in;
4388
4389 value = out = NULL;
4390 out_len = 0;
4391
4392 txt_beg = in;
4393 do {
4394 /* look for next '$' sign in <in> */
4395 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4396
4397 if (!*txt_end && !out) /* end and no expansion performed */
4398 return in;
4399
4400 val_len = 0;
4401 next = txt_end;
4402 if (*txt_end == '$') {
4403 char save;
4404
4405 var_beg = txt_end + 1;
4406 if (*var_beg == '{')
4407 var_beg++;
4408
4409 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004410 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004411 var_end++;
4412 }
4413
4414 next = var_end;
4415 if (*var_end == '}' && (var_beg > txt_end + 1))
4416 next++;
4417
4418 /* get value of the variable name at this location */
4419 save = *var_end;
4420 *var_end = '\0';
4421 value = getenv(var_beg);
4422 *var_end = save;
4423 val_len = value ? strlen(value) : 0;
4424 }
4425
Hubert Verstraete831962e2016-06-28 22:44:26 +02004426 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004427 if (txt_end > txt_beg) {
4428 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4429 out_len += txt_end - txt_beg;
4430 }
4431 if (val_len) {
4432 memcpy(out + out_len, value, val_len);
4433 out_len += val_len;
4434 }
4435 out[out_len] = 0;
4436 txt_beg = next;
4437 } while (*txt_beg);
4438
4439 /* here we know that <out> was allocated and that we don't need <in> anymore */
4440 free(in);
4441 return out;
4442}
4443
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004444
4445/* same as strstr() but case-insensitive and with limit length */
4446const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4447{
4448 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004449 unsigned int slen, plen;
4450 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004451
4452 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4453 return NULL;
4454
4455 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4456 return str1;
4457
4458 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4459 return NULL;
4460
4461 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 +02004462 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004463 start++;
4464 slen--;
4465 tmp1++;
4466
4467 if (tmp1 >= len_str1)
4468 return NULL;
4469
4470 /* if pattern longer than string */
4471 if (slen < plen)
4472 return NULL;
4473 }
4474
4475 sptr = start;
4476 pptr = (char *)str2;
4477
4478 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004479 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004480 sptr++;
4481 pptr++;
4482 tmp2++;
4483
4484 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4485 return start;
4486 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4487 return NULL;
4488 }
4489 }
4490 return NULL;
4491}
4492
Willy Tarreau3ff476e2022-03-30 10:02:56 +02004493/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and
4494 * in this case only non-null strings are compared. This allows to pass initial
4495 * values in iterators and in sort functions.
4496 */
4497int strordered(const char *s1, const char *s2, const char *s3)
4498{
4499 return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0);
4500}
4501
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004502/* This function read the next valid utf8 char.
4503 * <s> is the byte srray to be decode, <len> is its length.
4504 * The function returns decoded char encoded like this:
4505 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4506 * are the length read. The decoded character is stored in <c>.
4507 */
4508unsigned char utf8_next(const char *s, int len, unsigned int *c)
4509{
4510 const unsigned char *p = (unsigned char *)s;
4511 int dec;
4512 unsigned char code = UTF8_CODE_OK;
4513
4514 if (len < 1)
4515 return UTF8_CODE_OK;
4516
4517 /* Check the type of UTF8 sequence
4518 *
4519 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4520 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4521 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4522 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4523 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4524 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4525 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4526 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4527 */
4528 switch (*p) {
4529 case 0x00 ... 0x7f:
4530 *c = *p;
4531 return UTF8_CODE_OK | 1;
4532
4533 case 0x80 ... 0xbf:
4534 *c = *p;
4535 return UTF8_CODE_BADSEQ | 1;
4536
4537 case 0xc0 ... 0xdf:
4538 if (len < 2) {
4539 *c = *p;
4540 return UTF8_CODE_BADSEQ | 1;
4541 }
4542 *c = *p & 0x1f;
4543 dec = 1;
4544 break;
4545
4546 case 0xe0 ... 0xef:
4547 if (len < 3) {
4548 *c = *p;
4549 return UTF8_CODE_BADSEQ | 1;
4550 }
4551 *c = *p & 0x0f;
4552 dec = 2;
4553 break;
4554
4555 case 0xf0 ... 0xf7:
4556 if (len < 4) {
4557 *c = *p;
4558 return UTF8_CODE_BADSEQ | 1;
4559 }
4560 *c = *p & 0x07;
4561 dec = 3;
4562 break;
4563
4564 case 0xf8 ... 0xfb:
4565 if (len < 5) {
4566 *c = *p;
4567 return UTF8_CODE_BADSEQ | 1;
4568 }
4569 *c = *p & 0x03;
4570 dec = 4;
4571 break;
4572
4573 case 0xfc ... 0xfd:
4574 if (len < 6) {
4575 *c = *p;
4576 return UTF8_CODE_BADSEQ | 1;
4577 }
4578 *c = *p & 0x01;
4579 dec = 5;
4580 break;
4581
4582 case 0xfe ... 0xff:
4583 default:
4584 *c = *p;
4585 return UTF8_CODE_BADSEQ | 1;
4586 }
4587
4588 p++;
4589
4590 while (dec > 0) {
4591
4592 /* need 0x10 for the 2 first bits */
4593 if ( ( *p & 0xc0 ) != 0x80 )
4594 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4595
4596 /* add data at char */
4597 *c = ( *c << 6 ) | ( *p & 0x3f );
4598
4599 dec--;
4600 p++;
4601 }
4602
4603 /* Check ovelong encoding.
4604 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4605 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4606 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4607 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004608 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004609 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4610 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4611 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4612 code |= UTF8_CODE_OVERLONG;
4613
4614 /* Check invalid UTF8 range. */
4615 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4616 (*c >= 0xfffe && *c <= 0xffff))
4617 code |= UTF8_CODE_INVRANGE;
4618
4619 return code | ((p-(unsigned char *)s)&0x0f);
4620}
4621
Maxime de Roucydc887852016-05-13 23:52:54 +02004622/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4623 * On failure : return 0 and <err> filled with an error message.
4624 * The caller is responsible for freeing the <err> and <str> copy
4625 * memory area using free()
4626 */
4627int list_append_word(struct list *li, const char *str, char **err)
4628{
4629 struct wordlist *wl;
4630
4631 wl = calloc(1, sizeof(*wl));
4632 if (!wl) {
4633 memprintf(err, "out of memory");
4634 goto fail_wl;
4635 }
4636
4637 wl->s = strdup(str);
4638 if (!wl->s) {
4639 memprintf(err, "out of memory");
4640 goto fail_wl_s;
4641 }
4642
Willy Tarreau2b718102021-04-21 07:32:39 +02004643 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004644
4645 return 1;
4646
4647fail_wl_s:
4648 free(wl->s);
4649fail_wl:
4650 free(wl);
4651 return 0;
4652}
4653
Willy Tarreau37101052019-05-20 16:48:20 +02004654/* indicates if a memory location may safely be read or not. The trick consists
4655 * in performing a harmless syscall using this location as an input and letting
4656 * the operating system report whether it's OK or not. For this we have the
4657 * stat() syscall, which will return EFAULT when the memory location supposed
4658 * to contain the file name is not readable. If it is readable it will then
4659 * either return 0 if the area contains an existing file name, or -1 with
4660 * another code. This must not be abused, and some audit systems might detect
4661 * this as abnormal activity. It's used only for unsafe dumps.
4662 */
4663int may_access(const void *ptr)
4664{
4665 struct stat buf;
4666
4667 if (stat(ptr, &buf) == 0)
4668 return 1;
4669 if (errno == EFAULT)
4670 return 0;
4671 return 1;
4672}
4673
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004674/* print a string of text buffer to <out>. The format is :
4675 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4676 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4677 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4678 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004679int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004680{
4681 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004682 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004683
Tim Duesterhus18795d42021-08-29 00:58:22 +02004684 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004685 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004686 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004687 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004688 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004689 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004690 }
4691 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004692 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004693 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004694 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004695 switch (c) {
4696 case ' ': c = ' '; break;
4697 case '\t': c = 't'; break;
4698 case '\n': c = 'n'; break;
4699 case '\r': c = 'r'; break;
4700 case '\e': c = 'e'; break;
4701 case '\\': c = '\\'; break;
4702 case '=': c = '='; break;
4703 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004704 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004705 }
4706 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004707 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004708 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004709 out->area[out->data++] = '\\';
4710 out->area[out->data++] = 'x';
4711 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4712 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004713 }
4714 ptr++;
4715 }
4716
4717 return ptr;
4718}
4719
4720/* print a buffer in hexa.
4721 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4722 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004723int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004724{
4725 unsigned char c;
4726 int ptr = 0;
4727
4728 while (ptr < bsize) {
4729 c = buf[ptr];
4730
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004731 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004732 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004733 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4734 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004735
4736 ptr++;
4737 }
4738 return ptr;
4739}
4740
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004741/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4742 * prepending each line with prefix <pfx>. The output is *not* initialized.
4743 * The output will not wrap pas the buffer's end so it is more optimal if the
4744 * caller makes sure the buffer is aligned first. A trailing zero will always
4745 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004746 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4747 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004748 */
Willy Tarreau37101052019-05-20 16:48:20 +02004749void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004750{
4751 const unsigned char *d = buf;
4752 int i, j, start;
4753
4754 d = (const unsigned char *)(((unsigned long)buf) & -16);
4755 start = ((unsigned long)buf) & 15;
4756
4757 for (i = 0; i < start + len; i += 16) {
4758 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4759
Willy Tarreau37101052019-05-20 16:48:20 +02004760 // 0: unchecked, 1: checked safe, 2: danger
4761 unsafe = !!unsafe;
4762 if (unsafe && !may_access(d + i))
4763 unsafe = 2;
4764
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004765 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004766 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004767 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004768 else if (unsafe > 1)
4769 chunk_strcat(out, "** ");
4770 else
4771 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004772
4773 if (j == 7)
4774 chunk_strcat(out, "- ");
4775 }
4776 chunk_strcat(out, " ");
4777 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004778 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004779 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004780 else if (unsafe > 1)
4781 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004782 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004783 chunk_appendf(out, "%c", d[i + j]);
4784 else
4785 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004786 }
4787 chunk_strcat(out, "\n");
4788 }
4789}
4790
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004791/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4792 * enclosed in brackets after the address itself, formatted on 14 chars
4793 * including the "0x" prefix. This is meant to be used as a prefix for code
4794 * areas. For example:
4795 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4796 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4797 * is emitted. A NULL <pfx> will be considered empty.
4798 */
4799void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4800{
4801 int ok = 0;
4802 int i;
4803
4804 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4805
4806 for (i = 0; i < n; i++) {
4807 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4808 ok = may_access(addr + i);
4809 if (ok)
4810 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4811 else
4812 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4813 }
4814}
4815
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004816/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4817 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4818 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4819 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4820 * lines are respected within the limit of 70 output chars. Lines that are
4821 * continuation of a previous truncated line begin with "+" instead of " "
4822 * after the offset. The new pointer is returned.
4823 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004824int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004825 int *line, int ptr)
4826{
4827 int end;
4828 unsigned char c;
4829
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004830 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004831 if (end > out->size)
4832 return ptr;
4833
4834 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4835
4836 while (ptr < len && ptr < bsize) {
4837 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004838 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004839 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004840 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004841 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004842 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004843 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004844 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004845 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004846 switch (c) {
4847 case '\t': c = 't'; break;
4848 case '\n': c = 'n'; break;
4849 case '\r': c = 'r'; break;
4850 case '\e': c = 'e'; break;
4851 case '\\': c = '\\'; break;
4852 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004853 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004854 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004855 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004856 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004857 out->area[out->data++] = '\\';
4858 out->area[out->data++] = 'x';
4859 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4860 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004861 }
4862 if (buf[ptr++] == '\n') {
4863 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004864 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004865 *line = ptr;
4866 return ptr;
4867 }
4868 }
4869 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004870 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004871 return ptr;
4872}
4873
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004874/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004875 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4876 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004877 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004878void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4879 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004880{
Willy Tarreau73459792017-04-11 07:58:08 +02004881 unsigned int i;
4882 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004883
4884 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4885 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004886 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004887 for (j = 0; j < 8; j++) {
4888 if (b + j >= 0 && b + j < len)
4889 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4890 else
4891 fprintf(out, " ");
4892 }
4893
4894 if (b + j >= 0 && b + j < len)
4895 fputc('-', out);
4896 else
4897 fputc(' ', out);
4898
4899 for (j = 8; j < 16; j++) {
4900 if (b + j >= 0 && b + j < len)
4901 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4902 else
4903 fprintf(out, " ");
4904 }
4905
4906 fprintf(out, " ");
4907 for (j = 0; j < 16; j++) {
4908 if (b + j >= 0 && b + j < len) {
4909 if (isprint((unsigned char)buf[b + j]))
4910 fputc((unsigned char)buf[b + j], out);
4911 else
4912 fputc('.', out);
4913 }
4914 else
4915 fputc(' ', out);
4916 }
4917 fputc('\n', out);
4918 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004919}
4920
Willy Tarreaubb869862020-04-16 10:52:41 +02004921/* Tries to report the executable path name on platforms supporting this. If
4922 * not found or not possible, returns NULL.
4923 */
4924const char *get_exec_path()
4925{
4926 const char *ret = NULL;
4927
David Carlier43a56852022-03-04 15:50:48 +00004928#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004929 long execfn = getauxval(AT_EXECFN);
4930
4931 if (execfn && execfn != ENOENT)
4932 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004933#elif defined(__FreeBSD__)
4934 Elf_Auxinfo *auxv;
4935 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4936 if (auxv->a_type == AT_EXECPATH) {
4937 ret = (const char *)auxv->a_un.a_ptr;
4938 break;
4939 }
4940 }
David Carlierbd2cced2021-08-17 08:44:25 +01004941#elif defined(__NetBSD__)
4942 AuxInfo *auxv;
4943 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4944 if (auxv->a_type == AT_SUN_EXECNAME) {
4945 ret = (const char *)auxv->a_v;
4946 break;
4947 }
4948 }
David Carlier7198c702022-05-14 17:15:49 +01004949#elif defined(__sun)
4950 ret = getexecname();
Willy Tarreaubb869862020-04-16 10:52:41 +02004951#endif
4952 return ret;
4953}
4954
Baruch Siache1651b22020-07-24 07:52:20 +03004955#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004956/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4957 * also returns the symbol size in <size>, otherwise returns 0 there.
4958 */
4959static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4960{
4961 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004962#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreauf3d5c4b2022-01-28 09:42:29 +01004963 const ElfW(Sym) *sym __attribute__((may_alias));
Willy Tarreau9133e482020-03-04 10:19:36 +01004964
4965 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4966 if (ret)
4967 *size = sym ? sym->st_size : 0;
4968#else
David Carlierae5c42f2021-12-31 08:15:29 +00004969#if defined(__sun)
4970 ret = dladdr((void *)addr, dli);
4971#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004972 ret = dladdr(addr, dli);
David Carlierae5c42f2021-12-31 08:15:29 +00004973#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004974 *size = 0;
4975#endif
4976 return ret;
4977}
Willy Tarreau64192392021-05-05 09:06:21 +02004978
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004979/* Sets build_is_static to true if we detect a static build. Some older glibcs
4980 * tend to crash inside dlsym() in static builds, but tests show that at least
4981 * dladdr() still works (and will fail to resolve anything of course). Thus we
4982 * try to determine if we're on a static build to avoid calling dlsym() in this
4983 * case.
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004984 */
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004985void check_if_static_build()
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004986{
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004987 Dl_info dli = { };
4988 size_t size = 0;
4989
4990 /* Now let's try to be smarter */
4991 if (!dladdr_and_size(&main, &dli, &size))
4992 build_is_static = 1;
4993 else
4994 build_is_static = 0;
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004995}
4996
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004997INITCALL0(STG_PREPARE, check_if_static_build);
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004998
Willy Tarreau64192392021-05-05 09:06:21 +02004999/* Tries to retrieve the address of the first occurrence symbol <name>.
5000 * Note that NULL in return is not always an error as a symbol may have that
5001 * address in special situations.
5002 */
5003void *get_sym_curr_addr(const char *name)
5004{
5005 void *ptr = NULL;
5006
5007#ifdef RTLD_DEFAULT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005008 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005009 ptr = dlsym(RTLD_DEFAULT, name);
Willy Tarreau64192392021-05-05 09:06:21 +02005010#endif
5011 return ptr;
5012}
5013
5014
5015/* Tries to retrieve the address of the next occurrence of symbol <name>
5016 * Note that NULL in return is not always an error as a symbol may have that
5017 * address in special situations.
5018 */
5019void *get_sym_next_addr(const char *name)
5020{
5021 void *ptr = NULL;
5022
5023#ifdef RTLD_NEXT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005024 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005025 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01005026#endif
Willy Tarreau64192392021-05-05 09:06:21 +02005027 return ptr;
5028}
5029
5030#else /* elf & linux & dl */
5031
5032/* no possible resolving on other platforms at the moment */
5033void *get_sym_curr_addr(const char *name)
5034{
5035 return NULL;
5036}
5037
5038void *get_sym_next_addr(const char *name)
5039{
5040 return NULL;
5041}
5042
5043#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01005044
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005045/* Tries to append to buffer <buf> some indications about the symbol at address
5046 * <addr> using the following form:
5047 * lib:+0xoffset (unresolvable address from lib's base)
5048 * main+0xoffset (unresolvable address from main (+/-))
5049 * lib:main+0xoffset (unresolvable lib address from main (+/-))
5050 * name (resolved exact exec address)
5051 * lib:name (resolved exact lib address)
5052 * name+0xoffset/0xsize (resolved address within exec symbol)
5053 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
5054 *
5055 * The file name (lib or executable) is limited to what lies between the last
5056 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
5057 * 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 +03005058 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005059 *
5060 * The symbol's base address is returned, or NULL when unresolved, in order to
5061 * allow the caller to match it against known ones.
5062 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01005063const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005064{
5065 const struct {
5066 const void *func;
5067 const char *name;
5068 } fcts[] = {
5069 { .func = process_stream, .name = "process_stream" },
5070 { .func = task_run_applet, .name = "task_run_applet" },
Willy Tarreau462b9892022-05-18 18:06:53 +02005071 { .func = sc_conn_io_cb, .name = "sc_conn_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01005072 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005073 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
5074 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01005075 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005076 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
5077 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01005078 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01005079#ifdef USE_THREAD
5080 { .func = accept_queue_process, .name = "accept_queue_process" },
5081#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005082#ifdef USE_LUA
5083 { .func = hlua_process_task, .name = "hlua_process_task" },
5084#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005085#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005086 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
5087 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
5088#endif
5089 };
5090
Baruch Siache1651b22020-07-24 07:52:20 +03005091#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005092 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01005093 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005094 const char *fname, *p;
5095#endif
5096 int i;
5097
5098 if (pfx)
5099 chunk_appendf(buf, "%s", pfx);
5100
5101 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
5102 if (addr == fcts[i].func) {
5103 chunk_appendf(buf, "%s", fcts[i].name);
5104 return addr;
5105 }
5106 }
5107
Baruch Siache1651b22020-07-24 07:52:20 +03005108#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005109 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01005110 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005111 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005112
5113 /* 1. prefix the library name if it's not the same object as the one
5114 * that contains the main function. The name is picked between last '/'
5115 * and first following '.'.
5116 */
5117 if (!dladdr(main, &dli_main))
5118 dli_main.dli_fbase = NULL;
5119
5120 if (dli_main.dli_fbase != dli.dli_fbase) {
5121 fname = dli.dli_fname;
5122 p = strrchr(fname, '/');
5123 if (p++)
5124 fname = p;
5125 p = strchr(fname, '.');
5126 if (!p)
5127 p = fname + strlen(fname);
5128
5129 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
5130 }
5131
5132 /* 2. symbol name */
5133 if (dli.dli_sname) {
5134 /* known, dump it and return symbol's address (exact or relative) */
5135 chunk_appendf(buf, "%s", dli.dli_sname);
5136 if (addr != dli.dli_saddr) {
5137 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01005138 if (size)
5139 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005140 }
5141 return dli.dli_saddr;
5142 }
5143 else if (dli_main.dli_fbase != dli.dli_fbase) {
5144 /* unresolved symbol from a known library, report relative offset */
5145 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
5146 return NULL;
5147 }
Baruch Siache1651b22020-07-24 07:52:20 +03005148#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005149 unknown:
5150 /* unresolved symbol from the main file, report relative offset to main */
5151 if ((void*)addr < (void*)main)
5152 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5153 else
5154 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5155 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005156}
5157
Willy Tarreau6ab7b212021-12-28 09:57:10 +01005158/* On systems where this is supported, let's provide a possibility to enumerate
5159 * the list of object files. The output is appended to a buffer initialized by
5160 * the caller, with one name per line. A trailing zero is always emitted if data
5161 * are written. Only real objects are dumped (executable and .so libs). The
5162 * function returns non-zero if it dumps anything. These functions do not make
5163 * use of the trash so that it is possible for the caller to call them with the
5164 * trash on input. The output format may be platform-specific but at least one
5165 * version must emit raw object file names when argument is zero.
5166 */
5167#if defined(HA_HAVE_DUMP_LIBS)
5168# if defined(HA_HAVE_DL_ITERATE_PHDR)
5169/* the private <data> we pass below is a dump context initialized like this */
5170struct dl_dump_ctx {
5171 struct buffer *buf;
5172 int with_addr;
5173};
5174
5175static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5176{
5177 struct dl_dump_ctx *ctx = data;
5178 const char *fname;
5179 size_t p1, p2, beg, end;
5180 int idx;
5181
5182 if (!info || !info->dlpi_name)
5183 goto leave;
5184
5185 if (!*info->dlpi_name)
5186 fname = get_exec_path();
5187 else if (strchr(info->dlpi_name, '/'))
5188 fname = info->dlpi_name;
5189 else
5190 /* else it's a VDSO or similar and we're not interested */
5191 goto leave;
5192
5193 if (!ctx->with_addr)
5194 goto dump_name;
5195
5196 /* virtual addresses are relative to the load address and are per
5197 * pseudo-header, so we have to scan them all to find the furthest
5198 * one from the beginning. In this case we only dump entries if
5199 * they have at least one section.
5200 */
5201 beg = ~0; end = 0;
5202 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5203 if (!info->dlpi_phdr[idx].p_memsz)
5204 continue;
5205 p1 = info->dlpi_phdr[idx].p_vaddr;
5206 if (p1 < beg)
5207 beg = p1;
5208 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5209 if (p2 > end)
5210 end = p2;
5211 }
5212
5213 if (!idx)
5214 goto leave;
5215
5216 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5217 (ullong)info->dlpi_addr + beg,
5218 (ullong)info->dlpi_addr + end,
5219 (ullong)(end - beg + 1));
5220 dump_name:
5221 chunk_appendf(ctx->buf, "%s\n", fname);
5222 leave:
5223 return 0;
5224}
5225
5226/* dumps lib names and optionally address ranges */
5227int dump_libs(struct buffer *output, int with_addr)
5228{
5229 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5230 size_t old_data = output->data;
5231
5232 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5233 return output->data != old_data;
5234}
5235# else // no DL_ITERATE_PHDR
5236# error "No dump_libs() function for this platform"
5237# endif
5238#else // no HA_HAVE_DUMP_LIBS
5239
5240/* unsupported platform: do not dump anything */
5241int dump_libs(struct buffer *output, int with_addr)
5242{
5243 return 0;
5244}
5245
5246#endif // HA_HAVE_DUMP_LIBS
5247
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005248/*
5249 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005250 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005251 *
5252 * First, initializes the value with <sz> as address to 0 and initializes the
5253 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5254 * address updating <sz> pointed value to the size of this array.
5255 *
5256 * Returns 1 if succeeded, 0 if not.
5257 */
5258int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5259{
5260 unsigned int *n;
5261 const char *s, *end;
5262
5263 s = str;
5264 *sz = 0;
5265 end = str + strlen(str);
5266 *nums = n = NULL;
5267
5268 while (1) {
5269 unsigned int r;
5270
5271 if (s >= end)
5272 break;
5273
5274 r = read_uint(&s, end);
5275 /* Expected characters after having read an uint: '\0' or '.',
5276 * if '.', must not be terminal.
5277 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005278 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5279 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005280 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005281 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005282
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005283 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005284 if (!n)
5285 return 0;
5286
5287 n[(*sz)++] = r;
5288 }
5289 *nums = n;
5290
5291 return 1;
5292}
5293
Willy Tarreau4d589e72019-08-23 19:02:26 +02005294
5295/* returns the number of bytes needed to encode <v> as a varint. An inline
5296 * version exists for use with constants (__varint_bytes()).
5297 */
5298int varint_bytes(uint64_t v)
5299{
5300 int len = 1;
5301
5302 if (v >= 240) {
5303 v = (v - 240) >> 4;
5304 while (1) {
5305 len++;
5306 if (v < 128)
5307 break;
5308 v = (v - 128) >> 7;
5309 }
5310 }
5311 return len;
5312}
5313
Willy Tarreau52bf8392020-03-08 00:42:37 +01005314
5315/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005316static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005317
5318/* This is a thread-safe implementation of xoroshiro128** described below:
5319 * http://prng.di.unimi.it/
5320 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5321 * supports fast jumps and passes all common quality tests. It is thread-safe,
5322 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5323 * local lock on other ones.
5324 */
5325uint64_t ha_random64()
5326{
Willy Tarreau1544c142020-03-12 00:31:18 +01005327 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5328 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005329
5330#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5331 static HA_SPINLOCK_T rand_lock;
5332
5333 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5334#endif
5335
5336 old[0] = ha_random_state[0];
5337 old[1] = ha_random_state[1];
5338
5339#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5340 do {
5341#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005342 new[1] = old[0] ^ old[1];
5343 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5344 new[1] = rotl64(new[1], 37); // c
5345
5346#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5347 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5348#else
5349 ha_random_state[0] = new[0];
5350 ha_random_state[1] = new[1];
5351#if defined(USE_THREAD)
5352 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5353#endif
5354#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005355 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005356}
5357
5358/* seeds the random state using up to <len> bytes from <seed>, starting with
5359 * the first non-zero byte.
5360 */
5361void ha_random_seed(const unsigned char *seed, size_t len)
5362{
5363 size_t pos;
5364
5365 /* the seed must not be all zeroes, so we pre-fill it with alternating
5366 * bits and overwrite part of them with the block starting at the first
5367 * non-zero byte from the seed.
5368 */
5369 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5370
5371 for (pos = 0; pos < len; pos++)
5372 if (seed[pos] != 0)
5373 break;
5374
5375 if (pos == len)
5376 return;
5377
5378 seed += pos;
5379 len -= pos;
5380
5381 if (len > sizeof(ha_random_state))
5382 len = sizeof(ha_random_state);
5383
5384 memcpy(ha_random_state, seed, len);
5385}
5386
5387/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5388 * and is equivalent to calling ha_random64() as many times. It is used to
5389 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5390 * different generators (i.e. different processes after a fork). The <dist>
5391 * argument is the distance to jump to and is used in a loop so it rather not
5392 * be too large if the processing time is a concern.
5393 *
5394 * BEWARE: this function is NOT thread-safe and must not be called during
5395 * concurrent accesses to ha_random64().
5396 */
5397void ha_random_jump96(uint32_t dist)
5398{
5399 while (dist--) {
5400 uint64_t s0 = 0;
5401 uint64_t s1 = 0;
5402 int b;
5403
5404 for (b = 0; b < 64; b++) {
5405 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5406 s0 ^= ha_random_state[0];
5407 s1 ^= ha_random_state[1];
5408 }
5409 ha_random64();
5410 }
5411
5412 for (b = 0; b < 64; b++) {
5413 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5414 s0 ^= ha_random_state[0];
5415 s1 ^= ha_random_state[1];
5416 }
5417 ha_random64();
5418 }
5419 ha_random_state[0] = s0;
5420 ha_random_state[1] = s1;
5421 }
5422}
5423
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005424/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5425 * bytes large.
5426 */
5427void ha_generate_uuid(struct buffer *output)
5428{
5429 uint32_t rnd[4];
5430 uint64_t last;
5431
5432 last = ha_random64();
5433 rnd[0] = last;
5434 rnd[1] = last >> 32;
5435
5436 last = ha_random64();
5437 rnd[2] = last;
5438 rnd[3] = last >> 32;
5439
5440 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5441 rnd[0],
5442 rnd[1] & 0xFFFF,
5443 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5444 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5445 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5446}
5447
5448
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005449/* only used by parse_line() below. It supports writing in place provided that
5450 * <in> is updated to the next location before calling it. In that case, the
5451 * char at <in> may be overwritten.
5452 */
5453#define EMIT_CHAR(x) \
5454 do { \
5455 char __c = (char)(x); \
5456 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5457 err |= PARSE_ERR_OVERLAP; \
5458 if (outpos >= outmax) \
5459 err |= PARSE_ERR_TOOLARGE; \
5460 if (!err) \
5461 out[outpos] = __c; \
5462 outpos++; \
5463 } while (0)
5464
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005465/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005466 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5467 * extraneous ones are not emitted but <outlen> is updated so that the caller
5468 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5469 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005470 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5471 * it is guaranteed that at least one arg will point to the zero. It is safe
5472 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005473 *
5474 * <out> may overlap with <in> provided that it never goes further, in which
5475 * case the parser will accept to perform in-place parsing and unquoting/
5476 * unescaping but only if environment variables do not lead to expansion that
5477 * causes overlapping, otherwise the input string being destroyed, the error
5478 * will not be recoverable. Note that even during out-of-place <in> will
5479 * experience temporary modifications in-place for variable resolution and must
5480 * be writable, and will also receive zeroes to delimit words when using
5481 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5482 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5483 * starting point of the first invalid character sequence or unmatched
5484 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5485 * error reporting might be difficult since zeroes will have been inserted into
5486 * the string. One solution for the caller may consist in replacing all args
5487 * delimiters with spaces in this case.
5488 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005489uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, const char **errptr)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005490{
5491 char *quote = NULL;
5492 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005493 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005494 unsigned char hex1, hex2;
5495 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005496 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005497 size_t outpos = 0;
5498 int squote = 0;
5499 int dquote = 0;
5500 int arg = 0;
5501 uint32_t err = 0;
5502
5503 *nbargs = 0;
5504 *outlen = 0;
5505
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005506 /* argsmax may be -1 here, protecting args[] from any write */
5507 if (arg < argsmax)
5508 args[arg] = out;
5509
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005510 while (1) {
5511 if (*in >= '-' && *in != '\\') {
5512 /* speedup: directly send all regular chars starting
5513 * with '-', '.', '/', alnum etc...
5514 */
5515 EMIT_CHAR(*in++);
5516 continue;
5517 }
5518 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5519 /* end of line */
5520 break;
5521 }
5522 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5523 /* comment */
5524 break;
5525 }
5526 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5527 if (dquote) {
5528 dquote = 0;
5529 quote = NULL;
5530 }
5531 else {
5532 dquote = 1;
5533 quote = in;
5534 }
5535 in++;
5536 continue;
5537 }
5538 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5539 if (squote) {
5540 squote = 0;
5541 quote = NULL;
5542 }
5543 else {
5544 squote = 1;
5545 quote = in;
5546 }
5547 in++;
5548 continue;
5549 }
5550 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5551 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5552 * C equivalent value but only when they have a special meaning and within
5553 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5554 */
5555 char tosend = *in;
5556
5557 switch (in[1]) {
5558 case ' ':
5559 case '\\':
5560 tosend = in[1];
5561 in++;
5562 break;
5563
5564 case 't':
5565 tosend = '\t';
5566 in++;
5567 break;
5568
5569 case 'n':
5570 tosend = '\n';
5571 in++;
5572 break;
5573
5574 case 'r':
5575 tosend = '\r';
5576 in++;
5577 break;
5578
5579 case '#':
5580 /* escaping of "#" only if comments are supported */
5581 if (opts & PARSE_OPT_SHARP)
5582 in++;
5583 tosend = *in;
5584 break;
5585
5586 case '\'':
5587 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5588 if (opts & PARSE_OPT_SQUOTE && !squote)
5589 in++;
5590 tosend = *in;
5591 break;
5592
5593 case '"':
5594 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5595 if (opts & PARSE_OPT_DQUOTE && !squote)
5596 in++;
5597 tosend = *in;
5598 break;
5599
5600 case '$':
5601 /* escaping of '$' only inside double quotes and only if env supported */
5602 if (opts & PARSE_OPT_ENV && dquote)
5603 in++;
5604 tosend = *in;
5605 break;
5606
5607 case 'x':
5608 if (!ishex(in[2]) || !ishex(in[3])) {
5609 /* invalid or incomplete hex sequence */
5610 err |= PARSE_ERR_HEX;
5611 if (errptr)
5612 *errptr = in;
5613 goto leave;
5614 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005615 hex1 = toupper((unsigned char)in[2]) - '0';
5616 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005617 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5618 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5619 tosend = (hex1 << 4) + hex2;
5620 in += 3;
5621 break;
5622
5623 default:
5624 /* other combinations are not escape sequences */
5625 break;
5626 }
5627
5628 in++;
5629 EMIT_CHAR(tosend);
5630 }
5631 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5632 /* a non-escaped space is an argument separator */
5633 while (isspace((unsigned char)*in))
5634 in++;
5635 EMIT_CHAR(0);
5636 arg++;
5637 if (arg < argsmax)
5638 args[arg] = out + outpos;
5639 else
5640 err |= PARSE_ERR_TOOMANY;
5641 }
5642 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5643 /* environment variables are evaluated anywhere, or only
5644 * inside double quotes if they are supported.
5645 */
5646 char *var_name;
5647 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005648 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005649
5650 in++;
5651
5652 if (*in == '{')
5653 brace = in++;
5654
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005655 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005656 /* unacceptable character in variable name */
5657 err |= PARSE_ERR_VARNAME;
5658 if (errptr)
5659 *errptr = in;
5660 goto leave;
5661 }
5662
5663 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005664 if (*in == '.')
5665 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005666 while (isalnum((unsigned char)*in) || *in == '_')
5667 in++;
5668
5669 save_char = *in;
5670 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005671 if (unlikely(*var_name == '.')) {
5672 /* internal pseudo-variables */
5673 if (strcmp(var_name, ".LINE") == 0)
5674 value = ultoa(global.cfg_curr_line);
5675 else if (strcmp(var_name, ".FILE") == 0)
5676 value = global.cfg_curr_file;
5677 else if (strcmp(var_name, ".SECTION") == 0)
5678 value = global.cfg_curr_section;
5679 else {
5680 /* unsupported internal variable name */
5681 err |= PARSE_ERR_VARNAME;
5682 if (errptr)
5683 *errptr = var_name;
5684 goto leave;
5685 }
5686 } else {
5687 value = getenv(var_name);
5688 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005689 *in = save_char;
5690
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005691 /* support for '[*]' sequence to force word expansion,
5692 * only available inside braces */
5693 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5694 word_expand = in++;
5695
5696 if (*in++ != '*' || *in++ != ']') {
5697 err |= PARSE_ERR_WRONG_EXPAND;
5698 if (errptr)
5699 *errptr = word_expand;
5700 goto leave;
5701 }
5702 }
5703
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005704 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005705 if (*in == '-') {
5706 /* default value starts just after the '-' */
5707 if (!value)
5708 value = in + 1;
5709
5710 while (*in && *in != '}')
5711 in++;
5712 if (!*in)
5713 goto no_brace;
5714 *in = 0; // terminate the default value
5715 }
5716 else if (*in != '}') {
5717 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005718 /* unmatched brace */
5719 err |= PARSE_ERR_BRACE;
5720 if (errptr)
5721 *errptr = brace;
5722 goto leave;
5723 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005724
5725 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005726 in++;
5727 brace = NULL;
5728 }
5729
5730 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005731 while (*value) {
5732 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005733 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005734 EMIT_CHAR(0);
5735 ++arg;
5736 if (arg < argsmax)
5737 args[arg] = out + outpos;
5738 else
5739 err |= PARSE_ERR_TOOMANY;
5740
5741 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005742 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005743 ;
5744 } else {
5745 EMIT_CHAR(*value++);
5746 }
5747 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005748 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005749 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005750 }
5751 else {
5752 /* any other regular char */
5753 EMIT_CHAR(*in++);
5754 }
5755 }
5756
5757 /* end of output string */
5758 EMIT_CHAR(0);
Erwan Le Goas8a6767d2022-09-23 15:06:34 +02005759
Willy Tarreau94ab1392022-10-03 08:27:55 +02005760 /* Don't add an empty arg after trailing spaces. Note that args[arg]
5761 * may contain some distances relative to NULL if <out> was NULL, or
5762 * pointers beyond the end of <out> in case <outlen> is too short, thus
5763 * we must not dereference it.
Erwan Le Goas8a6767d2022-09-23 15:06:34 +02005764 */
Willy Tarreau94ab1392022-10-03 08:27:55 +02005765 if (arg < argsmax && args[arg] != out + outpos - 1)
Erwan Le Goas8a6767d2022-09-23 15:06:34 +02005766 arg++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005767
5768 if (quote) {
5769 /* unmatched quote */
5770 err |= PARSE_ERR_QUOTE;
5771 if (errptr)
5772 *errptr = quote;
5773 goto leave;
5774 }
5775 leave:
5776 *nbargs = arg;
5777 *outlen = outpos;
5778
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005779 /* empty all trailing args by making them point to the trailing zero,
5780 * at least the last one in any case.
5781 */
5782 if (arg > argsmax)
5783 arg = argsmax;
5784
5785 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005786 args[arg++] = out + outpos - 1;
5787
5788 return err;
5789}
5790#undef EMIT_CHAR
5791
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005792/* This is used to sanitize an input line that's about to be used for error reporting.
5793 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5794 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5795 * If non-printable chars are present in the output. It returns the new offset <pos>
5796 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5797 * be at least 6 to support two "..." otherwise the result is undefined. The line
5798 * itself must have at least 7 chars allocated for the same reason.
5799 */
5800size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5801{
5802 size_t shift = 0;
5803 char *out = line;
5804 char *in = line;
5805 char *end = line + width;
5806
5807 if (pos >= width) {
5808 /* if we have to shift, we'll be out of context, so let's
5809 * try to put <pos> at the center of width.
5810 */
5811 shift = pos - width / 2;
5812 in += shift + 3;
5813 end = out + width - 3;
5814 out[0] = out[1] = out[2] = '.';
5815 out += 3;
5816 }
5817
5818 while (out < end && *in) {
5819 if (isspace((unsigned char)*in))
5820 *out++ = ' ';
5821 else if (isprint((unsigned char)*in))
5822 *out++ = *in;
5823 else
5824 *out++ = '?';
5825 in++;
5826 }
5827
5828 if (end < line + width) {
5829 out[0] = out[1] = out[2] = '.';
5830 out += 3;
5831 }
5832
5833 *out++ = 0;
5834 return pos - shift;
5835}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005836
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005837/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005838 * transitions between characters. <fp> is a 1024-entries array indexed as
5839 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005840 * 1..26=letter, 27=digit, 28=other/begin/end.
5841 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005842 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005843void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005844{
5845 const char *p;
5846 int from, to;
5847 int c;
5848
Willy Tarreauba2c4452021-03-12 09:01:52 +01005849 from = 28; // begin
5850 for (p = word; *p; p++) {
5851 c = tolower(*p);
5852 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005853 case 'a'...'z': to = c - 'a' + 1; break;
5854 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5855 case '0'...'9': to = 27; break;
5856 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005857 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005858 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005859 fp[32 * from + to]++;
5860 from = to;
5861 }
5862 to = 28; // end
5863 fp[32 * from + to]++;
5864}
5865
Erwan Le Goas9c766372022-09-14 17:40:24 +02005866/* This function hashes a word, scramble is the anonymizing key, returns
5867 * the hashed word when the key (scramble) != 0, else returns the word.
5868 * This function can be called NB_L_HASH_WORD times in a row, don't call
5869 * it if you called it more than NB_L_HASH_WORD.
5870 */
5871const char *hash_anon(uint32_t scramble, const char *string2hash, const char *prefix, const char *suffix)
5872{
5873 index_hash++;
Erwan Le Goasd2605cf2022-09-21 16:24:23 +02005874 if (index_hash == NB_L_HASH_WORD)
Erwan Le Goas9c766372022-09-14 17:40:24 +02005875 index_hash = 0;
5876
5877 /* don't hash empty strings */
5878 if (!string2hash[0] || (string2hash[0] == ' ' && string2hash[1] == 0))
5879 return string2hash;
5880
5881 if (scramble != 0) {
5882 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "%s%06x%s",
5883 prefix, HA_ANON(scramble, string2hash, strlen(string2hash)), suffix);
5884 return hash_word[index_hash];
5885 }
5886 else
5887 return string2hash;
5888}
5889
5890/* This function hashes or not an ip address ipstring, scramble is the anonymizing
5891 * key, returns the hashed ip with his port or ipstring when there is nothing to hash.
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005892 * Put hasport equal 0 to point out ipstring has no port, else put an other int.
5893 * Without port, return a simple hash or ipstring.
Erwan Le Goas9c766372022-09-14 17:40:24 +02005894 */
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005895const char *hash_ipanon(uint32_t scramble, char *ipstring, int hasport)
Erwan Le Goas9c766372022-09-14 17:40:24 +02005896{
5897 char *errmsg = NULL;
5898 struct sockaddr_storage *sa;
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005899 struct sockaddr_storage ss;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005900 char addr[46];
5901 int port;
5902
5903 index_hash++;
Erwan Le Goasd2605cf2022-09-21 16:24:23 +02005904 if (index_hash == NB_L_HASH_WORD) {
Erwan Le Goas9c766372022-09-14 17:40:24 +02005905 index_hash = 0;
5906 }
5907
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005908 if (scramble == 0) {
Erwan Le Goas9c766372022-09-14 17:40:24 +02005909 return ipstring;
5910 }
Christopher Faulet015bbc22022-09-29 11:53:07 +02005911 if (strcmp(ipstring, "localhost") == 0 ||
5912 strcmp(ipstring, "stdout") == 0 ||
5913 strcmp(ipstring, "stderr") == 0 ||
5914 strncmp(ipstring, "fd@", 3) == 0 ||
5915 strncmp(ipstring, "sockpair@", 9) == 0) {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005916 return ipstring;
5917 }
Erwan Le Goas9c766372022-09-14 17:40:24 +02005918 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005919 if (hasport == 0) {
5920 memset(&ss, 0, sizeof(ss));
5921 if (str2ip2(ipstring, &ss, 1) == NULL) {
5922 return HA_ANON_STR(scramble, ipstring);
5923 }
5924 sa = &ss;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005925 }
5926 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005927 sa = str2sa_range(ipstring, NULL, NULL, NULL, NULL, NULL, &errmsg, NULL, NULL,
Christopher Faulet7e50e4b2022-09-29 11:46:34 +02005928 PA_O_PORT_OK | PA_O_STREAM | PA_O_DGRAM | PA_O_XPRT | PA_O_CONNECT |
5929 PA_O_PORT_RANGE | PA_O_PORT_OFS | PA_O_RESOLVE);
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005930 if (sa == NULL) {
5931 return HA_ANON_STR(scramble, ipstring);
5932 }
5933 }
5934 addr_to_str(sa, addr, sizeof(addr));
5935 port = get_host_port(sa);
Erwan Le Goas9c766372022-09-14 17:40:24 +02005936
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005937 switch(sa->ss_family) {
5938 case AF_INET:
5939 if (strncmp(addr, "127", 3) == 0 || strncmp(addr, "255", 3) == 0 || strncmp(addr, "0", 1) == 0) {
5940 return ipstring;
5941 }
5942 else {
5943 if (port != 0) {
5944 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV4(%06x):%d", HA_ANON(scramble, addr, strlen(addr)), port);
5945 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005946 }
5947 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005948 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV4(%06x)", HA_ANON(scramble, addr, strlen(addr)));
5949 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005950 }
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005951 }
5952 break;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005953
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005954 case AF_INET6:
5955 if (strcmp(addr, "::1") == 0) {
5956 return ipstring;
5957 }
5958 else {
5959 if (port != 0) {
5960 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV6(%06x):%d", HA_ANON(scramble, addr, strlen(addr)), port);
5961 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005962 }
5963 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005964 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV6(%06x)", HA_ANON(scramble, addr, strlen(addr)));
5965 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005966 }
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005967 }
5968 break;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005969
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005970 case AF_UNIX:
5971 return HA_ANON_STR(scramble, ipstring);
5972 break;
5973
5974 default:
5975 return ipstring;
5976 break;
5977 };
Erwan Le Goas9c766372022-09-14 17:40:24 +02005978 }
5979 return ipstring;
5980}
5981
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005982/* Initialize array <fp> with the fingerprint of word <word> by counting the
5983 * transitions between characters. <fp> is a 1024-entries array indexed as
5984 * 32*from+to. Positions for 'from' and 'to' are:
5985 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5986 */
5987void make_word_fingerprint(uint8_t *fp, const char *word)
5988{
5989 memset(fp, 0, 1024);
5990 update_word_fingerprint(fp, word);
5991}
5992
Willy Tarreauba2c4452021-03-12 09:01:52 +01005993/* Return the distance between two word fingerprints created by function
5994 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005995 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005996 */
5997int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5998{
5999 int i, k, dist = 0;
6000
6001 for (i = 0; i < 1024; i++) {
6002 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01006003 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01006004 }
6005 return dist;
6006}
6007
William Lallemand3aeb3f92021-08-21 23:59:56 +02006008/*
6009 * This function compares the loaded openssl version with a string <version>
6010 * This function use the same return code as compare_current_version:
6011 *
6012 * -1 : the version in argument is older than the current openssl version
6013 * 0 : the version in argument is the same as the current openssl version
6014 * 1 : the version in argument is newer than the current openssl version
6015 *
6016 * Or some errors:
6017 * -2 : openssl is not available on this process
6018 * -3 : the version in argument is not parsable
6019 */
6020int openssl_compare_current_version(const char *version)
6021{
6022#ifdef USE_OPENSSL
6023 int numversion;
6024
6025 numversion = openssl_version_parser(version);
6026 if (numversion == 0)
6027 return -3;
6028
6029 if (numversion < OPENSSL_VERSION_NUMBER)
6030 return -1;
6031 else if (numversion > OPENSSL_VERSION_NUMBER)
6032 return 1;
6033 else
6034 return 0;
6035#else
6036 return -2;
6037#endif
6038}
6039
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02006040/*
6041 * This function compares the loaded openssl name with a string <name>
6042 * This function returns 0 if the OpenSSL name starts like the passed parameter,
6043 * 1 otherwise.
6044 */
6045int openssl_compare_current_name(const char *name)
6046{
6047#ifdef USE_OPENSSL
6048 int name_len = 0;
6049 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
6050
6051 if (name) {
6052 name_len = strlen(name);
6053 if (strlen(name) <= strlen(openssl_version))
6054 return strncmp(openssl_version, name, name_len);
6055 }
6056#endif
6057 return 1;
6058}
6059
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006060#if defined(RTLD_DEFAULT) || defined(RTLD_NEXT)
6061/* redefine dlopen() so that we can detect unexpected replacement of some
6062 * critical symbols, typically init/alloc/free functions coming from alternate
6063 * libraries. When called, a tainted flag is set (TAINTED_SHARED_LIBS).
6064 */
6065void *dlopen(const char *filename, int flags)
6066{
6067 static void *(*_dlopen)(const char *filename, int flags);
Willy Tarreau177aed52022-06-19 16:49:51 +02006068 struct {
6069 const char *name;
6070 void *curr, *next;
6071 } check_syms[] = {
6072 { .name = "malloc", },
6073 { .name = "free", },
6074 { .name = "SSL_library_init", },
6075 { .name = "X509_free", },
6076 /* insert only above, 0 must be the last one */
6077 { 0 },
6078 };
6079 const char *trace;
6080 void *addr;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006081 void *ret;
Willy Tarreau177aed52022-06-19 16:49:51 +02006082 int sym = 0;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006083
6084 if (!_dlopen) {
6085 _dlopen = get_sym_next_addr("dlopen");
6086 if (!_dlopen || _dlopen == dlopen) {
6087 _dlopen = NULL;
6088 return NULL;
6089 }
6090 }
6091
Willy Tarreau177aed52022-06-19 16:49:51 +02006092 /* save a few pointers to critical symbols. We keep a copy of both the
6093 * current and the next value, because we might already have replaced
6094 * some of them (e.g. malloc/free with DEBUG_MEM_STATS), and we're only
6095 * interested in verifying that a loaded library doesn't come with a
6096 * completely different definition that would be incompatible.
6097 */
6098 for (sym = 0; check_syms[sym].name; sym++) {
6099 check_syms[sym].curr = get_sym_curr_addr(check_syms[sym].name);
6100 check_syms[sym].next = get_sym_next_addr(check_syms[sym].name);
6101 }
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006102
6103 /* now open the requested lib */
6104 ret = _dlopen(filename, flags);
6105 if (!ret)
6106 return ret;
6107
6108 mark_tainted(TAINTED_SHARED_LIBS);
6109
Willy Tarreau177aed52022-06-19 16:49:51 +02006110 /* and check that critical symbols didn't change */
6111 for (sym = 0; check_syms[sym].name; sym++) {
6112 if (!check_syms[sym].curr && !check_syms[sym].next)
6113 continue;
6114
6115 addr = dlsym(ret, check_syms[sym].name);
6116 if (!addr || addr == check_syms[sym].curr || addr == check_syms[sym].next)
6117 continue;
6118
6119 /* OK it's clear that this symbol was redefined */
6120 mark_tainted(TAINTED_REDEFINITION);
6121
6122 trace = hlua_show_current_location("\n ");
6123 ha_warning("dlopen(): shared library '%s' brings a different definition of symbol '%s'. The process cannot be trusted anymore!%s%s\n",
6124 filename, check_syms[sym].name,
6125 trace ? " Suspected call location: \n " : "",
6126 trace ? trace : "");
6127 }
6128
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006129 return ret;
6130}
6131#endif
6132
Willy Tarreau06e69b52021-03-02 14:01:35 +01006133static int init_tools_per_thread()
6134{
6135 /* Let's make each thread start from a different position */
6136 statistical_prng_state += tid * MAX_THREADS;
6137 if (!statistical_prng_state)
6138 statistical_prng_state++;
6139 return 1;
6140}
6141REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02006142
Willy Tarreaubaaee002006-06-26 02:48:02 +02006143/*
6144 * Local variables:
6145 * c-indent-level: 8
6146 * c-basic-offset: 8
6147 * End:
6148 */