blob: 6e84fb217faa2e982b9de9a5e78d4a236b64303e [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010019#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020020#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020022#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020023#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <stdlib.h>
25#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010026#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020027#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010028#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020029#include <sys/stat.h>
30#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010031#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netinet/in.h>
33#include <arpa/inet.h>
34
Willy Tarreau30053062020-08-20 16:39:14 +020035#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
36#include <sys/auxv.h>
37#endif
38
Willy Tarreau48fbcae2020-06-03 18:09:46 +020039#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020040#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020041
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020042#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020043#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020044#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020045#include <haproxy/dns.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020046#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020047#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020048#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020049#include <haproxy/namespace.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020050#include <haproxy/protocol.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010051#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020052#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020053#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020054#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020055#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010056
Thierry Fournier93127942016-01-20 18:49:45 +010057/* This macro returns false if the test __x is false. Many
58 * of the following parsing function must be abort the processing
59 * if it returns 0, so this macro is useful for writing light code.
60 */
61#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
62
Willy Tarreau56adcf22012-12-23 18:00:29 +010063/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020064 * 2^64-1 = 18446744073709551615 or
65 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020066 *
67 * The HTML version needs room for adding the 25 characters
68 * '<span class="rls"></span>' around digits at positions 3N+1 in order
69 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020070 */
Christopher Faulet99bca652017-11-14 16:47:26 +010071THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
72THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020073
Willy Tarreau588297f2014-06-16 15:16:40 +020074/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
75 * to quote strings larger than a max configuration line.
76 */
Christopher Faulet99bca652017-11-14 16:47:26 +010077THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
78THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020079
Willy Tarreaubaaee002006-06-26 02:48:02 +020080/*
William Lallemande7340ec2012-01-24 11:15:39 +010081 * unsigned long long ASCII representation
82 *
83 * return the last char '\0' or NULL if no enough
84 * space in dst
85 */
86char *ulltoa(unsigned long long n, char *dst, size_t size)
87{
88 int i = 0;
89 char *res;
90
91 switch(n) {
92 case 1ULL ... 9ULL:
93 i = 0;
94 break;
95
96 case 10ULL ... 99ULL:
97 i = 1;
98 break;
99
100 case 100ULL ... 999ULL:
101 i = 2;
102 break;
103
104 case 1000ULL ... 9999ULL:
105 i = 3;
106 break;
107
108 case 10000ULL ... 99999ULL:
109 i = 4;
110 break;
111
112 case 100000ULL ... 999999ULL:
113 i = 5;
114 break;
115
116 case 1000000ULL ... 9999999ULL:
117 i = 6;
118 break;
119
120 case 10000000ULL ... 99999999ULL:
121 i = 7;
122 break;
123
124 case 100000000ULL ... 999999999ULL:
125 i = 8;
126 break;
127
128 case 1000000000ULL ... 9999999999ULL:
129 i = 9;
130 break;
131
132 case 10000000000ULL ... 99999999999ULL:
133 i = 10;
134 break;
135
136 case 100000000000ULL ... 999999999999ULL:
137 i = 11;
138 break;
139
140 case 1000000000000ULL ... 9999999999999ULL:
141 i = 12;
142 break;
143
144 case 10000000000000ULL ... 99999999999999ULL:
145 i = 13;
146 break;
147
148 case 100000000000000ULL ... 999999999999999ULL:
149 i = 14;
150 break;
151
152 case 1000000000000000ULL ... 9999999999999999ULL:
153 i = 15;
154 break;
155
156 case 10000000000000000ULL ... 99999999999999999ULL:
157 i = 16;
158 break;
159
160 case 100000000000000000ULL ... 999999999999999999ULL:
161 i = 17;
162 break;
163
164 case 1000000000000000000ULL ... 9999999999999999999ULL:
165 i = 18;
166 break;
167
168 case 10000000000000000000ULL ... ULLONG_MAX:
169 i = 19;
170 break;
171 }
172 if (i + 2 > size) // (i + 1) + '\0'
173 return NULL; // too long
174 res = dst + i + 1;
175 *res = '\0';
176 for (; i >= 0; i--) {
177 dst[i] = n % 10ULL + '0';
178 n /= 10ULL;
179 }
180 return res;
181}
182
183/*
184 * unsigned long ASCII representation
185 *
186 * return the last char '\0' or NULL if no enough
187 * space in dst
188 */
189char *ultoa_o(unsigned long n, char *dst, size_t size)
190{
191 int i = 0;
192 char *res;
193
194 switch (n) {
195 case 0U ... 9UL:
196 i = 0;
197 break;
198
199 case 10U ... 99UL:
200 i = 1;
201 break;
202
203 case 100U ... 999UL:
204 i = 2;
205 break;
206
207 case 1000U ... 9999UL:
208 i = 3;
209 break;
210
211 case 10000U ... 99999UL:
212 i = 4;
213 break;
214
215 case 100000U ... 999999UL:
216 i = 5;
217 break;
218
219 case 1000000U ... 9999999UL:
220 i = 6;
221 break;
222
223 case 10000000U ... 99999999UL:
224 i = 7;
225 break;
226
227 case 100000000U ... 999999999UL:
228 i = 8;
229 break;
230#if __WORDSIZE == 32
231
232 case 1000000000ULL ... ULONG_MAX:
233 i = 9;
234 break;
235
236#elif __WORDSIZE == 64
237
238 case 1000000000ULL ... 9999999999UL:
239 i = 9;
240 break;
241
242 case 10000000000ULL ... 99999999999UL:
243 i = 10;
244 break;
245
246 case 100000000000ULL ... 999999999999UL:
247 i = 11;
248 break;
249
250 case 1000000000000ULL ... 9999999999999UL:
251 i = 12;
252 break;
253
254 case 10000000000000ULL ... 99999999999999UL:
255 i = 13;
256 break;
257
258 case 100000000000000ULL ... 999999999999999UL:
259 i = 14;
260 break;
261
262 case 1000000000000000ULL ... 9999999999999999UL:
263 i = 15;
264 break;
265
266 case 10000000000000000ULL ... 99999999999999999UL:
267 i = 16;
268 break;
269
270 case 100000000000000000ULL ... 999999999999999999UL:
271 i = 17;
272 break;
273
274 case 1000000000000000000ULL ... 9999999999999999999UL:
275 i = 18;
276 break;
277
278 case 10000000000000000000ULL ... ULONG_MAX:
279 i = 19;
280 break;
281
282#endif
283 }
284 if (i + 2 > size) // (i + 1) + '\0'
285 return NULL; // too long
286 res = dst + i + 1;
287 *res = '\0';
288 for (; i >= 0; i--) {
289 dst[i] = n % 10U + '0';
290 n /= 10U;
291 }
292 return res;
293}
294
295/*
296 * signed long ASCII representation
297 *
298 * return the last char '\0' or NULL if no enough
299 * space in dst
300 */
301char *ltoa_o(long int n, char *dst, size_t size)
302{
303 char *pos = dst;
304
305 if (n < 0) {
306 if (size < 3)
307 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
308 *pos = '-';
309 pos++;
310 dst = ultoa_o(-n, pos, size - 1);
311 } else {
312 dst = ultoa_o(n, dst, size);
313 }
314 return dst;
315}
316
317/*
318 * signed long long ASCII representation
319 *
320 * return the last char '\0' or NULL if no enough
321 * space in dst
322 */
323char *lltoa(long long n, char *dst, size_t size)
324{
325 char *pos = dst;
326
327 if (n < 0) {
328 if (size < 3)
329 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
330 *pos = '-';
331 pos++;
332 dst = ulltoa(-n, pos, size - 1);
333 } else {
334 dst = ulltoa(n, dst, size);
335 }
336 return dst;
337}
338
339/*
340 * write a ascii representation of a unsigned into dst,
341 * return a pointer to the last character
342 * Pad the ascii representation with '0', using size.
343 */
344char *utoa_pad(unsigned int n, char *dst, size_t size)
345{
346 int i = 0;
347 char *ret;
348
349 switch(n) {
350 case 0U ... 9U:
351 i = 0;
352 break;
353
354 case 10U ... 99U:
355 i = 1;
356 break;
357
358 case 100U ... 999U:
359 i = 2;
360 break;
361
362 case 1000U ... 9999U:
363 i = 3;
364 break;
365
366 case 10000U ... 99999U:
367 i = 4;
368 break;
369
370 case 100000U ... 999999U:
371 i = 5;
372 break;
373
374 case 1000000U ... 9999999U:
375 i = 6;
376 break;
377
378 case 10000000U ... 99999999U:
379 i = 7;
380 break;
381
382 case 100000000U ... 999999999U:
383 i = 8;
384 break;
385
386 case 1000000000U ... 4294967295U:
387 i = 9;
388 break;
389 }
390 if (i + 2 > size) // (i + 1) + '\0'
391 return NULL; // too long
392 if (i < size)
393 i = size - 2; // padding - '\0'
394
395 ret = dst + i + 1;
396 *ret = '\0';
397 for (; i >= 0; i--) {
398 dst[i] = n % 10U + '0';
399 n /= 10U;
400 }
401 return ret;
402}
403
404/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200405 * copies at most <size-1> chars from <src> to <dst>. Last char is always
406 * set to 0, unless <size> is 0. The number of chars copied is returned
407 * (excluding the terminating zero).
408 * This code has been optimized for size and speed : on x86, it's 45 bytes
409 * long, uses only registers, and consumes only 4 cycles per char.
410 */
411int strlcpy2(char *dst, const char *src, int size)
412{
413 char *orig = dst;
414 if (size) {
415 while (--size && (*dst = *src)) {
416 src++; dst++;
417 }
418 *dst = 0;
419 }
420 return dst - orig;
421}
422
423/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200424 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200425 * the ascii representation for number 'n' in decimal.
426 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100427char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200428{
429 char *pos;
430
Willy Tarreau72d759c2007-10-25 12:14:10 +0200431 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200432 *pos-- = '\0';
433
434 do {
435 *pos-- = '0' + n % 10;
436 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200437 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200438 return pos + 1;
439}
440
Willy Tarreau91092e52007-10-25 16:58:42 +0200441/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200442 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200443 * the ascii representation for number 'n' in decimal.
444 */
445char *lltoa_r(long long int in, char *buffer, int size)
446{
447 char *pos;
448 int neg = 0;
449 unsigned long long int n;
450
451 pos = buffer + size - 1;
452 *pos-- = '\0';
453
454 if (in < 0) {
455 neg = 1;
456 n = -in;
457 }
458 else
459 n = in;
460
461 do {
462 *pos-- = '0' + n % 10;
463 n /= 10;
464 } while (n && pos >= buffer);
465 if (neg && pos > buffer)
466 *pos-- = '-';
467 return pos + 1;
468}
469
470/*
471 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200472 * the ascii representation for signed number 'n' in decimal.
473 */
474char *sltoa_r(long n, char *buffer, int size)
475{
476 char *pos;
477
478 if (n >= 0)
479 return ultoa_r(n, buffer, size);
480
481 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
482 *pos = '-';
483 return pos;
484}
485
486/*
487 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200488 * the ascii representation for number 'n' in decimal, formatted for
489 * HTML output with tags to create visual grouping by 3 digits. The
490 * output needs to support at least 171 characters.
491 */
492const char *ulltoh_r(unsigned long long n, char *buffer, int size)
493{
494 char *start;
495 int digit = 0;
496
497 start = buffer + size;
498 *--start = '\0';
499
500 do {
501 if (digit == 3 && start >= buffer + 7)
502 memcpy(start -= 7, "</span>", 7);
503
504 if (start >= buffer + 1) {
505 *--start = '0' + n % 10;
506 n /= 10;
507 }
508
509 if (digit == 3 && start >= buffer + 18)
510 memcpy(start -= 18, "<span class=\"rls\">", 18);
511
512 if (digit++ == 3)
513 digit = 1;
514 } while (n && start > buffer);
515 return start;
516}
517
518/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200519 * This function simply returns a locally allocated string containing the ascii
520 * representation for number 'n' in decimal, unless n is 0 in which case it
521 * returns the alternate string (or an empty string if the alternate string is
522 * NULL). It use is intended for limits reported in reports, where it's
523 * desirable not to display anything if there is no limit. Warning! it shares
524 * the same vector as ultoa_r().
525 */
526const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
527{
528 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
529}
530
Willy Tarreau588297f2014-06-16 15:16:40 +0200531/* returns a locally allocated string containing the quoted encoding of the
532 * input string. The output may be truncated to QSTR_SIZE chars, but it is
533 * guaranteed that the string will always be properly terminated. Quotes are
534 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
535 * always be at least 4 chars.
536 */
537const char *qstr(const char *str)
538{
539 char *ret = quoted_str[quoted_idx];
540 char *p, *end;
541
542 if (++quoted_idx >= NB_QSTR)
543 quoted_idx = 0;
544
545 p = ret;
546 end = ret + QSTR_SIZE;
547
548 *p++ = '"';
549
550 /* always keep 3 chars to support passing "" and the ending " */
551 while (*str && p < end - 3) {
552 if (*str == '"') {
553 *p++ = '"';
554 *p++ = '"';
555 }
556 else
557 *p++ = *str;
558 str++;
559 }
560 *p++ = '"';
561 return ret;
562}
563
Robert Tsai81ae1952007-12-05 10:47:29 +0100564/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200565 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
566 *
567 * It looks like this one would be a good candidate for inlining, but this is
568 * not interesting because it around 35 bytes long and often called multiple
569 * times within the same function.
570 */
571int ishex(char s)
572{
573 s -= '0';
574 if ((unsigned char)s <= 9)
575 return 1;
576 s -= 'A' - '0';
577 if ((unsigned char)s <= 5)
578 return 1;
579 s -= 'a' - 'A';
580 if ((unsigned char)s <= 5)
581 return 1;
582 return 0;
583}
584
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100585/* rounds <i> down to the closest value having max 2 digits */
586unsigned int round_2dig(unsigned int i)
587{
588 unsigned int mul = 1;
589
590 while (i >= 100) {
591 i /= 10;
592 mul *= 10;
593 }
594 return i * mul;
595}
596
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100597/*
598 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
599 * invalid character is found, a pointer to it is returned. If everything is
600 * fine, NULL is returned.
601 */
602const char *invalid_char(const char *name)
603{
604 if (!*name)
605 return name;
606
607 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100608 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100609 *name != '_' && *name != '-')
610 return name;
611 name++;
612 }
613 return NULL;
614}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200615
616/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200617 * Checks <name> for invalid characters. Valid chars are [_.-] and those
618 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200619 * If an invalid character is found, a pointer to it is returned.
620 * If everything is fine, NULL is returned.
621 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200622static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200623
624 if (!*name)
625 return name;
626
627 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100628 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200629 *name != '_' && *name != '-')
630 return name;
631
632 name++;
633 }
634
635 return NULL;
636}
637
638/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200639 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
640 * If an invalid character is found, a pointer to it is returned.
641 * If everything is fine, NULL is returned.
642 */
643const char *invalid_domainchar(const char *name) {
644 return __invalid_char(name, isalnum);
645}
646
647/*
648 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
649 * If an invalid character is found, a pointer to it is returned.
650 * If everything is fine, NULL is returned.
651 */
652const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200653 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200654}
655
656/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100657 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100658 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
659 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
660 * the function tries to guess the address family from the syntax. If the
661 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100662 * string is assumed to contain only an address, no port. The address can be a
663 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
664 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
665 * The return address will only have the address family and the address set,
666 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100667 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
668 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100669 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200670 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100671struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200672{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100673 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100674 /* max IPv6 length, including brackets and terminating NULL */
675 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100676 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100677
678 /* check IPv6 with square brackets */
679 if (str[0] == '[') {
680 size_t iplength = strlen(str);
681
682 if (iplength < 4) {
683 /* minimal size is 4 when using brackets "[::]" */
684 goto fail;
685 }
686 else if (iplength >= sizeof(tmpip)) {
687 /* IPv6 literal can not be larger than tmpip */
688 goto fail;
689 }
690 else {
691 if (str[iplength - 1] != ']') {
692 /* if address started with bracket, it should end with bracket */
693 goto fail;
694 }
695 else {
696 memcpy(tmpip, str + 1, iplength - 2);
697 tmpip[iplength - 2] = '\0';
698 str = tmpip;
699 }
700 }
701 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100702
Willy Tarreaufab5a432011-03-04 15:31:53 +0100703 /* Any IPv6 address */
704 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100705 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
706 sa->ss_family = AF_INET6;
707 else if (sa->ss_family != AF_INET6)
708 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100709 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100710 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100711 }
712
Willy Tarreau24709282013-03-10 21:32:12 +0100713 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100714 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100715 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
716 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100717 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100718 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100719 }
720
721 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100722 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
723 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100724 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100725 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100726 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100727 }
728
729 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100730 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
731 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100732 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100733 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100734 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100735 }
736
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100737 if (!resolve)
738 return NULL;
739
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200740 if (!dns_hostname_validation(str, NULL))
741 return NULL;
742
David du Colombierd5f43282011-03-17 10:40:16 +0100743#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200744 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100745 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100746 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100747
748 memset(&result, 0, sizeof(result));
749 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100750 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100751 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200752 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100753 hints.ai_protocol = 0;
754
755 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100756 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
757 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100758 else if (sa->ss_family != result->ai_family) {
759 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100760 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100761 }
Willy Tarreau24709282013-03-10 21:32:12 +0100762
David du Colombierd5f43282011-03-17 10:40:16 +0100763 switch (result->ai_family) {
764 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100765 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100766 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100767 success = 1;
768 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100769 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100770 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100771 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100772 success = 1;
773 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100774 }
775 }
776
Sean Carey58ea0392013-02-15 23:39:18 +0100777 if (result)
778 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100779
780 if (success)
781 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100782 }
David du Colombierd5f43282011-03-17 10:40:16 +0100783#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200784 /* try to resolve an IPv4/IPv6 hostname */
785 he = gethostbyname(str);
786 if (he) {
787 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
788 sa->ss_family = he->h_addrtype;
789 else if (sa->ss_family != he->h_addrtype)
790 goto fail;
791
792 switch (sa->ss_family) {
793 case AF_INET:
794 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100795 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200796 return sa;
797 case AF_INET6:
798 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100799 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200800 return sa;
801 }
802 }
803
David du Colombierd5f43282011-03-17 10:40:16 +0100804 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100805 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100806 return NULL;
807}
808
809/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100810 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
811 * range or offset consisting in two integers that the caller will have to
812 * check to find the relevant input format. The following format are supported :
813 *
814 * String format | address | port | low | high
815 * addr | <addr> | 0 | 0 | 0
816 * addr: | <addr> | 0 | 0 | 0
817 * addr:port | <addr> | <port> | <port> | <port>
818 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
819 * addr:+port | <addr> | <port> | 0 | <port>
820 * addr:-port | <addr> |-<port> | <port> | 0
821 *
822 * The detection of a port range or increment by the caller is made by
823 * comparing <low> and <high>. If both are equal, then port 0 means no port
824 * was specified. The caller may pass NULL for <low> and <high> if it is not
825 * interested in retrieving port ranges.
826 *
827 * Note that <addr> above may also be :
828 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
829 * - "*" => family will be AF_INET and address will be INADDR_ANY
830 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
831 * - a host name => family and address will depend on host name resolving.
832 *
Willy Tarreau24709282013-03-10 21:32:12 +0100833 * A prefix may be passed in before the address above to force the family :
834 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
835 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
836 * - "unix@" => force address to be a path to a UNIX socket even if the
837 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200838 * - 'abns@' -> force address to belong to the abstract namespace (Linux
839 * only). These sockets are just like Unix sockets but without
840 * the need for an underlying file system. The address is a
841 * string. Technically it's like a Unix socket with a zero in
842 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100843 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100844 *
mildisff5d5102015-10-26 18:50:08 +0100845 * IPv6 addresses can be declared with or without square brackets. When using
846 * square brackets for IPv6 addresses, the port separator (colon) is optional.
847 * If not using square brackets, and in order to avoid any ambiguity with
848 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
849 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
850 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100851 *
852 * If <pfx> is non-null, it is used as a string prefix before any path-based
853 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100854 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200855 * if <fqdn> is non-null, it will be filled with :
856 * - a pointer to the FQDN of the server name to resolve if there's one, and
857 * that the caller will have to free(),
858 * - NULL if there was an explicit address that doesn't require resolution.
859 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200860 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
861 * still honored so it is possible for the caller to know whether a resolution
862 * failed by clearing this flag and checking if <fqdn> was filled, indicating
863 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200864 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100865 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200866 * the address when cast to sockaddr_in and the address family is
867 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200868 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200869 * The matching protocol will be set into <proto> if non-null.
870 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200871 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
872 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100873 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200874struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
875 struct protocol **proto, char **err,
876 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100877{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100878 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100879 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200880 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100881 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100882 char *port1, *port2;
883 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200884 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200885 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200886 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100887
888 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200889 if (fqdn)
890 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200891
Willy Tarreaudad36a32013-03-11 01:20:04 +0100892 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100893 if (str2 == NULL) {
894 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100895 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100896 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200897
Willy Tarreau9f69f462015-09-08 16:01:25 +0200898 if (!*str2) {
899 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
900 goto out;
901 }
902
Willy Tarreau24709282013-03-10 21:32:12 +0100903 memset(&ss, 0, sizeof(ss));
904
Willy Tarreaue835bd82020-09-16 11:35:47 +0200905 /* prepare the default socket types */
906 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM)
907 sock_type = ctrl_type = SOCK_DGRAM;
908 else
909 sock_type = ctrl_type = SOCK_STREAM;
910
911 if (strncmp(str2, "stream+", 7) == 0) {
912 str2 += 7;
913 sock_type = ctrl_type = SOCK_STREAM;
914 }
915 else if (strncmp(str2, "dgram+", 6) == 0) {
916 str2 += 6;
917 sock_type = ctrl_type = SOCK_DGRAM;
918 }
919
Willy Tarreau24709282013-03-10 21:32:12 +0100920 if (strncmp(str2, "unix@", 5) == 0) {
921 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200922 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100923 ss.ss_family = AF_UNIX;
924 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200925 else if (strncmp(str2, "abns@", 5) == 0) {
926 str2 += 5;
927 abstract = 1;
928 ss.ss_family = AF_UNIX;
929 }
Willy Tarreau24709282013-03-10 21:32:12 +0100930 else if (strncmp(str2, "ipv4@", 5) == 0) {
931 str2 += 5;
932 ss.ss_family = AF_INET;
933 }
934 else if (strncmp(str2, "ipv6@", 5) == 0) {
935 str2 += 5;
936 ss.ss_family = AF_INET6;
937 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200938 else if (strncmp(str2, "udp4@", 5) == 0) {
939 str2 += 5;
940 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200941 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200942 }
943 else if (strncmp(str2, "udp6@", 5) == 0) {
944 str2 += 5;
945 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200946 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200947 }
948 else if (strncmp(str2, "udp@", 4) == 0) {
949 str2 += 4;
950 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200951 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200952 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +0100953 else if (strncmp(str2, "quic4@", 6) == 0) {
954 str2 += 6;
955 ss.ss_family = AF_INET;
956 sock_type = SOCK_DGRAM;
957 ctrl_type = SOCK_STREAM;
958 }
959 else if (strncmp(str2, "quic6@", 6) == 0) {
960 str2 += 6;
961 ss.ss_family = AF_INET6;
962 sock_type = SOCK_DGRAM;
963 ctrl_type = SOCK_STREAM;
964 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200965 else if (strncmp(str2, "fd@", 3) == 0) {
966 str2 += 3;
967 ss.ss_family = AF_CUST_EXISTING_FD;
968 }
969 else if (strncmp(str2, "sockpair@", 9) == 0) {
970 str2 += 9;
971 ss.ss_family = AF_CUST_SOCKPAIR;
972 }
Willy Tarreau24709282013-03-10 21:32:12 +0100973 else if (*str2 == '/') {
974 ss.ss_family = AF_UNIX;
975 }
976 else
977 ss.ss_family = AF_UNSPEC;
978
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200979 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200980 struct sockaddr_storage ss2;
981 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200982 char *endptr;
983
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200984 new_fd = strtol(str2, &endptr, 10);
985 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200986 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
987 goto out;
988 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200989
Willy Tarreaua215be22020-09-16 10:14:16 +0200990 /* just verify that it's a socket */
991 addr_len = sizeof(ss2);
992 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
993 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
994 goto out;
995 }
996
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200997 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
998 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200999 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001000 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001001 char *endptr;
1002
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001003 new_fd = strtol(str2, &endptr, 10);
1004 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001005 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001006 goto out;
1007 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001008
Willy Tarreau6edc7222020-09-15 17:41:56 +02001009 if (opts & PA_O_SOCKET_FD) {
1010 socklen_t addr_len;
1011 int type;
1012
1013 addr_len = sizeof(ss);
1014 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1015 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1016 goto out;
1017 }
1018
1019 addr_len = sizeof(type);
1020 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001021 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001022 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1023 goto out;
1024 }
1025
1026 porta = portl = porth = get_host_port(&ss);
1027 } else if (opts & PA_O_RAW_FD) {
1028 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1029 ((struct sockaddr_in *)&ss)->sin_port = 0;
1030 } else {
1031 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1032 goto out;
1033 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001034 }
1035 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001036 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001037 int prefix_path_len;
1038 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001039 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001040
1041 /* complete unix socket path name during startup or soft-restart is
1042 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1043 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001044 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001045 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001046 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001047
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001048 adr_len = strlen(str2);
1049 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001050 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1051 goto out;
1052 }
1053
Willy Tarreauccfccef2014-05-10 01:49:15 +02001054 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001055 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001056 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001057 memcpy(un->sun_path, pfx, prefix_path_len);
1058 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001059 }
Willy Tarreau24709282013-03-10 21:32:12 +01001060 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001061 char *end = str2 + strlen(str2);
1062 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001063
mildisff5d5102015-10-26 18:50:08 +01001064 /* search for : or ] whatever comes first */
1065 for (chr = end-1; chr > str2; chr--) {
1066 if (*chr == ']' || *chr == ':')
1067 break;
1068 }
1069
1070 if (*chr == ':') {
1071 /* Found a colon before a closing-bracket, must be a port separator.
1072 * This guarantee backward compatibility.
1073 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001074 if (!(opts & PA_O_PORT_OK)) {
1075 memprintf(err, "port specification not permitted here in '%s'", str);
1076 goto out;
1077 }
mildisff5d5102015-10-26 18:50:08 +01001078 *chr++ = '\0';
1079 port1 = chr;
1080 }
1081 else {
1082 /* Either no colon and no closing-bracket
1083 * or directly ending with a closing-bracket.
1084 * However, no port.
1085 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001086 if (opts & PA_O_PORT_MAND) {
1087 memprintf(err, "missing port specification in '%s'", str);
1088 goto out;
1089 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001090 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001091 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001092
Willy Tarreau90807112020-02-25 08:16:33 +01001093 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001094 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001095 if (port2) {
1096 if (!(opts & PA_O_PORT_RANGE)) {
1097 memprintf(err, "port range not permitted here in '%s'", str);
1098 goto out;
1099 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001100 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001101 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001102 else
1103 port2 = port1;
1104 portl = atoi(port1);
1105 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001106
1107 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1108 memprintf(err, "invalid port '%s'", port1);
1109 goto out;
1110 }
1111
1112 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1113 memprintf(err, "invalid port '%s'", port2);
1114 goto out;
1115 }
1116
1117 if (portl > porth) {
1118 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1119 goto out;
1120 }
1121
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001122 porta = portl;
1123 }
1124 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001125 if (!(opts & PA_O_PORT_OFS)) {
1126 memprintf(err, "port offset not permitted here in '%s'", str);
1127 goto out;
1128 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001129 portl = atoi(port1 + 1);
1130 porta = -portl;
1131 }
1132 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001133 if (!(opts & PA_O_PORT_OFS)) {
1134 memprintf(err, "port offset not permitted here in '%s'", str);
1135 goto out;
1136 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001137 porth = atoi(port1 + 1);
1138 porta = porth;
1139 }
1140 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001141 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001142 goto out;
1143 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001144 else if (opts & PA_O_PORT_MAND) {
1145 memprintf(err, "missing port specification in '%s'", str);
1146 goto out;
1147 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001148
1149 /* first try to parse the IP without resolving. If it fails, it
1150 * tells us we need to keep a copy of the FQDN to resolve later
1151 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001152 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001153 */
1154 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001155 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1156 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001157 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1158 goto out;
1159 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001160
Willy Tarreauceccdd72016-11-02 22:27:10 +01001161 if (fqdn) {
1162 if (str2 != back)
1163 memmove(back, str2, strlen(str2) + 1);
1164 *fqdn = back;
1165 back = NULL;
1166 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001167 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001168 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001169 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001170
Willy Tarreaue835bd82020-09-16 11:35:47 +02001171 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1172 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1173 goto out;
1174 }
1175 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1176 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1177 goto out;
1178 }
1179
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001180 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001181 /* Note: if the caller asks for a proto, we must find one,
1182 * except if we return with an fqdn that will resolve later,
1183 * in which case the address is not known yet (this is only
1184 * for servers actually).
1185 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001186 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001187 sock_type == SOCK_DGRAM,
1188 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001189
Willy Tarreau5fc93282020-09-16 18:25:03 +02001190 if (!new_proto && (!fqdn || !*fqdn)) {
1191 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1192 goto out;
1193 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001194
1195 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1196 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1197 goto out;
1198 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001199 }
1200
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001201 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001202 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001203 if (port)
1204 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001205 if (low)
1206 *low = portl;
1207 if (high)
1208 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001209 if (fd)
1210 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001211 if (proto)
1212 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001213 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001214 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001215}
1216
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001217/* converts <str> to a struct in_addr containing a network mask. It can be
1218 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001219 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001220 */
1221int str2mask(const char *str, struct in_addr *mask)
1222{
1223 if (strchr(str, '.') != NULL) { /* dotted notation */
1224 if (!inet_pton(AF_INET, str, mask))
1225 return 0;
1226 }
1227 else { /* mask length */
1228 char *err;
1229 unsigned long len = strtol(str, &err, 10);
1230
1231 if (!*str || (err && *err) || (unsigned)len > 32)
1232 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001233
1234 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001235 }
1236 return 1;
1237}
1238
Tim Duesterhus47185172018-01-25 16:24:49 +01001239/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001240 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001241 * if the conversion succeeds otherwise zero.
1242 */
1243int str2mask6(const char *str, struct in6_addr *mask)
1244{
1245 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1246 if (!inet_pton(AF_INET6, str, mask))
1247 return 0;
1248 }
1249 else { /* mask length */
1250 char *err;
1251 unsigned long len = strtol(str, &err, 10);
1252
1253 if (!*str || (err && *err) || (unsigned)len > 128)
1254 return 0;
1255
1256 len2mask6(len, mask);
1257 }
1258 return 1;
1259}
1260
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001261/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1262 * succeeds otherwise zero.
1263 */
1264int cidr2dotted(int cidr, struct in_addr *mask) {
1265
1266 if (cidr < 0 || cidr > 32)
1267 return 0;
1268
1269 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1270 return 1;
1271}
1272
Thierry Fournier70473a52016-02-17 17:12:14 +01001273/* Convert mask from bit length form to in_addr form.
1274 * This function never fails.
1275 */
1276void len2mask4(int len, struct in_addr *addr)
1277{
1278 if (len >= 32) {
1279 addr->s_addr = 0xffffffff;
1280 return;
1281 }
1282 if (len <= 0) {
1283 addr->s_addr = 0x00000000;
1284 return;
1285 }
1286 addr->s_addr = 0xffffffff << (32 - len);
1287 addr->s_addr = htonl(addr->s_addr);
1288}
1289
1290/* Convert mask from bit length form to in6_addr form.
1291 * This function never fails.
1292 */
1293void len2mask6(int len, struct in6_addr *addr)
1294{
1295 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1296 len -= 32;
1297 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1298 len -= 32;
1299 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1300 len -= 32;
1301 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1302}
1303
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001304/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001305 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001306 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001307 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001308 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1309 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001310int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001311{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001312 __label__ out_free, out_err;
1313 char *c, *s;
1314 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001315
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001316 s = strdup(str);
1317 if (!s)
1318 return 0;
1319
Willy Tarreaubaaee002006-06-26 02:48:02 +02001320 memset(mask, 0, sizeof(*mask));
1321 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001322
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001323 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001324 *c++ = '\0';
1325 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001326 if (!str2mask(c, mask))
1327 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001328 }
1329 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001330 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001331 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001332 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001333 struct hostent *he;
1334
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001335 if (!resolve)
1336 goto out_err;
1337
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001338 if ((he = gethostbyname(s)) == NULL) {
1339 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001340 }
1341 else
1342 *addr = *(struct in_addr *) *(he->h_addr_list);
1343 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001344
1345 ret_val = 1;
1346 out_free:
1347 free(s);
1348 return ret_val;
1349 out_err:
1350 ret_val = 0;
1351 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001352}
1353
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001354
1355/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001356 * converts <str> to two struct in6_addr* which must be pre-allocated.
1357 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001358 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001359 * Returns 1 if OK, 0 if error.
1360 */
1361int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1362{
1363 char *c, *s;
1364 int ret_val = 0;
1365 char *err;
1366 unsigned long len = 128;
1367
1368 s = strdup(str);
1369 if (!s)
1370 return 0;
1371
1372 memset(mask, 0, sizeof(*mask));
1373 memset(addr, 0, sizeof(*addr));
1374
1375 if ((c = strrchr(s, '/')) != NULL) {
1376 *c++ = '\0'; /* c points to the mask */
1377 if (!*c)
1378 goto out_free;
1379
1380 len = strtoul(c, &err, 10);
1381 if ((err && *err) || (unsigned)len > 128)
1382 goto out_free;
1383 }
1384 *mask = len; /* OK we have a valid mask in <len> */
1385
1386 if (!inet_pton(AF_INET6, s, addr))
1387 goto out_free;
1388
1389 ret_val = 1;
1390 out_free:
1391 free(s);
1392 return ret_val;
1393}
1394
1395
1396/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001397 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001398 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001399int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001400{
1401 int saw_digit, octets, ch;
1402 u_char tmp[4], *tp;
1403 const char *cp = addr;
1404
1405 saw_digit = 0;
1406 octets = 0;
1407 *(tp = tmp) = 0;
1408
1409 while (*addr) {
1410 unsigned char digit = (ch = *addr++) - '0';
1411 if (digit > 9 && ch != '.')
1412 break;
1413 if (digit <= 9) {
1414 u_int new = *tp * 10 + digit;
1415 if (new > 255)
1416 return 0;
1417 *tp = new;
1418 if (!saw_digit) {
1419 if (++octets > 4)
1420 return 0;
1421 saw_digit = 1;
1422 }
1423 } else if (ch == '.' && saw_digit) {
1424 if (octets == 4)
1425 return 0;
1426 *++tp = 0;
1427 saw_digit = 0;
1428 } else
1429 return 0;
1430 }
1431
1432 if (octets < 4)
1433 return 0;
1434
1435 memcpy(&dst->s_addr, tmp, 4);
1436 return addr-cp-1;
1437}
1438
1439/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001440 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001441 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001442 * the hostname. Actually only http and https are supported. <out> can be NULL.
1443 * This function returns the consumed length. It is useful if you parse complete
1444 * url like http://host:port/path, because the consumed length corresponds to
1445 * the first character of the path. If the conversion fails, it returns -1.
1446 *
1447 * This function tries to resolve the DNS name if haproxy is in starting mode.
1448 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001449 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001450int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001451{
1452 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001453 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001454 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001455 unsigned long long int http_code = 0;
1456 int default_port;
1457 struct hostent *he;
1458 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001459
1460 /* Firstly, try to find :// pattern */
1461 while (curr < url+ulen && url_code != 0x3a2f2f) {
1462 url_code = ((url_code & 0xffff) << 8);
1463 url_code += (unsigned char)*curr++;
1464 }
1465
1466 /* Secondly, if :// pattern is found, verify parsed stuff
1467 * before pattern is matching our http pattern.
1468 * If so parse ip address and port in uri.
1469 *
1470 * WARNING: Current code doesn't support dynamic async dns resolver.
1471 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001472 if (url_code != 0x3a2f2f)
1473 return -1;
1474
1475 /* Copy scheme, and utrn to lower case. */
1476 while (cp < curr - 3)
1477 http_code = (http_code << 8) + *cp++;
1478 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001479
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001480 /* HTTP or HTTPS url matching */
1481 if (http_code == 0x2020202068747470ULL) {
1482 default_port = 80;
1483 if (out)
1484 out->scheme = SCH_HTTP;
1485 }
1486 else if (http_code == 0x2020206874747073ULL) {
1487 default_port = 443;
1488 if (out)
1489 out->scheme = SCH_HTTPS;
1490 }
1491 else
1492 return -1;
1493
1494 /* If the next char is '[', the host address is IPv6. */
1495 if (*curr == '[') {
1496 curr++;
1497
1498 /* Check trash size */
1499 if (trash.size < ulen)
1500 return -1;
1501
1502 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001503 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001504 for (end = curr;
1505 end < url + ulen && *end != ']';
1506 end++, p++)
1507 *p = *end;
1508 if (*end != ']')
1509 return -1;
1510 *p = '\0';
1511
1512 /* Update out. */
1513 if (out) {
1514 out->host = curr;
1515 out->host_len = end - curr;
1516 }
1517
1518 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001519 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001520 return -1;
1521 end++;
1522
1523 /* Decode port. */
1524 if (*end == ':') {
1525 end++;
1526 default_port = read_uint(&end, url + ulen);
1527 }
1528 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1529 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1530 return end - url;
1531 }
1532 else {
1533 /* We are looking for IP address. If you want to parse and
1534 * resolve hostname found in url, you can use str2sa_range(), but
1535 * be warned this can slow down global daemon performances
1536 * while handling lagging dns responses.
1537 */
1538 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1539 if (ret) {
1540 /* Update out. */
1541 if (out) {
1542 out->host = curr;
1543 out->host_len = ret;
1544 }
1545
1546 curr += ret;
1547
1548 /* Decode port. */
1549 if (*curr == ':') {
1550 curr++;
1551 default_port = read_uint(&curr, url + ulen);
1552 }
1553 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1554
1555 /* Set family. */
1556 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1557 return curr - url;
1558 }
1559 else if (global.mode & MODE_STARTING) {
1560 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1561 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001562 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001563
1564 /* look for : or / or end */
1565 for (end = curr;
1566 end < url + ulen && *end != '/' && *end != ':';
1567 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001568 memcpy(trash.area, curr, end - curr);
1569 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001570
1571 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001572 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001573 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001574 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001575
1576 /* Update out. */
1577 if (out) {
1578 out->host = curr;
1579 out->host_len = end - curr;
1580 }
1581
1582 /* Decode port. */
1583 if (*end == ':') {
1584 end++;
1585 default_port = read_uint(&end, url + ulen);
1586 }
1587
1588 /* Copy IP address, set port and family. */
1589 switch (he->h_addrtype) {
1590 case AF_INET:
1591 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1592 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1593 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1594 return end - url;
1595
1596 case AF_INET6:
1597 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1598 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1599 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1600 return end - url;
1601 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001602 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001603 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001604 return -1;
1605}
1606
Willy Tarreau631f01c2011-09-05 00:36:48 +02001607/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1608 * address family is returned so that it's easy for the caller to adapt to the
1609 * output format. Zero is returned if the address family is not supported. -1
1610 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1611 * supported.
1612 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001613int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001614{
1615
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001616 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001617
1618 if (size < 5)
1619 return 0;
1620 *str = '\0';
1621
1622 switch (addr->ss_family) {
1623 case AF_INET:
1624 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1625 break;
1626 case AF_INET6:
1627 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1628 break;
1629 case AF_UNIX:
1630 memcpy(str, "unix", 5);
1631 return addr->ss_family;
1632 default:
1633 return 0;
1634 }
1635
1636 if (inet_ntop(addr->ss_family, ptr, str, size))
1637 return addr->ss_family;
1638
1639 /* failed */
1640 return -1;
1641}
1642
Simon Horman75ab8bd2014-06-16 09:39:41 +09001643/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1644 * address family is returned so that it's easy for the caller to adapt to the
1645 * output format. Zero is returned if the address family is not supported. -1
1646 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1647 * supported.
1648 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001649int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001650{
1651
1652 uint16_t port;
1653
1654
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001655 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001656 return 0;
1657 *str = '\0';
1658
1659 switch (addr->ss_family) {
1660 case AF_INET:
1661 port = ((struct sockaddr_in *)addr)->sin_port;
1662 break;
1663 case AF_INET6:
1664 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1665 break;
1666 case AF_UNIX:
1667 memcpy(str, "unix", 5);
1668 return addr->ss_family;
1669 default:
1670 return 0;
1671 }
1672
1673 snprintf(str, size, "%u", ntohs(port));
1674 return addr->ss_family;
1675}
1676
Willy Tarreau16e01562016-08-09 16:46:18 +02001677/* check if the given address is local to the system or not. It will return
1678 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1679 * it is. We don't want to iterate over all interfaces for this (and it is not
1680 * portable). So instead we try to bind in UDP to this address on a free non
1681 * privileged port and to connect to the same address, port 0 (connect doesn't
1682 * care). If it succeeds, we own the address. Note that non-inet addresses are
1683 * considered local since they're most likely AF_UNIX.
1684 */
1685int addr_is_local(const struct netns_entry *ns,
1686 const struct sockaddr_storage *orig)
1687{
1688 struct sockaddr_storage addr;
1689 int result;
1690 int fd;
1691
1692 if (!is_inet_addr(orig))
1693 return 1;
1694
1695 memcpy(&addr, orig, sizeof(addr));
1696 set_host_port(&addr, 0);
1697
1698 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1699 if (fd < 0)
1700 return -1;
1701
1702 result = -1;
1703 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1704 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1705 result = 0; // fail, non-local address
1706 else
1707 result = 1; // success, local address
1708 }
1709 else {
1710 if (errno == EADDRNOTAVAIL)
1711 result = 0; // definitely not local :-)
1712 }
1713 close(fd);
1714
1715 return result;
1716}
1717
Willy Tarreaubaaee002006-06-26 02:48:02 +02001718/* will try to encode the string <string> replacing all characters tagged in
1719 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1720 * prefixed by <escape>, and will store the result between <start> (included)
1721 * and <stop> (excluded), and will always terminate the string with a '\0'
1722 * before <stop>. The position of the '\0' is returned if the conversion
1723 * completes. If bytes are missing between <start> and <stop>, then the
1724 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1725 * cannot even be stored so we return <start> without writing the 0.
1726 * The input string must also be zero-terminated.
1727 */
1728const char hextab[16] = "0123456789ABCDEF";
1729char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001730 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001731 const char *string)
1732{
1733 if (start < stop) {
1734 stop--; /* reserve one byte for the final '\0' */
1735 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001736 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001737 *start++ = *string;
1738 else {
1739 if (start + 3 >= stop)
1740 break;
1741 *start++ = escape;
1742 *start++ = hextab[(*string >> 4) & 15];
1743 *start++ = hextab[*string & 15];
1744 }
1745 string++;
1746 }
1747 *start = '\0';
1748 }
1749 return start;
1750}
1751
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001752/*
1753 * Same behavior as encode_string() above, except that it encodes chunk
1754 * <chunk> instead of a string.
1755 */
1756char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001757 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001758 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001759{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001760 char *str = chunk->area;
1761 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001762
1763 if (start < stop) {
1764 stop--; /* reserve one byte for the final '\0' */
1765 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001766 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001767 *start++ = *str;
1768 else {
1769 if (start + 3 >= stop)
1770 break;
1771 *start++ = escape;
1772 *start++ = hextab[(*str >> 4) & 15];
1773 *start++ = hextab[*str & 15];
1774 }
1775 str++;
1776 }
1777 *start = '\0';
1778 }
1779 return start;
1780}
1781
Dragan Dosen0edd1092016-02-12 13:23:02 +01001782/*
1783 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001784 * character. The input <string> must be zero-terminated. The result will
1785 * be stored between <start> (included) and <stop> (excluded). This
1786 * function will always try to terminate the resulting string with a '\0'
1787 * before <stop>, and will return its position if the conversion
1788 * completes.
1789 */
1790char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001791 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001792 const char *string)
1793{
1794 if (start < stop) {
1795 stop--; /* reserve one byte for the final '\0' */
1796 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001797 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001798 *start++ = *string;
1799 else {
1800 if (start + 2 >= stop)
1801 break;
1802 *start++ = escape;
1803 *start++ = *string;
1804 }
1805 string++;
1806 }
1807 *start = '\0';
1808 }
1809 return start;
1810}
1811
1812/*
1813 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001814 * character. <chunk> contains the input to be escaped. The result will be
1815 * stored between <start> (included) and <stop> (excluded). The function
1816 * will always try to terminate the resulting string with a '\0' before
1817 * <stop>, and will return its position if the conversion completes.
1818 */
1819char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001820 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001821 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001822{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001823 char *str = chunk->area;
1824 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001825
1826 if (start < stop) {
1827 stop--; /* reserve one byte for the final '\0' */
1828 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001829 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001830 *start++ = *str;
1831 else {
1832 if (start + 2 >= stop)
1833 break;
1834 *start++ = escape;
1835 *start++ = *str;
1836 }
1837 str++;
1838 }
1839 *start = '\0';
1840 }
1841 return start;
1842}
1843
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001844/* Check a string for using it in a CSV output format. If the string contains
1845 * one of the following four char <">, <,>, CR or LF, the string is
1846 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1847 * <str> is the input string to be escaped. The function assumes that
1848 * the input string is null-terminated.
1849 *
1850 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001851 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001852 * format.
1853 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001854 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001855 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001856 * If <quote> is 1, the converter puts the quotes only if any reserved character
1857 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001858 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001859 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001860 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001861 * The function returns the converted string on its output. If an error
1862 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001863 * for using the function directly as printf() argument.
1864 *
1865 * If the output buffer is too short to contain the input string, the result
1866 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001867 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001868 * This function appends the encoding to the existing output chunk, and it
1869 * guarantees that it starts immediately at the first available character of
1870 * the chunk. Please use csv_enc() instead if you want to replace the output
1871 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001872 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001873const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001874{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001875 char *end = output->area + output->size;
1876 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001877 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001878
Willy Tarreaub631c292016-01-08 10:04:08 +01001879 if (quote == 1) {
1880 /* automatic quoting: first verify if we'll have to quote the string */
1881 if (!strpbrk(str, "\n\r,\""))
1882 quote = 0;
1883 }
1884
1885 if (quote)
1886 *ptr++ = '"';
1887
Willy Tarreau898529b2016-01-06 18:07:04 +01001888 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1889 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001890 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001891 ptr++;
1892 if (ptr >= end - 2) {
1893 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001894 break;
1895 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001896 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001897 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001898 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001899 str++;
1900 }
1901
Willy Tarreaub631c292016-01-08 10:04:08 +01001902 if (quote)
1903 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001904
Willy Tarreau898529b2016-01-06 18:07:04 +01001905 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001906 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001907 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001908}
1909
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001910/* Decode an URL-encoded string in-place. The resulting string might
1911 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001912 * aborted, the string is truncated before the issue and a negative value is
1913 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001914 * If the 'in_form' argument is non-nul the string is assumed to be part of
1915 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1916 * turned to a space. If it's zero, this will only be done after a question
1917 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001918 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001919int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001920{
1921 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001922 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001923
1924 in = string;
1925 out = string;
1926 while (*in) {
1927 switch (*in) {
1928 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001929 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001930 break;
1931 case '%' :
1932 if (!ishex(in[1]) || !ishex(in[2]))
1933 goto end;
1934 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1935 in += 2;
1936 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001937 case '?':
1938 in_form = 1;
1939 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001940 default:
1941 *out++ = *in;
1942 break;
1943 }
1944 in++;
1945 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001946 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001947 end:
1948 *out = 0;
1949 return ret;
1950}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001951
Willy Tarreau6911fa42007-03-04 18:06:08 +01001952unsigned int str2ui(const char *s)
1953{
1954 return __str2ui(s);
1955}
1956
1957unsigned int str2uic(const char *s)
1958{
1959 return __str2uic(s);
1960}
1961
1962unsigned int strl2ui(const char *s, int len)
1963{
1964 return __strl2ui(s, len);
1965}
1966
1967unsigned int strl2uic(const char *s, int len)
1968{
1969 return __strl2uic(s, len);
1970}
1971
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001972unsigned int read_uint(const char **s, const char *end)
1973{
1974 return __read_uint(s, end);
1975}
1976
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001977/* This function reads an unsigned integer from the string pointed to by <s> and
1978 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1979 * function automatically stops at <end>. If the number overflows, the 2^64-1
1980 * value is returned.
1981 */
1982unsigned long long int read_uint64(const char **s, const char *end)
1983{
1984 const char *ptr = *s;
1985 unsigned long long int i = 0, tmp;
1986 unsigned int j;
1987
1988 while (ptr < end) {
1989
1990 /* read next char */
1991 j = *ptr - '0';
1992 if (j > 9)
1993 goto read_uint64_end;
1994
1995 /* add char to the number and check overflow. */
1996 tmp = i * 10;
1997 if (tmp / 10 != i) {
1998 i = ULLONG_MAX;
1999 goto read_uint64_eat;
2000 }
2001 if (ULLONG_MAX - tmp < j) {
2002 i = ULLONG_MAX;
2003 goto read_uint64_eat;
2004 }
2005 i = tmp + j;
2006 ptr++;
2007 }
2008read_uint64_eat:
2009 /* eat each numeric char */
2010 while (ptr < end) {
2011 if ((unsigned int)(*ptr - '0') > 9)
2012 break;
2013 ptr++;
2014 }
2015read_uint64_end:
2016 *s = ptr;
2017 return i;
2018}
2019
2020/* This function reads an integer from the string pointed to by <s> and returns
2021 * it. The <s> pointer is adjusted to point to the first unread char. The function
2022 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2023 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2024 * returned.
2025 */
2026long long int read_int64(const char **s, const char *end)
2027{
2028 unsigned long long int i = 0;
2029 int neg = 0;
2030
2031 /* Look for minus char. */
2032 if (**s == '-') {
2033 neg = 1;
2034 (*s)++;
2035 }
2036 else if (**s == '+')
2037 (*s)++;
2038
2039 /* convert as positive number. */
2040 i = read_uint64(s, end);
2041
2042 if (neg) {
2043 if (i > 0x8000000000000000ULL)
2044 return LLONG_MIN;
2045 return -i;
2046 }
2047 if (i > 0x7fffffffffffffffULL)
2048 return LLONG_MAX;
2049 return i;
2050}
2051
Willy Tarreau6911fa42007-03-04 18:06:08 +01002052/* This one is 7 times faster than strtol() on athlon with checks.
2053 * It returns the value of the number composed of all valid digits read,
2054 * and can process negative numbers too.
2055 */
2056int strl2ic(const char *s, int len)
2057{
2058 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002059 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002060
2061 if (len > 0) {
2062 if (*s != '-') {
2063 /* positive number */
2064 while (len-- > 0) {
2065 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002066 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002067 if (j > 9)
2068 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002069 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002070 }
2071 } else {
2072 /* negative number */
2073 s++;
2074 while (--len > 0) {
2075 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002076 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002077 if (j > 9)
2078 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002079 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002080 }
2081 }
2082 }
2083 return i;
2084}
2085
2086
2087/* This function reads exactly <len> chars from <s> and converts them to a
2088 * signed integer which it stores into <ret>. It accurately detects any error
2089 * (truncated string, invalid chars, overflows). It is meant to be used in
2090 * applications designed for hostile environments. It returns zero when the
2091 * number has successfully been converted, non-zero otherwise. When an error
2092 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2093 * faster than strtol().
2094 */
2095int strl2irc(const char *s, int len, int *ret)
2096{
2097 int i = 0;
2098 int j;
2099
2100 if (!len)
2101 return 1;
2102
2103 if (*s != '-') {
2104 /* positive number */
2105 while (len-- > 0) {
2106 j = (*s++) - '0';
2107 if (j > 9) return 1; /* invalid char */
2108 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2109 i = i * 10;
2110 if (i + j < i) return 1; /* check for addition overflow */
2111 i = i + j;
2112 }
2113 } else {
2114 /* negative number */
2115 s++;
2116 while (--len > 0) {
2117 j = (*s++) - '0';
2118 if (j > 9) return 1; /* invalid char */
2119 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2120 i = i * 10;
2121 if (i - j > i) return 1; /* check for subtract overflow */
2122 i = i - j;
2123 }
2124 }
2125 *ret = i;
2126 return 0;
2127}
2128
2129
2130/* This function reads exactly <len> chars from <s> and converts them to a
2131 * signed integer which it stores into <ret>. It accurately detects any error
2132 * (truncated string, invalid chars, overflows). It is meant to be used in
2133 * applications designed for hostile environments. It returns zero when the
2134 * number has successfully been converted, non-zero otherwise. When an error
2135 * is returned, the <ret> value is left untouched. It is about 3 times slower
2136 * than str2irc().
2137 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002138
2139int strl2llrc(const char *s, int len, long long *ret)
2140{
2141 long long i = 0;
2142 int j;
2143
2144 if (!len)
2145 return 1;
2146
2147 if (*s != '-') {
2148 /* positive number */
2149 while (len-- > 0) {
2150 j = (*s++) - '0';
2151 if (j > 9) return 1; /* invalid char */
2152 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2153 i = i * 10LL;
2154 if (i + j < i) return 1; /* check for addition overflow */
2155 i = i + j;
2156 }
2157 } else {
2158 /* negative number */
2159 s++;
2160 while (--len > 0) {
2161 j = (*s++) - '0';
2162 if (j > 9) return 1; /* invalid char */
2163 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2164 i = i * 10LL;
2165 if (i - j > i) return 1; /* check for subtract overflow */
2166 i = i - j;
2167 }
2168 }
2169 *ret = i;
2170 return 0;
2171}
2172
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002173/* This function is used with pat_parse_dotted_ver(). It converts a string
2174 * composed by two number separated by a dot. Each part must contain in 16 bits
2175 * because internally they will be represented as a 32-bit quantity stored in
2176 * a 64-bit integer. It returns zero when the number has successfully been
2177 * converted, non-zero otherwise. When an error is returned, the <ret> value
2178 * is left untouched.
2179 *
2180 * "1.3" -> 0x0000000000010003
2181 * "65535.65535" -> 0x00000000ffffffff
2182 */
2183int strl2llrc_dotted(const char *text, int len, long long *ret)
2184{
2185 const char *end = &text[len];
2186 const char *p;
2187 long long major, minor;
2188
2189 /* Look for dot. */
2190 for (p = text; p < end; p++)
2191 if (*p == '.')
2192 break;
2193
2194 /* Convert major. */
2195 if (strl2llrc(text, p - text, &major) != 0)
2196 return 1;
2197
2198 /* Check major. */
2199 if (major >= 65536)
2200 return 1;
2201
2202 /* Convert minor. */
2203 minor = 0;
2204 if (p < end)
2205 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2206 return 1;
2207
2208 /* Check minor. */
2209 if (minor >= 65536)
2210 return 1;
2211
2212 /* Compose value. */
2213 *ret = (major << 16) | (minor & 0xffff);
2214 return 0;
2215}
2216
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002217/* This function parses a time value optionally followed by a unit suffix among
2218 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2219 * expected by the caller. The computation does its best to avoid overflows.
2220 * The value is returned in <ret> if everything is fine, and a NULL is returned
2221 * by the function. In case of error, a pointer to the error is returned and
2222 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002223 * Values resulting in values larger than or equal to 2^31 after conversion are
2224 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2225 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002226 */
2227const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2228{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002229 unsigned long long imult, idiv;
2230 unsigned long long omult, odiv;
2231 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002232 const char *str = text;
2233
2234 if (!isdigit((unsigned char)*text))
2235 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002236
2237 omult = odiv = 1;
2238
2239 switch (unit_flags & TIME_UNIT_MASK) {
2240 case TIME_UNIT_US: omult = 1000000; break;
2241 case TIME_UNIT_MS: omult = 1000; break;
2242 case TIME_UNIT_S: break;
2243 case TIME_UNIT_MIN: odiv = 60; break;
2244 case TIME_UNIT_HOUR: odiv = 3600; break;
2245 case TIME_UNIT_DAY: odiv = 86400; break;
2246 default: break;
2247 }
2248
2249 value = 0;
2250
2251 while (1) {
2252 unsigned int j;
2253
2254 j = *text - '0';
2255 if (j > 9)
2256 break;
2257 text++;
2258 value *= 10;
2259 value += j;
2260 }
2261
2262 imult = idiv = 1;
2263 switch (*text) {
2264 case '\0': /* no unit = default unit */
2265 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002266 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002267 case 's': /* second = unscaled unit */
2268 break;
2269 case 'u': /* microsecond : "us" */
2270 if (text[1] == 's') {
2271 idiv = 1000000;
2272 text++;
2273 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002274 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002275 case 'm': /* millisecond : "ms" or minute: "m" */
2276 if (text[1] == 's') {
2277 idiv = 1000;
2278 text++;
2279 } else
2280 imult = 60;
2281 break;
2282 case 'h': /* hour : "h" */
2283 imult = 3600;
2284 break;
2285 case 'd': /* day : "d" */
2286 imult = 86400;
2287 break;
2288 default:
2289 return text;
2290 break;
2291 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002292 if (*(++text) != '\0') {
2293 ha_warning("unexpected character '%c' after the timer value '%s', only "
2294 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2295 " This will be reported as an error in next versions.\n", *text, str);
2296 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002297
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002298 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002299 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2300 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2301 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2302 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2303
Willy Tarreau9faebe32019-06-07 19:00:37 +02002304 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2305 if (result >= 0x80000000)
2306 return PARSE_TIME_OVER;
2307 if (!result && value)
2308 return PARSE_TIME_UNDER;
2309 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002310 return NULL;
2311}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002312
Emeric Brun39132b22010-01-04 14:57:24 +01002313/* this function converts the string starting at <text> to an unsigned int
2314 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002315 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002316 */
2317const char *parse_size_err(const char *text, unsigned *ret) {
2318 unsigned value = 0;
2319
Christopher Faulet82635a02020-12-11 09:30:45 +01002320 if (!isdigit((unsigned char)*text))
2321 return text;
2322
Emeric Brun39132b22010-01-04 14:57:24 +01002323 while (1) {
2324 unsigned int j;
2325
2326 j = *text - '0';
2327 if (j > 9)
2328 break;
2329 if (value > ~0U / 10)
2330 return text;
2331 value *= 10;
2332 if (value > (value + j))
2333 return text;
2334 value += j;
2335 text++;
2336 }
2337
2338 switch (*text) {
2339 case '\0':
2340 break;
2341 case 'K':
2342 case 'k':
2343 if (value > ~0U >> 10)
2344 return text;
2345 value = value << 10;
2346 break;
2347 case 'M':
2348 case 'm':
2349 if (value > ~0U >> 20)
2350 return text;
2351 value = value << 20;
2352 break;
2353 case 'G':
2354 case 'g':
2355 if (value > ~0U >> 30)
2356 return text;
2357 value = value << 30;
2358 break;
2359 default:
2360 return text;
2361 }
2362
Godbach58048a22015-01-28 17:36:16 +08002363 if (*text != '\0' && *++text != '\0')
2364 return text;
2365
Emeric Brun39132b22010-01-04 14:57:24 +01002366 *ret = value;
2367 return NULL;
2368}
2369
Willy Tarreau126d4062013-12-03 17:50:47 +01002370/*
2371 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002372 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002373 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002374 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002375 */
2376int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2377{
2378 int len;
2379 const char *p = source;
2380 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002381 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002382
2383 len = strlen(source);
2384 if (len % 2) {
2385 memprintf(err, "an even number of hex digit is expected");
2386 return 0;
2387 }
2388
2389 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002390
Willy Tarreau126d4062013-12-03 17:50:47 +01002391 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002392 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002393 if (!*binstr) {
2394 memprintf(err, "out of memory while loading string pattern");
2395 return 0;
2396 }
2397 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002398 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002399 else {
2400 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002401 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002402 len, *binstrlen);
2403 return 0;
2404 }
2405 alloc = 0;
2406 }
2407 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002408
2409 i = j = 0;
2410 while (j < len) {
2411 if (!ishex(p[i++]))
2412 goto bad_input;
2413 if (!ishex(p[i++]))
2414 goto bad_input;
2415 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2416 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002417 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002418
2419bad_input:
2420 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002421 if (alloc) {
2422 free(*binstr);
2423 *binstr = NULL;
2424 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002425 return 0;
2426}
2427
Willy Tarreau946ba592009-05-10 15:41:18 +02002428/* copies at most <n> characters from <src> and always terminates with '\0' */
2429char *my_strndup(const char *src, int n)
2430{
2431 int len = 0;
2432 char *ret;
2433
2434 while (len < n && src[len])
2435 len++;
2436
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002437 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002438 if (!ret)
2439 return ret;
2440 memcpy(ret, src, len);
2441 ret[len] = '\0';
2442 return ret;
2443}
2444
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002445/*
2446 * search needle in haystack
2447 * returns the pointer if found, returns NULL otherwise
2448 */
2449const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2450{
2451 const void *c = NULL;
2452 unsigned char f;
2453
2454 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2455 return NULL;
2456
2457 f = *(char *)needle;
2458 c = haystack;
2459 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2460 if ((haystacklen - (c - haystack)) < needlelen)
2461 return NULL;
2462
2463 if (memcmp(c, needle, needlelen) == 0)
2464 return c;
2465 ++c;
2466 }
2467 return NULL;
2468}
2469
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002470/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002471size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2472{
2473 size_t ret = 0;
2474
2475 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2476 str++;
2477 ret++;
2478 }
2479 return ret;
2480}
2481
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002482/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002483size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2484{
2485 size_t ret = 0;
2486
2487 while (ret < len) {
2488 if(memchr(reject, *((int *)str), rejectlen))
2489 return ret;
2490 str++;
2491 ret++;
2492 }
2493 return ret;
2494}
2495
Willy Tarreau482b00d2009-10-04 22:48:42 +02002496/* This function returns the first unused key greater than or equal to <key> in
2497 * ID tree <root>. Zero is returned if no place is found.
2498 */
2499unsigned int get_next_id(struct eb_root *root, unsigned int key)
2500{
2501 struct eb32_node *used;
2502
2503 do {
2504 used = eb32_lookup_ge(root, key);
2505 if (!used || used->key > key)
2506 return key; /* key is available */
2507 key++;
2508 } while (key);
2509 return key;
2510}
2511
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002512/* dump the full tree to <file> in DOT format for debugging purposes. Will
2513 * optionally highlight node <subj> if found, depending on operation <op> :
2514 * 0 : nothing
2515 * >0 : insertion, node/leaf are surrounded in red
2516 * <0 : removal, node/leaf are dashed with no background
2517 * Will optionally add "desc" as a label on the graph if set and non-null.
2518 */
2519void 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 +01002520{
2521 struct eb32sc_node *node;
2522 unsigned long scope = -1;
2523
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002524 fprintf(file, "digraph ebtree {\n");
2525
2526 if (desc && *desc) {
2527 fprintf(file,
2528 " fontname=\"fixed\";\n"
2529 " fontsize=8;\n"
2530 " label=\"%s\";\n", desc);
2531 }
2532
Willy Tarreaued3cda02017-11-15 15:04:05 +01002533 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002534 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2535 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002536 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2537 );
2538
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002539 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002540 (long)eb_root_to_node(root),
2541 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002542 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2543
2544 node = eb32sc_first(root, scope);
2545 while (node) {
2546 if (node->node.node_p) {
2547 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002548 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2549 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2550 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002551
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002552 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002553 (long)node,
2554 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002555 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002556
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002557 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002558 (long)node,
2559 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002560 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2561
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002562 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002563 (long)node,
2564 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002565 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2566 }
2567
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002568 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2569 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2570 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002571
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002572 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002573 (long)node,
2574 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002575 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002576 node = eb32sc_next(node, scope);
2577 }
2578 fprintf(file, "}\n");
2579}
2580
Willy Tarreau348238b2010-01-18 15:05:57 +01002581/* This function compares a sample word possibly followed by blanks to another
2582 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2583 * otherwise zero. This intends to be used when checking HTTP headers for some
2584 * values. Note that it validates a word followed only by blanks but does not
2585 * validate a word followed by blanks then other chars.
2586 */
2587int word_match(const char *sample, int slen, const char *word, int wlen)
2588{
2589 if (slen < wlen)
2590 return 0;
2591
2592 while (wlen) {
2593 char c = *sample ^ *word;
2594 if (c && c != ('A' ^ 'a'))
2595 return 0;
2596 sample++;
2597 word++;
2598 slen--;
2599 wlen--;
2600 }
2601
2602 while (slen) {
2603 if (*sample != ' ' && *sample != '\t')
2604 return 0;
2605 sample++;
2606 slen--;
2607 }
2608 return 1;
2609}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002610
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002611/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2612 * is particularly fast because it avoids expensive operations such as
2613 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002614 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002615 */
2616unsigned int inetaddr_host(const char *text)
2617{
2618 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2619 register unsigned int dig100, dig10, dig1;
2620 int s;
2621 const char *p, *d;
2622
2623 dig1 = dig10 = dig100 = ascii_zero;
2624 s = 24;
2625
2626 p = text;
2627 while (1) {
2628 if (((unsigned)(*p - '0')) <= 9) {
2629 p++;
2630 continue;
2631 }
2632
2633 /* here, we have a complete byte between <text> and <p> (exclusive) */
2634 if (p == text)
2635 goto end;
2636
2637 d = p - 1;
2638 dig1 |= (unsigned int)(*d << s);
2639 if (d == text)
2640 goto end;
2641
2642 d--;
2643 dig10 |= (unsigned int)(*d << s);
2644 if (d == text)
2645 goto end;
2646
2647 d--;
2648 dig100 |= (unsigned int)(*d << s);
2649 end:
2650 if (!s || *p != '.')
2651 break;
2652
2653 s -= 8;
2654 text = ++p;
2655 }
2656
2657 dig100 -= ascii_zero;
2658 dig10 -= ascii_zero;
2659 dig1 -= ascii_zero;
2660 return ((dig100 * 10) + dig10) * 10 + dig1;
2661}
2662
2663/*
2664 * Idem except the first unparsed character has to be passed in <stop>.
2665 */
2666unsigned int inetaddr_host_lim(const char *text, const char *stop)
2667{
2668 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2669 register unsigned int dig100, dig10, dig1;
2670 int s;
2671 const char *p, *d;
2672
2673 dig1 = dig10 = dig100 = ascii_zero;
2674 s = 24;
2675
2676 p = text;
2677 while (1) {
2678 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2679 p++;
2680 continue;
2681 }
2682
2683 /* here, we have a complete byte between <text> and <p> (exclusive) */
2684 if (p == text)
2685 goto end;
2686
2687 d = p - 1;
2688 dig1 |= (unsigned int)(*d << s);
2689 if (d == text)
2690 goto end;
2691
2692 d--;
2693 dig10 |= (unsigned int)(*d << s);
2694 if (d == text)
2695 goto end;
2696
2697 d--;
2698 dig100 |= (unsigned int)(*d << s);
2699 end:
2700 if (!s || p == stop || *p != '.')
2701 break;
2702
2703 s -= 8;
2704 text = ++p;
2705 }
2706
2707 dig100 -= ascii_zero;
2708 dig10 -= ascii_zero;
2709 dig1 -= ascii_zero;
2710 return ((dig100 * 10) + dig10) * 10 + dig1;
2711}
2712
2713/*
2714 * Idem except the pointer to first unparsed byte is returned into <ret> which
2715 * must not be NULL.
2716 */
Willy Tarreau74172752010-10-15 23:21:42 +02002717unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002718{
2719 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2720 register unsigned int dig100, dig10, dig1;
2721 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002722 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002723
2724 dig1 = dig10 = dig100 = ascii_zero;
2725 s = 24;
2726
2727 p = text;
2728 while (1) {
2729 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2730 p++;
2731 continue;
2732 }
2733
2734 /* here, we have a complete byte between <text> and <p> (exclusive) */
2735 if (p == text)
2736 goto end;
2737
2738 d = p - 1;
2739 dig1 |= (unsigned int)(*d << s);
2740 if (d == text)
2741 goto end;
2742
2743 d--;
2744 dig10 |= (unsigned int)(*d << s);
2745 if (d == text)
2746 goto end;
2747
2748 d--;
2749 dig100 |= (unsigned int)(*d << s);
2750 end:
2751 if (!s || p == stop || *p != '.')
2752 break;
2753
2754 s -= 8;
2755 text = ++p;
2756 }
2757
2758 *ret = p;
2759 dig100 -= ascii_zero;
2760 dig10 -= ascii_zero;
2761 dig1 -= ascii_zero;
2762 return ((dig100 * 10) + dig10) * 10 + dig1;
2763}
2764
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002765/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2766 * or the number of chars read in case of success. Maybe this could be replaced
2767 * by one of the functions above. Also, apparently this function does not support
2768 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002769 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002770 */
2771int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2772{
2773 const char *addr;
2774 int saw_digit, octets, ch;
2775 u_char tmp[4], *tp;
2776 const char *cp = buf;
2777
2778 saw_digit = 0;
2779 octets = 0;
2780 *(tp = tmp) = 0;
2781
2782 for (addr = buf; addr - buf < len; addr++) {
2783 unsigned char digit = (ch = *addr) - '0';
2784
2785 if (digit > 9 && ch != '.')
2786 break;
2787
2788 if (digit <= 9) {
2789 u_int new = *tp * 10 + digit;
2790
2791 if (new > 255)
2792 return 0;
2793
2794 *tp = new;
2795
2796 if (!saw_digit) {
2797 if (++octets > 4)
2798 return 0;
2799 saw_digit = 1;
2800 }
2801 } else if (ch == '.' && saw_digit) {
2802 if (octets == 4)
2803 return 0;
2804
2805 *++tp = 0;
2806 saw_digit = 0;
2807 } else
2808 return 0;
2809 }
2810
2811 if (octets < 4)
2812 return 0;
2813
2814 memcpy(&dst->s_addr, tmp, 4);
2815 return addr - cp;
2816}
2817
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002818/* This function converts the string in <buf> of the len <len> to
2819 * struct in6_addr <dst> which must be allocated by the caller.
2820 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002821 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002822 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002823int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2824{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002825 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002826 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002827
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002828 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002829 return 0;
2830
2831 memcpy(null_term_ip6, buf, len);
2832 null_term_ip6[len] = '\0';
2833
Willy Tarreau075415a2013-12-12 11:29:39 +01002834 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002835 return 0;
2836
Willy Tarreau075415a2013-12-12 11:29:39 +01002837 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002838 return 1;
2839}
2840
Willy Tarreauacf95772010-06-14 19:09:21 +02002841/* To be used to quote config arg positions. Returns the short string at <ptr>
2842 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2843 * if ptr is NULL or empty. The string is locally allocated.
2844 */
2845const char *quote_arg(const char *ptr)
2846{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002847 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002848 int i;
2849
2850 if (!ptr || !*ptr)
2851 return "end of line";
2852 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002853 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002854 val[i] = *ptr++;
2855 val[i++] = '\'';
2856 val[i] = '\0';
2857 return val;
2858}
2859
Willy Tarreau5b180202010-07-18 10:40:48 +02002860/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2861int get_std_op(const char *str)
2862{
2863 int ret = -1;
2864
2865 if (*str == 'e' && str[1] == 'q')
2866 ret = STD_OP_EQ;
2867 else if (*str == 'n' && str[1] == 'e')
2868 ret = STD_OP_NE;
2869 else if (*str == 'l') {
2870 if (str[1] == 'e') ret = STD_OP_LE;
2871 else if (str[1] == 't') ret = STD_OP_LT;
2872 }
2873 else if (*str == 'g') {
2874 if (str[1] == 'e') ret = STD_OP_GE;
2875 else if (str[1] == 't') ret = STD_OP_GT;
2876 }
2877
2878 if (ret == -1 || str[2] != '\0')
2879 return -1;
2880 return ret;
2881}
2882
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002883/* hash a 32-bit integer to another 32-bit integer */
2884unsigned int full_hash(unsigned int a)
2885{
2886 return __full_hash(a);
2887}
2888
Willy Tarreauf3241112019-02-26 09:56:22 +01002889/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2890 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2891 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2892 * a popcount variant and is described here :
2893 * https://graphics.stanford.edu/~seander/bithacks.html
2894 */
2895unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2896{
2897 unsigned long a, b, c, d;
2898 unsigned int s;
2899 unsigned int t;
2900
2901 a = m - ((m >> 1) & ~0UL/3);
2902 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2903 c = (b + (b >> 4)) & ~0UL/0x11;
2904 d = (c + (c >> 8)) & ~0UL/0x101;
2905
2906 r++; // make r be 1..64
2907
2908 t = 0;
2909 s = LONGBITS;
2910 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002911 unsigned long d2 = (d >> 16) >> 16;
2912 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002913 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2914 }
2915
2916 t = (d >> (s - 16)) & 0xff;
2917 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2918 t = (c >> (s - 8)) & 0xf;
2919 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2920 t = (b >> (s - 4)) & 0x7;
2921 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2922 t = (a >> (s - 2)) & 0x3;
2923 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2924 t = (m >> (s - 1)) & 0x1;
2925 s -= ((t - r) & 256) >> 8;
2926
2927 return s - 1;
2928}
2929
2930/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2931 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2932 * using mask_prep_rank_map() below.
2933 */
2934unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2935 unsigned long a, unsigned long b,
2936 unsigned long c, unsigned long d)
2937{
2938 unsigned int s;
2939 unsigned int t;
2940
2941 r++; // make r be 1..64
2942
2943 t = 0;
2944 s = LONGBITS;
2945 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002946 unsigned long d2 = (d >> 16) >> 16;
2947 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002948 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2949 }
2950
2951 t = (d >> (s - 16)) & 0xff;
2952 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2953 t = (c >> (s - 8)) & 0xf;
2954 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2955 t = (b >> (s - 4)) & 0x7;
2956 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2957 t = (a >> (s - 2)) & 0x3;
2958 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2959 t = (m >> (s - 1)) & 0x1;
2960 s -= ((t - r) & 256) >> 8;
2961
2962 return s - 1;
2963}
2964
2965/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2966 * above.
2967 */
2968void mask_prep_rank_map(unsigned long m,
2969 unsigned long *a, unsigned long *b,
2970 unsigned long *c, unsigned long *d)
2971{
2972 *a = m - ((m >> 1) & ~0UL/3);
2973 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2974 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2975 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2976}
2977
David du Colombier4f92d322011-03-24 11:09:31 +01002978/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002979 * otherwise zero. Note that <addr> may not necessarily be aligned
2980 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002981 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002982int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002983{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002984 struct in_addr addr_copy;
2985
2986 memcpy(&addr_copy, addr, sizeof(addr_copy));
2987 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002988}
2989
2990/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002991 * otherwise zero. Note that <addr> may not necessarily be aligned
2992 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002993 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002994int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002995{
2996 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002997 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002998
Willy Tarreaueec1d382016-07-13 11:59:39 +02002999 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003000 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003001 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003002 (((int *)net)[i] & ((int *)mask)[i]))
3003 return 0;
3004 return 1;
3005}
3006
3007/* RFC 4291 prefix */
3008const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3009 0x00, 0x00, 0x00, 0x00,
3010 0x00, 0x00, 0xFF, 0xFF };
3011
Joseph Herlant32b83272018-11-15 11:58:28 -08003012/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003013 * Input and output may overlap.
3014 */
David du Colombier4f92d322011-03-24 11:09:31 +01003015void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3016{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003017 struct in_addr tmp_addr;
3018
3019 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003020 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003021 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003022}
3023
Joseph Herlant32b83272018-11-15 11:58:28 -08003024/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003025 * Return true if conversion is possible and false otherwise.
3026 */
3027int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3028{
3029 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3030 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3031 sizeof(struct in_addr));
3032 return 1;
3033 }
3034
3035 return 0;
3036}
3037
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003038/* compare two struct sockaddr_storage and return:
3039 * 0 (true) if the addr is the same in both
3040 * 1 (false) if the addr is not the same in both
3041 * -1 (unable) if one of the addr is not AF_INET*
3042 */
3043int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3044{
3045 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3046 return -1;
3047
3048 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3049 return -1;
3050
3051 if (ss1->ss_family != ss2->ss_family)
3052 return 1;
3053
3054 switch (ss1->ss_family) {
3055 case AF_INET:
3056 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3057 &((struct sockaddr_in *)ss2)->sin_addr,
3058 sizeof(struct in_addr)) != 0;
3059 case AF_INET6:
3060 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3061 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3062 sizeof(struct in6_addr)) != 0;
3063 }
3064
3065 return 1;
3066}
3067
Baptiste Assmann08396c82016-01-31 00:27:17 +01003068/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003069 * The caller must allocate and clear <dest> before calling.
3070 * The source must be in either AF_INET or AF_INET6 family, or the destination
3071 * address will be undefined. If the destination address used to hold a port,
3072 * it is preserved, so that this function can be used to switch to another
3073 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003074 */
3075struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3076{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003077 int prev_port;
3078
3079 prev_port = get_net_port(dest);
3080 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003081 dest->ss_family = source->ss_family;
3082
3083 /* copy new addr and apply it */
3084 switch (source->ss_family) {
3085 case AF_INET:
3086 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003087 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003088 break;
3089 case AF_INET6:
3090 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 +01003091 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003092 break;
3093 }
3094
3095 return dest;
3096}
3097
William Lallemand421f5b52012-02-06 18:15:57 +01003098char *human_time(int t, short hz_div) {
3099 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3100 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003101 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003102 int cnt=2; // print two numbers
3103
3104 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003105 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003106 return rv;
3107 }
3108
3109 if (unlikely(hz_div > 1))
3110 t /= hz_div;
3111
3112 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003113 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003114 cnt--;
3115 }
3116
3117 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003118 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003119 cnt--;
3120 }
3121
3122 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003123 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003124 cnt--;
3125 }
3126
3127 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003128 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003129
3130 return rv;
3131}
3132
3133const char *monthname[12] = {
3134 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3135 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3136};
3137
3138/* date2str_log: write a date in the format :
3139 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3140 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3141 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3142 *
3143 * without using sprintf. return a pointer to the last char written (\0) or
3144 * NULL if there isn't enough space.
3145 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003146char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003147{
3148
3149 if (size < 25) /* the size is fixed: 24 chars + \0 */
3150 return NULL;
3151
3152 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003153 if (!dst)
3154 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003155 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003156
William Lallemand421f5b52012-02-06 18:15:57 +01003157 memcpy(dst, monthname[tm->tm_mon], 3); // month
3158 dst += 3;
3159 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003160
William Lallemand421f5b52012-02-06 18:15:57 +01003161 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003162 if (!dst)
3163 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003164 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003165
William Lallemand421f5b52012-02-06 18:15:57 +01003166 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003167 if (!dst)
3168 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003169 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003170
William Lallemand421f5b52012-02-06 18:15:57 +01003171 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003172 if (!dst)
3173 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003174 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003175
William Lallemand421f5b52012-02-06 18:15:57 +01003176 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003177 if (!dst)
3178 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003179 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003180
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003181 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003182 if (!dst)
3183 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003184 *dst = '\0';
3185
3186 return dst;
3187}
3188
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003189/* Base year used to compute leap years */
3190#define TM_YEAR_BASE 1900
3191
3192/* Return the difference in seconds between two times (leap seconds are ignored).
3193 * Retrieved from glibc 2.18 source code.
3194 */
3195static int my_tm_diff(const struct tm *a, const struct tm *b)
3196{
3197 /* Compute intervening leap days correctly even if year is negative.
3198 * Take care to avoid int overflow in leap day calculations,
3199 * but it's OK to assume that A and B are close to each other.
3200 */
3201 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3202 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3203 int a100 = a4 / 25 - (a4 % 25 < 0);
3204 int b100 = b4 / 25 - (b4 % 25 < 0);
3205 int a400 = a100 >> 2;
3206 int b400 = b100 >> 2;
3207 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3208 int years = a->tm_year - b->tm_year;
3209 int days = (365 * years + intervening_leap_days
3210 + (a->tm_yday - b->tm_yday));
3211 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3212 + (a->tm_min - b->tm_min))
3213 + (a->tm_sec - b->tm_sec));
3214}
3215
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003216/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003217 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003218 * The string returned has the same format as returned by strftime(... "%z", tm).
3219 * Offsets are kept in an internal cache for better performances.
3220 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003221const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003222{
3223 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003224 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003225
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003226 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003227 struct tm tm_gmt;
3228 int diff;
3229 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003230
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003231 /* Pretend DST not active if its status is unknown */
3232 if (isdst < 0)
3233 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003234
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003235 /* Fetch the offset and initialize it if needed */
3236 gmt_offset = gmt_offsets[isdst & 0x01];
3237 if (unlikely(!*gmt_offset)) {
3238 get_gmtime(t, &tm_gmt);
3239 diff = my_tm_diff(tm, &tm_gmt);
3240 if (diff < 0) {
3241 diff = -diff;
3242 *gmt_offset = '-';
3243 } else {
3244 *gmt_offset = '+';
3245 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003246 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003247 diff /= 60; /* Convert to minutes */
3248 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3249 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003250
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003251 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003252}
3253
William Lallemand421f5b52012-02-06 18:15:57 +01003254/* gmt2str_log: write a date in the format :
3255 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3256 * return a pointer to the last char written (\0) or
3257 * NULL if there isn't enough space.
3258 */
3259char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3260{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003261 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003262 return NULL;
3263
3264 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003265 if (!dst)
3266 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003267 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003268
William Lallemand421f5b52012-02-06 18:15:57 +01003269 memcpy(dst, monthname[tm->tm_mon], 3); // month
3270 dst += 3;
3271 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003272
William Lallemand421f5b52012-02-06 18:15:57 +01003273 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003274 if (!dst)
3275 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003276 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003277
William Lallemand421f5b52012-02-06 18:15:57 +01003278 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003279 if (!dst)
3280 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003281 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003282
William Lallemand421f5b52012-02-06 18:15:57 +01003283 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003284 if (!dst)
3285 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003286 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003287
William Lallemand421f5b52012-02-06 18:15:57 +01003288 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003289 if (!dst)
3290 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003291 *dst++ = ' ';
3292 *dst++ = '+';
3293 *dst++ = '0';
3294 *dst++ = '0';
3295 *dst++ = '0';
3296 *dst++ = '0';
3297 *dst = '\0';
3298
3299 return dst;
3300}
3301
Yuxans Yao4e25b012012-10-19 10:36:09 +08003302/* localdate2str_log: write a date in the format :
3303 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003304 * Both t and tm must represent the same time.
3305 * return a pointer to the last char written (\0) or
3306 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003307 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003308char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003309{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003310 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003311 if (size < 27) /* the size is fixed: 26 chars + \0 */
3312 return NULL;
3313
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003314 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003315
Yuxans Yao4e25b012012-10-19 10:36:09 +08003316 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003317 if (!dst)
3318 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003319 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003320
Yuxans Yao4e25b012012-10-19 10:36:09 +08003321 memcpy(dst, monthname[tm->tm_mon], 3); // month
3322 dst += 3;
3323 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003324
Yuxans Yao4e25b012012-10-19 10:36:09 +08003325 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003326 if (!dst)
3327 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003328 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003329
Yuxans Yao4e25b012012-10-19 10:36:09 +08003330 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003331 if (!dst)
3332 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003333 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003334
Yuxans Yao4e25b012012-10-19 10:36:09 +08003335 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003336 if (!dst)
3337 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003338 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003339
Yuxans Yao4e25b012012-10-19 10:36:09 +08003340 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003341 if (!dst)
3342 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003343 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003344
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003345 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003346 dst += 5;
3347 *dst = '\0';
3348
3349 return dst;
3350}
3351
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003352/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3353 * It is meant as a portable replacement for timegm() for use with valid inputs.
3354 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3355 */
3356time_t my_timegm(const struct tm *tm)
3357{
3358 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3359 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3360 * sum of the extra N days for elapsed months. The sum of all these N
3361 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3362 * in a 5-bit word. This means that with 60 bits we can represent a
3363 * matrix of all these values at once, which is fast and efficient to
3364 * access. The extra February day for leap years is not counted here.
3365 *
3366 * Jan : none = 0 (0)
3367 * Feb : Jan = 3 (3)
3368 * Mar : Jan..Feb = 3 (3 + 0)
3369 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3370 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3371 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3372 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3373 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3374 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3375 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3376 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3377 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3378 */
3379 uint64_t extra =
3380 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3381 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3382 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3383 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3384
3385 unsigned int y = tm->tm_year + 1900;
3386 unsigned int m = tm->tm_mon;
3387 unsigned long days = 0;
3388
3389 /* days since 1/1/1970 for full years */
3390 days += days_since_zero(y) - days_since_zero(1970);
3391
3392 /* days for full months in the current year */
3393 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3394
3395 /* count + 1 after March for leap years. A leap year is a year multiple
3396 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3397 * is leap, 1900 isn't, 1904 is.
3398 */
3399 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3400 days++;
3401
3402 days += tm->tm_mday - 1;
3403 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3404}
3405
Thierry Fournier93127942016-01-20 18:49:45 +01003406/* This function check a char. It returns true and updates
3407 * <date> and <len> pointer to the new position if the
3408 * character is found.
3409 */
3410static inline int parse_expect_char(const char **date, int *len, char c)
3411{
3412 if (*len < 1 || **date != c)
3413 return 0;
3414 (*len)--;
3415 (*date)++;
3416 return 1;
3417}
3418
3419/* This function expects a string <str> of len <l>. It return true and updates.
3420 * <date> and <len> if the string matches, otherwise, it returns false.
3421 */
3422static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3423{
3424 if (*len < l || strncmp(*date, str, l) != 0)
3425 return 0;
3426 (*len) -= l;
3427 (*date) += l;
3428 return 1;
3429}
3430
3431/* This macro converts 3 chars name in integer. */
3432#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3433
3434/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3435 * / %x54.75.65 ; "Tue", case-sensitive
3436 * / %x57.65.64 ; "Wed", case-sensitive
3437 * / %x54.68.75 ; "Thu", case-sensitive
3438 * / %x46.72.69 ; "Fri", case-sensitive
3439 * / %x53.61.74 ; "Sat", case-sensitive
3440 * / %x53.75.6E ; "Sun", case-sensitive
3441 *
3442 * This array must be alphabetically sorted
3443 */
3444static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3445{
3446 if (*len < 3)
3447 return 0;
3448 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3449 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3450 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3451 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3452 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3453 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3454 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3455 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3456 default: return 0;
3457 }
3458 *len -= 3;
3459 *date += 3;
3460 return 1;
3461}
3462
3463/* month = %x4A.61.6E ; "Jan", case-sensitive
3464 * / %x46.65.62 ; "Feb", case-sensitive
3465 * / %x4D.61.72 ; "Mar", case-sensitive
3466 * / %x41.70.72 ; "Apr", case-sensitive
3467 * / %x4D.61.79 ; "May", case-sensitive
3468 * / %x4A.75.6E ; "Jun", case-sensitive
3469 * / %x4A.75.6C ; "Jul", case-sensitive
3470 * / %x41.75.67 ; "Aug", case-sensitive
3471 * / %x53.65.70 ; "Sep", case-sensitive
3472 * / %x4F.63.74 ; "Oct", case-sensitive
3473 * / %x4E.6F.76 ; "Nov", case-sensitive
3474 * / %x44.65.63 ; "Dec", case-sensitive
3475 *
3476 * This array must be alphabetically sorted
3477 */
3478static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3479{
3480 if (*len < 3)
3481 return 0;
3482 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3483 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3484 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3485 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3486 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3487 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3488 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3489 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3490 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3491 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3492 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3493 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3494 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3495 default: return 0;
3496 }
3497 *len -= 3;
3498 *date += 3;
3499 return 1;
3500}
3501
3502/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3503 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3504 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3505 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3506 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3507 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3508 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3509 *
3510 * This array must be alphabetically sorted
3511 */
3512static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3513{
3514 if (*len < 6) /* Minimum length. */
3515 return 0;
3516 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3517 case STR2I3('M','o','n'):
3518 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3519 tm->tm_wday = 1;
3520 return 1;
3521 case STR2I3('T','u','e'):
3522 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3523 tm->tm_wday = 2;
3524 return 1;
3525 case STR2I3('W','e','d'):
3526 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3527 tm->tm_wday = 3;
3528 return 1;
3529 case STR2I3('T','h','u'):
3530 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3531 tm->tm_wday = 4;
3532 return 1;
3533 case STR2I3('F','r','i'):
3534 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3535 tm->tm_wday = 5;
3536 return 1;
3537 case STR2I3('S','a','t'):
3538 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3539 tm->tm_wday = 6;
3540 return 1;
3541 case STR2I3('S','u','n'):
3542 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3543 tm->tm_wday = 7;
3544 return 1;
3545 }
3546 return 0;
3547}
3548
3549/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3550static inline int parse_digit(const char **date, int *len, int *digit)
3551{
3552 if (*len < 1 || **date < '0' || **date > '9')
3553 return 0;
3554 *digit = (**date - '0');
3555 (*date)++;
3556 (*len)--;
3557 return 1;
3558}
3559
3560/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3561static inline int parse_2digit(const char **date, int *len, int *digit)
3562{
3563 int value;
3564
3565 RET0_UNLESS(parse_digit(date, len, &value));
3566 (*digit) = value * 10;
3567 RET0_UNLESS(parse_digit(date, len, &value));
3568 (*digit) += value;
3569
3570 return 1;
3571}
3572
3573/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3574static inline int parse_4digit(const char **date, int *len, int *digit)
3575{
3576 int value;
3577
3578 RET0_UNLESS(parse_digit(date, len, &value));
3579 (*digit) = value * 1000;
3580
3581 RET0_UNLESS(parse_digit(date, len, &value));
3582 (*digit) += value * 100;
3583
3584 RET0_UNLESS(parse_digit(date, len, &value));
3585 (*digit) += value * 10;
3586
3587 RET0_UNLESS(parse_digit(date, len, &value));
3588 (*digit) += value;
3589
3590 return 1;
3591}
3592
3593/* time-of-day = hour ":" minute ":" second
3594 * ; 00:00:00 - 23:59:60 (leap second)
3595 *
3596 * hour = 2DIGIT
3597 * minute = 2DIGIT
3598 * second = 2DIGIT
3599 */
3600static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3601{
3602 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3603 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3604 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3605 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3606 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3607 return 1;
3608}
3609
3610/* From RFC7231
3611 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3612 *
3613 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3614 * ; fixed length/zone/capitalization subset of the format
3615 * ; see Section 3.3 of [RFC5322]
3616 *
3617 *
3618 * date1 = day SP month SP year
3619 * ; e.g., 02 Jun 1982
3620 *
3621 * day = 2DIGIT
3622 * year = 4DIGIT
3623 *
3624 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3625 *
3626 * time-of-day = hour ":" minute ":" second
3627 * ; 00:00:00 - 23:59:60 (leap second)
3628 *
3629 * hour = 2DIGIT
3630 * minute = 2DIGIT
3631 * second = 2DIGIT
3632 *
3633 * DIGIT = decimal 0-9
3634 */
3635int parse_imf_date(const char *date, int len, struct tm *tm)
3636{
David Carlier327298c2016-11-20 10:42:38 +00003637 /* tm_gmtoff, if present, ought to be zero'ed */
3638 memset(tm, 0, sizeof(*tm));
3639
Thierry Fournier93127942016-01-20 18:49:45 +01003640 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3641 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3642 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3643 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3644 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3645 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3646 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3647 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3648 tm->tm_year -= 1900;
3649 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3650 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3651 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3652 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3653 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003654 return 1;
3655}
3656
3657/* From RFC7231
3658 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3659 *
3660 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3661 * date2 = day "-" month "-" 2DIGIT
3662 * ; e.g., 02-Jun-82
3663 *
3664 * day = 2DIGIT
3665 */
3666int parse_rfc850_date(const char *date, int len, struct tm *tm)
3667{
3668 int year;
3669
David Carlier327298c2016-11-20 10:42:38 +00003670 /* tm_gmtoff, if present, ought to be zero'ed */
3671 memset(tm, 0, sizeof(*tm));
3672
Thierry Fournier93127942016-01-20 18:49:45 +01003673 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3674 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3675 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3676 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3677 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3678 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3679 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3680
3681 /* year = 2DIGIT
3682 *
3683 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3684 * two-digit year, MUST interpret a timestamp that appears to be more
3685 * than 50 years in the future as representing the most recent year in
3686 * the past that had the same last two digits.
3687 */
3688 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3689
3690 /* expect SP */
3691 if (!parse_expect_char(&date, &len, ' ')) {
3692 /* Maybe we have the date with 4 digits. */
3693 RET0_UNLESS(parse_2digit(&date, &len, &year));
3694 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3695 /* expect SP */
3696 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3697 } else {
3698 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3699 * tm_year is the number of year since 1900, so for +1900, we
3700 * do nothing, and for +2000, we add 100.
3701 */
3702 if (tm->tm_year <= 60)
3703 tm->tm_year += 100;
3704 }
3705
3706 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3707 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3708 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3709 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003710
3711 return 1;
3712}
3713
3714/* From RFC7231
3715 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3716 *
3717 * asctime-date = day-name SP date3 SP time-of-day SP year
3718 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3719 * ; e.g., Jun 2
3720 *
3721 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3722 * whitespace in an HTTP-date beyond that specifically included as SP in
3723 * the grammar.
3724 */
3725int parse_asctime_date(const char *date, int len, struct tm *tm)
3726{
David Carlier327298c2016-11-20 10:42:38 +00003727 /* tm_gmtoff, if present, ought to be zero'ed */
3728 memset(tm, 0, sizeof(*tm));
3729
Thierry Fournier93127942016-01-20 18:49:45 +01003730 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3731 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3732 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3733 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3734
3735 /* expect SP and 1DIGIT or 2DIGIT */
3736 if (parse_expect_char(&date, &len, ' '))
3737 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3738 else
3739 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3740
3741 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3742 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3743 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3744 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3745 tm->tm_year -= 1900;
3746 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003747 return 1;
3748}
3749
3750/* From RFC7231
3751 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3752 *
3753 * HTTP-date = IMF-fixdate / obs-date
3754 * obs-date = rfc850-date / asctime-date
3755 *
3756 * parses an HTTP date in the RFC format and is accepted
3757 * alternatives. <date> is the strinf containing the date,
3758 * len is the len of the string. <tm> is filled with the
3759 * parsed time. We must considers this time as GMT.
3760 */
3761int parse_http_date(const char *date, int len, struct tm *tm)
3762{
3763 if (parse_imf_date(date, len, tm))
3764 return 1;
3765
3766 if (parse_rfc850_date(date, len, tm))
3767 return 1;
3768
3769 if (parse_asctime_date(date, len, tm))
3770 return 1;
3771
3772 return 0;
3773}
3774
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003775/* Dynamically allocates a string of the proper length to hold the formatted
3776 * output. NULL is returned on error. The caller is responsible for freeing the
3777 * memory area using free(). The resulting string is returned in <out> if the
3778 * pointer is not NULL. A previous version of <out> might be used to build the
3779 * new string, and it will be freed before returning if it is not NULL, which
3780 * makes it possible to build complex strings from iterative calls without
3781 * having to care about freeing intermediate values, as in the example below :
3782 *
3783 * memprintf(&err, "invalid argument: '%s'", arg);
3784 * ...
3785 * memprintf(&err, "parser said : <%s>\n", *err);
3786 * ...
3787 * free(*err);
3788 *
3789 * This means that <err> must be initialized to NULL before first invocation.
3790 * The return value also holds the allocated string, which eases error checking
3791 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003792 * passed instead and it will be ignored. The returned message will then also
3793 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003794 *
3795 * It is also convenient to use it without any free except the last one :
3796 * err = NULL;
3797 * if (!fct1(err)) report(*err);
3798 * if (!fct2(err)) report(*err);
3799 * if (!fct3(err)) report(*err);
3800 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003801 *
3802 * memprintf relies on memvprintf. This last version can be called from any
3803 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003804 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003805char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003806{
3807 va_list args;
3808 char *ret = NULL;
3809 int allocated = 0;
3810 int needed = 0;
3811
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003812 if (!out)
3813 return NULL;
3814
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003815 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003816 char buf1;
3817
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003818 /* vsnprintf() will return the required length even when the
3819 * target buffer is NULL. We do this in a loop just in case
3820 * intermediate evaluations get wrong.
3821 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003822 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003823 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003824 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003825 if (needed < allocated) {
3826 /* Note: on Solaris 8, the first iteration always
3827 * returns -1 if allocated is zero, so we force a
3828 * retry.
3829 */
3830 if (!allocated)
3831 needed = 0;
3832 else
3833 break;
3834 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003835
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003836 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003837 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003838 } while (ret);
3839
3840 if (needed < 0) {
3841 /* an error was encountered */
3842 free(ret);
3843 ret = NULL;
3844 }
3845
3846 if (out) {
3847 free(*out);
3848 *out = ret;
3849 }
3850
3851 return ret;
3852}
William Lallemand421f5b52012-02-06 18:15:57 +01003853
Christopher Faulet93a518f2017-10-24 11:25:33 +02003854char *memprintf(char **out, const char *format, ...)
3855{
3856 va_list args;
3857 char *ret = NULL;
3858
3859 va_start(args, format);
3860 ret = memvprintf(out, format, args);
3861 va_end(args);
3862
3863 return ret;
3864}
3865
Willy Tarreau21c705b2012-09-14 11:40:36 +02003866/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3867 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003868 * freed by the caller. It also supports being passed a NULL which results in the same
3869 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003870 * Example of use :
3871 * parse(cmd, &err); (callee: memprintf(&err, ...))
3872 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3873 * free(err);
3874 */
3875char *indent_msg(char **out, int level)
3876{
3877 char *ret, *in, *p;
3878 int needed = 0;
3879 int lf = 0;
3880 int lastlf = 0;
3881 int len;
3882
Willy Tarreau70eec382012-10-10 08:56:47 +02003883 if (!out || !*out)
3884 return NULL;
3885
Willy Tarreau21c705b2012-09-14 11:40:36 +02003886 in = *out - 1;
3887 while ((in = strchr(in + 1, '\n')) != NULL) {
3888 lastlf = in - *out;
3889 lf++;
3890 }
3891
3892 if (!lf) /* single line, no LF, return it as-is */
3893 return *out;
3894
3895 len = strlen(*out);
3896
3897 if (lf == 1 && lastlf == len - 1) {
3898 /* single line, LF at end, strip it and return as-is */
3899 (*out)[lastlf] = 0;
3900 return *out;
3901 }
3902
3903 /* OK now we have at least one LF, we need to process the whole string
3904 * as a multi-line string. What we'll do :
3905 * - prefix with an LF if there is none
3906 * - add <level> spaces before each line
3907 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3908 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3909 */
3910
3911 needed = 1 + level * (lf + 1) + len + 1;
3912 p = ret = malloc(needed);
3913 in = *out;
3914
3915 /* skip initial LFs */
3916 while (*in == '\n')
3917 in++;
3918
3919 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3920 while (*in) {
3921 *p++ = '\n';
3922 memset(p, ' ', level);
3923 p += level;
3924 do {
3925 *p++ = *in++;
3926 } while (*in && *in != '\n');
3927 if (*in)
3928 in++;
3929 }
3930 *p = 0;
3931
3932 free(*out);
3933 *out = ret;
3934
3935 return ret;
3936}
3937
Willy Tarreaua2c99112019-08-21 13:17:37 +02003938/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3939 * and end of lines replaced with <eol> if not 0. The first line to indent has
3940 * to be indicated in <first> (starts at zero), so that it is possible to skip
3941 * indenting the first line if it has to be appended after an existing message.
3942 * Empty strings are never indented, and NULL strings are considered empty both
3943 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3944 * character, non-zero otherwise.
3945 */
3946int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3947{
3948 int bol, lf;
3949 int pfxlen = pfx ? strlen(pfx) : 0;
3950
3951 if (!in)
3952 return 0;
3953
3954 bol = 1;
3955 lf = 0;
3956 while (*in) {
3957 if (bol && pfxlen) {
3958 if (first > 0)
3959 first--;
3960 else
3961 b_putblk(out, pfx, pfxlen);
3962 bol = 0;
3963 }
3964
3965 lf = (*in == '\n');
3966 bol |= lf;
3967 b_putchr(out, (lf && eol) ? eol : *in);
3968 in++;
3969 }
3970 return lf;
3971}
3972
Willy Tarreau9d22e562019-03-29 18:49:09 +01003973/* removes environment variable <name> from the environment as found in
3974 * environ. This is only provided as an alternative for systems without
3975 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003976 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003977 * <name> and to replace the matching pointers with the last pointer of
3978 * the array (since variables are not ordered).
3979 * It always returns 0 (success).
3980 */
3981int my_unsetenv(const char *name)
3982{
3983 extern char **environ;
3984 char **p = environ;
3985 int vars;
3986 int next;
3987 int len;
3988
3989 len = strlen(name);
3990 for (vars = 0; p[vars]; vars++)
3991 ;
3992 next = 0;
3993 while (next < vars) {
3994 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3995 next++;
3996 continue;
3997 }
3998 if (next < vars - 1)
3999 p[next] = p[vars - 1];
4000 p[--vars] = NULL;
4001 }
4002 return 0;
4003}
4004
Willy Tarreaudad36a32013-03-11 01:20:04 +01004005/* Convert occurrences of environment variables in the input string to their
4006 * corresponding value. A variable is identified as a series of alphanumeric
4007 * characters or underscores following a '$' sign. The <in> string must be
4008 * free()able. NULL returns NULL. The resulting string might be reallocated if
4009 * some expansion is made. Variable names may also be enclosed into braces if
4010 * needed (eg: to concatenate alphanum characters).
4011 */
4012char *env_expand(char *in)
4013{
4014 char *txt_beg;
4015 char *out;
4016 char *txt_end;
4017 char *var_beg;
4018 char *var_end;
4019 char *value;
4020 char *next;
4021 int out_len;
4022 int val_len;
4023
4024 if (!in)
4025 return in;
4026
4027 value = out = NULL;
4028 out_len = 0;
4029
4030 txt_beg = in;
4031 do {
4032 /* look for next '$' sign in <in> */
4033 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4034
4035 if (!*txt_end && !out) /* end and no expansion performed */
4036 return in;
4037
4038 val_len = 0;
4039 next = txt_end;
4040 if (*txt_end == '$') {
4041 char save;
4042
4043 var_beg = txt_end + 1;
4044 if (*var_beg == '{')
4045 var_beg++;
4046
4047 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004048 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004049 var_end++;
4050 }
4051
4052 next = var_end;
4053 if (*var_end == '}' && (var_beg > txt_end + 1))
4054 next++;
4055
4056 /* get value of the variable name at this location */
4057 save = *var_end;
4058 *var_end = '\0';
4059 value = getenv(var_beg);
4060 *var_end = save;
4061 val_len = value ? strlen(value) : 0;
4062 }
4063
Hubert Verstraete831962e2016-06-28 22:44:26 +02004064 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004065 if (txt_end > txt_beg) {
4066 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4067 out_len += txt_end - txt_beg;
4068 }
4069 if (val_len) {
4070 memcpy(out + out_len, value, val_len);
4071 out_len += val_len;
4072 }
4073 out[out_len] = 0;
4074 txt_beg = next;
4075 } while (*txt_beg);
4076
4077 /* here we know that <out> was allocated and that we don't need <in> anymore */
4078 free(in);
4079 return out;
4080}
4081
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004082
4083/* same as strstr() but case-insensitive and with limit length */
4084const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4085{
4086 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004087 unsigned int slen, plen;
4088 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004089
4090 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4091 return NULL;
4092
4093 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4094 return str1;
4095
4096 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4097 return NULL;
4098
4099 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 +02004100 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004101 start++;
4102 slen--;
4103 tmp1++;
4104
4105 if (tmp1 >= len_str1)
4106 return NULL;
4107
4108 /* if pattern longer than string */
4109 if (slen < plen)
4110 return NULL;
4111 }
4112
4113 sptr = start;
4114 pptr = (char *)str2;
4115
4116 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004117 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004118 sptr++;
4119 pptr++;
4120 tmp2++;
4121
4122 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4123 return start;
4124 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4125 return NULL;
4126 }
4127 }
4128 return NULL;
4129}
4130
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004131/* This function read the next valid utf8 char.
4132 * <s> is the byte srray to be decode, <len> is its length.
4133 * The function returns decoded char encoded like this:
4134 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4135 * are the length read. The decoded character is stored in <c>.
4136 */
4137unsigned char utf8_next(const char *s, int len, unsigned int *c)
4138{
4139 const unsigned char *p = (unsigned char *)s;
4140 int dec;
4141 unsigned char code = UTF8_CODE_OK;
4142
4143 if (len < 1)
4144 return UTF8_CODE_OK;
4145
4146 /* Check the type of UTF8 sequence
4147 *
4148 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4149 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4150 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4151 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4152 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4153 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4154 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4155 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4156 */
4157 switch (*p) {
4158 case 0x00 ... 0x7f:
4159 *c = *p;
4160 return UTF8_CODE_OK | 1;
4161
4162 case 0x80 ... 0xbf:
4163 *c = *p;
4164 return UTF8_CODE_BADSEQ | 1;
4165
4166 case 0xc0 ... 0xdf:
4167 if (len < 2) {
4168 *c = *p;
4169 return UTF8_CODE_BADSEQ | 1;
4170 }
4171 *c = *p & 0x1f;
4172 dec = 1;
4173 break;
4174
4175 case 0xe0 ... 0xef:
4176 if (len < 3) {
4177 *c = *p;
4178 return UTF8_CODE_BADSEQ | 1;
4179 }
4180 *c = *p & 0x0f;
4181 dec = 2;
4182 break;
4183
4184 case 0xf0 ... 0xf7:
4185 if (len < 4) {
4186 *c = *p;
4187 return UTF8_CODE_BADSEQ | 1;
4188 }
4189 *c = *p & 0x07;
4190 dec = 3;
4191 break;
4192
4193 case 0xf8 ... 0xfb:
4194 if (len < 5) {
4195 *c = *p;
4196 return UTF8_CODE_BADSEQ | 1;
4197 }
4198 *c = *p & 0x03;
4199 dec = 4;
4200 break;
4201
4202 case 0xfc ... 0xfd:
4203 if (len < 6) {
4204 *c = *p;
4205 return UTF8_CODE_BADSEQ | 1;
4206 }
4207 *c = *p & 0x01;
4208 dec = 5;
4209 break;
4210
4211 case 0xfe ... 0xff:
4212 default:
4213 *c = *p;
4214 return UTF8_CODE_BADSEQ | 1;
4215 }
4216
4217 p++;
4218
4219 while (dec > 0) {
4220
4221 /* need 0x10 for the 2 first bits */
4222 if ( ( *p & 0xc0 ) != 0x80 )
4223 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4224
4225 /* add data at char */
4226 *c = ( *c << 6 ) | ( *p & 0x3f );
4227
4228 dec--;
4229 p++;
4230 }
4231
4232 /* Check ovelong encoding.
4233 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4234 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4235 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4236 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004237 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004238 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4239 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4240 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4241 code |= UTF8_CODE_OVERLONG;
4242
4243 /* Check invalid UTF8 range. */
4244 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4245 (*c >= 0xfffe && *c <= 0xffff))
4246 code |= UTF8_CODE_INVRANGE;
4247
4248 return code | ((p-(unsigned char *)s)&0x0f);
4249}
4250
Maxime de Roucydc887852016-05-13 23:52:54 +02004251/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4252 * On failure : return 0 and <err> filled with an error message.
4253 * The caller is responsible for freeing the <err> and <str> copy
4254 * memory area using free()
4255 */
4256int list_append_word(struct list *li, const char *str, char **err)
4257{
4258 struct wordlist *wl;
4259
4260 wl = calloc(1, sizeof(*wl));
4261 if (!wl) {
4262 memprintf(err, "out of memory");
4263 goto fail_wl;
4264 }
4265
4266 wl->s = strdup(str);
4267 if (!wl->s) {
4268 memprintf(err, "out of memory");
4269 goto fail_wl_s;
4270 }
4271
4272 LIST_ADDQ(li, &wl->list);
4273
4274 return 1;
4275
4276fail_wl_s:
4277 free(wl->s);
4278fail_wl:
4279 free(wl);
4280 return 0;
4281}
4282
Willy Tarreau37101052019-05-20 16:48:20 +02004283/* indicates if a memory location may safely be read or not. The trick consists
4284 * in performing a harmless syscall using this location as an input and letting
4285 * the operating system report whether it's OK or not. For this we have the
4286 * stat() syscall, which will return EFAULT when the memory location supposed
4287 * to contain the file name is not readable. If it is readable it will then
4288 * either return 0 if the area contains an existing file name, or -1 with
4289 * another code. This must not be abused, and some audit systems might detect
4290 * this as abnormal activity. It's used only for unsafe dumps.
4291 */
4292int may_access(const void *ptr)
4293{
4294 struct stat buf;
4295
4296 if (stat(ptr, &buf) == 0)
4297 return 1;
4298 if (errno == EFAULT)
4299 return 0;
4300 return 1;
4301}
4302
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004303/* print a string of text buffer to <out>. The format is :
4304 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4305 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4306 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4307 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004308int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004309{
4310 unsigned char c;
4311 int ptr = 0;
4312
4313 while (buf[ptr] && ptr < bsize) {
4314 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004315 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004316 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004317 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004318 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004319 }
4320 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004321 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004322 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004323 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004324 switch (c) {
4325 case ' ': c = ' '; break;
4326 case '\t': c = 't'; break;
4327 case '\n': c = 'n'; break;
4328 case '\r': c = 'r'; break;
4329 case '\e': c = 'e'; break;
4330 case '\\': c = '\\'; break;
4331 case '=': c = '='; break;
4332 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004333 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004334 }
4335 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004336 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004337 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004338 out->area[out->data++] = '\\';
4339 out->area[out->data++] = 'x';
4340 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4341 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004342 }
4343 ptr++;
4344 }
4345
4346 return ptr;
4347}
4348
4349/* print a buffer in hexa.
4350 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4351 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004352int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004353{
4354 unsigned char c;
4355 int ptr = 0;
4356
4357 while (ptr < bsize) {
4358 c = buf[ptr];
4359
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004360 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004361 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004362 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4363 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004364
4365 ptr++;
4366 }
4367 return ptr;
4368}
4369
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004370/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4371 * prepending each line with prefix <pfx>. The output is *not* initialized.
4372 * The output will not wrap pas the buffer's end so it is more optimal if the
4373 * caller makes sure the buffer is aligned first. A trailing zero will always
4374 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004375 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4376 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004377 */
Willy Tarreau37101052019-05-20 16:48:20 +02004378void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004379{
4380 const unsigned char *d = buf;
4381 int i, j, start;
4382
4383 d = (const unsigned char *)(((unsigned long)buf) & -16);
4384 start = ((unsigned long)buf) & 15;
4385
4386 for (i = 0; i < start + len; i += 16) {
4387 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4388
Willy Tarreau37101052019-05-20 16:48:20 +02004389 // 0: unchecked, 1: checked safe, 2: danger
4390 unsafe = !!unsafe;
4391 if (unsafe && !may_access(d + i))
4392 unsafe = 2;
4393
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004394 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004395 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004396 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004397 else if (unsafe > 1)
4398 chunk_strcat(out, "** ");
4399 else
4400 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004401
4402 if (j == 7)
4403 chunk_strcat(out, "- ");
4404 }
4405 chunk_strcat(out, " ");
4406 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004407 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004408 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004409 else if (unsafe > 1)
4410 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004411 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004412 chunk_appendf(out, "%c", d[i + j]);
4413 else
4414 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004415 }
4416 chunk_strcat(out, "\n");
4417 }
4418}
4419
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004420/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4421 * enclosed in brackets after the address itself, formatted on 14 chars
4422 * including the "0x" prefix. This is meant to be used as a prefix for code
4423 * areas. For example:
4424 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4425 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4426 * is emitted. A NULL <pfx> will be considered empty.
4427 */
4428void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4429{
4430 int ok = 0;
4431 int i;
4432
4433 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4434
4435 for (i = 0; i < n; i++) {
4436 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4437 ok = may_access(addr + i);
4438 if (ok)
4439 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4440 else
4441 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4442 }
4443}
4444
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004445/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4446 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4447 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4448 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4449 * lines are respected within the limit of 70 output chars. Lines that are
4450 * continuation of a previous truncated line begin with "+" instead of " "
4451 * after the offset. The new pointer is returned.
4452 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004453int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004454 int *line, int ptr)
4455{
4456 int end;
4457 unsigned char c;
4458
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004459 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004460 if (end > out->size)
4461 return ptr;
4462
4463 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4464
4465 while (ptr < len && ptr < bsize) {
4466 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004467 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004468 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004469 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004470 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004471 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004472 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004473 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004474 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004475 switch (c) {
4476 case '\t': c = 't'; break;
4477 case '\n': c = 'n'; break;
4478 case '\r': c = 'r'; break;
4479 case '\e': c = 'e'; break;
4480 case '\\': c = '\\'; break;
4481 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004482 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004483 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004484 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004485 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004486 out->area[out->data++] = '\\';
4487 out->area[out->data++] = 'x';
4488 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4489 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004490 }
4491 if (buf[ptr++] == '\n') {
4492 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004493 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004494 *line = ptr;
4495 return ptr;
4496 }
4497 }
4498 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004499 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004500 return ptr;
4501}
4502
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004503/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004504 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4505 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004506 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004507void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4508 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004509{
Willy Tarreau73459792017-04-11 07:58:08 +02004510 unsigned int i;
4511 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004512
4513 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4514 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004515 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004516 for (j = 0; j < 8; j++) {
4517 if (b + j >= 0 && b + j < len)
4518 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4519 else
4520 fprintf(out, " ");
4521 }
4522
4523 if (b + j >= 0 && b + j < len)
4524 fputc('-', out);
4525 else
4526 fputc(' ', out);
4527
4528 for (j = 8; j < 16; j++) {
4529 if (b + j >= 0 && b + j < len)
4530 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4531 else
4532 fprintf(out, " ");
4533 }
4534
4535 fprintf(out, " ");
4536 for (j = 0; j < 16; j++) {
4537 if (b + j >= 0 && b + j < len) {
4538 if (isprint((unsigned char)buf[b + j]))
4539 fputc((unsigned char)buf[b + j], out);
4540 else
4541 fputc('.', out);
4542 }
4543 else
4544 fputc(' ', out);
4545 }
4546 fputc('\n', out);
4547 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004548}
4549
Willy Tarreaubb869862020-04-16 10:52:41 +02004550/* Tries to report the executable path name on platforms supporting this. If
4551 * not found or not possible, returns NULL.
4552 */
4553const char *get_exec_path()
4554{
4555 const char *ret = NULL;
4556
4557#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4558 long execfn = getauxval(AT_EXECFN);
4559
4560 if (execfn && execfn != ENOENT)
4561 ret = (const char *)execfn;
4562#endif
4563 return ret;
4564}
4565
Baruch Siache1651b22020-07-24 07:52:20 +03004566#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004567/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4568 * also returns the symbol size in <size>, otherwise returns 0 there.
4569 */
4570static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4571{
4572 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004573#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004574 const ElfW(Sym) *sym;
4575
4576 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4577 if (ret)
4578 *size = sym ? sym->st_size : 0;
4579#else
4580 ret = dladdr(addr, dli);
4581 *size = 0;
4582#endif
4583 return ret;
4584}
4585#endif
4586
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004587/* Tries to append to buffer <buf> some indications about the symbol at address
4588 * <addr> using the following form:
4589 * lib:+0xoffset (unresolvable address from lib's base)
4590 * main+0xoffset (unresolvable address from main (+/-))
4591 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4592 * name (resolved exact exec address)
4593 * lib:name (resolved exact lib address)
4594 * name+0xoffset/0xsize (resolved address within exec symbol)
4595 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4596 *
4597 * The file name (lib or executable) is limited to what lies between the last
4598 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4599 * 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 +03004600 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004601 *
4602 * The symbol's base address is returned, or NULL when unresolved, in order to
4603 * allow the caller to match it against known ones.
4604 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004605const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004606{
4607 const struct {
4608 const void *func;
4609 const char *name;
4610 } fcts[] = {
4611 { .func = process_stream, .name = "process_stream" },
4612 { .func = task_run_applet, .name = "task_run_applet" },
4613 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004614 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004615 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4616 { .func = listener_accept, .name = "listener_accept" },
4617 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4618 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4619#ifdef USE_LUA
4620 { .func = hlua_process_task, .name = "hlua_process_task" },
4621#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004622#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004623 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4624 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4625#endif
4626 };
4627
Baruch Siache1651b22020-07-24 07:52:20 +03004628#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004629 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004630 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004631 const char *fname, *p;
4632#endif
4633 int i;
4634
4635 if (pfx)
4636 chunk_appendf(buf, "%s", pfx);
4637
4638 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4639 if (addr == fcts[i].func) {
4640 chunk_appendf(buf, "%s", fcts[i].name);
4641 return addr;
4642 }
4643 }
4644
Baruch Siache1651b22020-07-24 07:52:20 +03004645#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004646 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004647 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004648 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004649
4650 /* 1. prefix the library name if it's not the same object as the one
4651 * that contains the main function. The name is picked between last '/'
4652 * and first following '.'.
4653 */
4654 if (!dladdr(main, &dli_main))
4655 dli_main.dli_fbase = NULL;
4656
4657 if (dli_main.dli_fbase != dli.dli_fbase) {
4658 fname = dli.dli_fname;
4659 p = strrchr(fname, '/');
4660 if (p++)
4661 fname = p;
4662 p = strchr(fname, '.');
4663 if (!p)
4664 p = fname + strlen(fname);
4665
4666 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4667 }
4668
4669 /* 2. symbol name */
4670 if (dli.dli_sname) {
4671 /* known, dump it and return symbol's address (exact or relative) */
4672 chunk_appendf(buf, "%s", dli.dli_sname);
4673 if (addr != dli.dli_saddr) {
4674 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004675 if (size)
4676 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004677 }
4678 return dli.dli_saddr;
4679 }
4680 else if (dli_main.dli_fbase != dli.dli_fbase) {
4681 /* unresolved symbol from a known library, report relative offset */
4682 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4683 return NULL;
4684 }
Baruch Siache1651b22020-07-24 07:52:20 +03004685#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004686 unknown:
4687 /* unresolved symbol from the main file, report relative offset to main */
4688 if ((void*)addr < (void*)main)
4689 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4690 else
4691 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4692 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004693}
4694
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004695/*
4696 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004697 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004698 *
4699 * First, initializes the value with <sz> as address to 0 and initializes the
4700 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4701 * address updating <sz> pointed value to the size of this array.
4702 *
4703 * Returns 1 if succeeded, 0 if not.
4704 */
4705int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4706{
4707 unsigned int *n;
4708 const char *s, *end;
4709
4710 s = str;
4711 *sz = 0;
4712 end = str + strlen(str);
4713 *nums = n = NULL;
4714
4715 while (1) {
4716 unsigned int r;
4717
4718 if (s >= end)
4719 break;
4720
4721 r = read_uint(&s, end);
4722 /* Expected characters after having read an uint: '\0' or '.',
4723 * if '.', must not be terminal.
4724 */
4725 if (*s != '\0'&& (*s++ != '.' || s == end))
4726 return 0;
4727
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004728 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004729 if (!n)
4730 return 0;
4731
4732 n[(*sz)++] = r;
4733 }
4734 *nums = n;
4735
4736 return 1;
4737}
4738
Willy Tarreau4d589e72019-08-23 19:02:26 +02004739
4740/* returns the number of bytes needed to encode <v> as a varint. An inline
4741 * version exists for use with constants (__varint_bytes()).
4742 */
4743int varint_bytes(uint64_t v)
4744{
4745 int len = 1;
4746
4747 if (v >= 240) {
4748 v = (v - 240) >> 4;
4749 while (1) {
4750 len++;
4751 if (v < 128)
4752 break;
4753 v = (v - 128) >> 7;
4754 }
4755 }
4756 return len;
4757}
4758
Willy Tarreau52bf8392020-03-08 00:42:37 +01004759
4760/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004761static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004762
4763/* This is a thread-safe implementation of xoroshiro128** described below:
4764 * http://prng.di.unimi.it/
4765 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4766 * supports fast jumps and passes all common quality tests. It is thread-safe,
4767 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4768 * local lock on other ones.
4769 */
4770uint64_t ha_random64()
4771{
4772 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004773 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4774 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004775
4776#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4777 static HA_SPINLOCK_T rand_lock;
4778
4779 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4780#endif
4781
4782 old[0] = ha_random_state[0];
4783 old[1] = ha_random_state[1];
4784
4785#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4786 do {
4787#endif
4788 result = rotl64(old[0] * 5, 7) * 9;
4789 new[1] = old[0] ^ old[1];
4790 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4791 new[1] = rotl64(new[1], 37); // c
4792
4793#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4794 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4795#else
4796 ha_random_state[0] = new[0];
4797 ha_random_state[1] = new[1];
4798#if defined(USE_THREAD)
4799 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4800#endif
4801#endif
4802 return result;
4803}
4804
4805/* seeds the random state using up to <len> bytes from <seed>, starting with
4806 * the first non-zero byte.
4807 */
4808void ha_random_seed(const unsigned char *seed, size_t len)
4809{
4810 size_t pos;
4811
4812 /* the seed must not be all zeroes, so we pre-fill it with alternating
4813 * bits and overwrite part of them with the block starting at the first
4814 * non-zero byte from the seed.
4815 */
4816 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4817
4818 for (pos = 0; pos < len; pos++)
4819 if (seed[pos] != 0)
4820 break;
4821
4822 if (pos == len)
4823 return;
4824
4825 seed += pos;
4826 len -= pos;
4827
4828 if (len > sizeof(ha_random_state))
4829 len = sizeof(ha_random_state);
4830
4831 memcpy(ha_random_state, seed, len);
4832}
4833
4834/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4835 * and is equivalent to calling ha_random64() as many times. It is used to
4836 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4837 * different generators (i.e. different processes after a fork). The <dist>
4838 * argument is the distance to jump to and is used in a loop so it rather not
4839 * be too large if the processing time is a concern.
4840 *
4841 * BEWARE: this function is NOT thread-safe and must not be called during
4842 * concurrent accesses to ha_random64().
4843 */
4844void ha_random_jump96(uint32_t dist)
4845{
4846 while (dist--) {
4847 uint64_t s0 = 0;
4848 uint64_t s1 = 0;
4849 int b;
4850
4851 for (b = 0; b < 64; b++) {
4852 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4853 s0 ^= ha_random_state[0];
4854 s1 ^= ha_random_state[1];
4855 }
4856 ha_random64();
4857 }
4858
4859 for (b = 0; b < 64; b++) {
4860 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4861 s0 ^= ha_random_state[0];
4862 s1 ^= ha_random_state[1];
4863 }
4864 ha_random64();
4865 }
4866 ha_random_state[0] = s0;
4867 ha_random_state[1] = s1;
4868 }
4869}
4870
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004871/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4872 * bytes large.
4873 */
4874void ha_generate_uuid(struct buffer *output)
4875{
4876 uint32_t rnd[4];
4877 uint64_t last;
4878
4879 last = ha_random64();
4880 rnd[0] = last;
4881 rnd[1] = last >> 32;
4882
4883 last = ha_random64();
4884 rnd[2] = last;
4885 rnd[3] = last >> 32;
4886
4887 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4888 rnd[0],
4889 rnd[1] & 0xFFFF,
4890 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4891 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4892 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4893}
4894
4895
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004896/* only used by parse_line() below. It supports writing in place provided that
4897 * <in> is updated to the next location before calling it. In that case, the
4898 * char at <in> may be overwritten.
4899 */
4900#define EMIT_CHAR(x) \
4901 do { \
4902 char __c = (char)(x); \
4903 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4904 err |= PARSE_ERR_OVERLAP; \
4905 if (outpos >= outmax) \
4906 err |= PARSE_ERR_TOOLARGE; \
4907 if (!err) \
4908 out[outpos] = __c; \
4909 outpos++; \
4910 } while (0)
4911
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004912/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004913 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4914 * extraneous ones are not emitted but <outlen> is updated so that the caller
4915 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4916 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004917 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4918 * it is guaranteed that at least one arg will point to the zero. It is safe
4919 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004920 *
4921 * <out> may overlap with <in> provided that it never goes further, in which
4922 * case the parser will accept to perform in-place parsing and unquoting/
4923 * unescaping but only if environment variables do not lead to expansion that
4924 * causes overlapping, otherwise the input string being destroyed, the error
4925 * will not be recoverable. Note that even during out-of-place <in> will
4926 * experience temporary modifications in-place for variable resolution and must
4927 * be writable, and will also receive zeroes to delimit words when using
4928 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4929 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4930 * starting point of the first invalid character sequence or unmatched
4931 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4932 * error reporting might be difficult since zeroes will have been inserted into
4933 * the string. One solution for the caller may consist in replacing all args
4934 * delimiters with spaces in this case.
4935 */
4936uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4937{
4938 char *quote = NULL;
4939 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02004940 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004941 unsigned char hex1, hex2;
4942 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004943 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004944 size_t outpos = 0;
4945 int squote = 0;
4946 int dquote = 0;
4947 int arg = 0;
4948 uint32_t err = 0;
4949
4950 *nbargs = 0;
4951 *outlen = 0;
4952
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004953 /* argsmax may be -1 here, protecting args[] from any write */
4954 if (arg < argsmax)
4955 args[arg] = out;
4956
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004957 while (1) {
4958 if (*in >= '-' && *in != '\\') {
4959 /* speedup: directly send all regular chars starting
4960 * with '-', '.', '/', alnum etc...
4961 */
4962 EMIT_CHAR(*in++);
4963 continue;
4964 }
4965 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4966 /* end of line */
4967 break;
4968 }
4969 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4970 /* comment */
4971 break;
4972 }
4973 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4974 if (dquote) {
4975 dquote = 0;
4976 quote = NULL;
4977 }
4978 else {
4979 dquote = 1;
4980 quote = in;
4981 }
4982 in++;
4983 continue;
4984 }
4985 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4986 if (squote) {
4987 squote = 0;
4988 quote = NULL;
4989 }
4990 else {
4991 squote = 1;
4992 quote = in;
4993 }
4994 in++;
4995 continue;
4996 }
4997 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4998 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4999 * C equivalent value but only when they have a special meaning and within
5000 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5001 */
5002 char tosend = *in;
5003
5004 switch (in[1]) {
5005 case ' ':
5006 case '\\':
5007 tosend = in[1];
5008 in++;
5009 break;
5010
5011 case 't':
5012 tosend = '\t';
5013 in++;
5014 break;
5015
5016 case 'n':
5017 tosend = '\n';
5018 in++;
5019 break;
5020
5021 case 'r':
5022 tosend = '\r';
5023 in++;
5024 break;
5025
5026 case '#':
5027 /* escaping of "#" only if comments are supported */
5028 if (opts & PARSE_OPT_SHARP)
5029 in++;
5030 tosend = *in;
5031 break;
5032
5033 case '\'':
5034 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5035 if (opts & PARSE_OPT_SQUOTE && !squote)
5036 in++;
5037 tosend = *in;
5038 break;
5039
5040 case '"':
5041 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5042 if (opts & PARSE_OPT_DQUOTE && !squote)
5043 in++;
5044 tosend = *in;
5045 break;
5046
5047 case '$':
5048 /* escaping of '$' only inside double quotes and only if env supported */
5049 if (opts & PARSE_OPT_ENV && dquote)
5050 in++;
5051 tosend = *in;
5052 break;
5053
5054 case 'x':
5055 if (!ishex(in[2]) || !ishex(in[3])) {
5056 /* invalid or incomplete hex sequence */
5057 err |= PARSE_ERR_HEX;
5058 if (errptr)
5059 *errptr = in;
5060 goto leave;
5061 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005062 hex1 = toupper((unsigned char)in[2]) - '0';
5063 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005064 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5065 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5066 tosend = (hex1 << 4) + hex2;
5067 in += 3;
5068 break;
5069
5070 default:
5071 /* other combinations are not escape sequences */
5072 break;
5073 }
5074
5075 in++;
5076 EMIT_CHAR(tosend);
5077 }
5078 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5079 /* a non-escaped space is an argument separator */
5080 while (isspace((unsigned char)*in))
5081 in++;
5082 EMIT_CHAR(0);
5083 arg++;
5084 if (arg < argsmax)
5085 args[arg] = out + outpos;
5086 else
5087 err |= PARSE_ERR_TOOMANY;
5088 }
5089 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5090 /* environment variables are evaluated anywhere, or only
5091 * inside double quotes if they are supported.
5092 */
5093 char *var_name;
5094 char save_char;
5095 char *value;
5096
5097 in++;
5098
5099 if (*in == '{')
5100 brace = in++;
5101
5102 if (!isalpha((unsigned char)*in) && *in != '_') {
5103 /* unacceptable character in variable name */
5104 err |= PARSE_ERR_VARNAME;
5105 if (errptr)
5106 *errptr = in;
5107 goto leave;
5108 }
5109
5110 var_name = in;
5111 while (isalnum((unsigned char)*in) || *in == '_')
5112 in++;
5113
5114 save_char = *in;
5115 *in = '\0';
5116 value = getenv(var_name);
5117 *in = save_char;
5118
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005119 /* support for '[*]' sequence to force word expansion,
5120 * only available inside braces */
5121 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5122 word_expand = in++;
5123
5124 if (*in++ != '*' || *in++ != ']') {
5125 err |= PARSE_ERR_WRONG_EXPAND;
5126 if (errptr)
5127 *errptr = word_expand;
5128 goto leave;
5129 }
5130 }
5131
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005132 if (brace) {
5133 if (*in != '}') {
5134 /* unmatched brace */
5135 err |= PARSE_ERR_BRACE;
5136 if (errptr)
5137 *errptr = brace;
5138 goto leave;
5139 }
5140 in++;
5141 brace = NULL;
5142 }
5143
5144 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005145 while (*value) {
5146 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005147 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005148 EMIT_CHAR(0);
5149 ++arg;
5150 if (arg < argsmax)
5151 args[arg] = out + outpos;
5152 else
5153 err |= PARSE_ERR_TOOMANY;
5154
5155 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005156 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005157 ;
5158 } else {
5159 EMIT_CHAR(*value++);
5160 }
5161 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005162 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005163 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005164 }
5165 else {
5166 /* any other regular char */
5167 EMIT_CHAR(*in++);
5168 }
5169 }
5170
5171 /* end of output string */
5172 EMIT_CHAR(0);
5173 arg++;
5174
5175 if (quote) {
5176 /* unmatched quote */
5177 err |= PARSE_ERR_QUOTE;
5178 if (errptr)
5179 *errptr = quote;
5180 goto leave;
5181 }
5182 leave:
5183 *nbargs = arg;
5184 *outlen = outpos;
5185
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005186 /* empty all trailing args by making them point to the trailing zero,
5187 * at least the last one in any case.
5188 */
5189 if (arg > argsmax)
5190 arg = argsmax;
5191
5192 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005193 args[arg++] = out + outpos - 1;
5194
5195 return err;
5196}
5197#undef EMIT_CHAR
5198
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005199/* This is used to sanitize an input line that's about to be used for error reporting.
5200 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5201 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5202 * If non-printable chars are present in the output. It returns the new offset <pos>
5203 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5204 * be at least 6 to support two "..." otherwise the result is undefined. The line
5205 * itself must have at least 7 chars allocated for the same reason.
5206 */
5207size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5208{
5209 size_t shift = 0;
5210 char *out = line;
5211 char *in = line;
5212 char *end = line + width;
5213
5214 if (pos >= width) {
5215 /* if we have to shift, we'll be out of context, so let's
5216 * try to put <pos> at the center of width.
5217 */
5218 shift = pos - width / 2;
5219 in += shift + 3;
5220 end = out + width - 3;
5221 out[0] = out[1] = out[2] = '.';
5222 out += 3;
5223 }
5224
5225 while (out < end && *in) {
5226 if (isspace((unsigned char)*in))
5227 *out++ = ' ';
5228 else if (isprint((unsigned char)*in))
5229 *out++ = *in;
5230 else
5231 *out++ = '?';
5232 in++;
5233 }
5234
5235 if (end < line + width) {
5236 out[0] = out[1] = out[2] = '.';
5237 out += 3;
5238 }
5239
5240 *out++ = 0;
5241 return pos - shift;
5242}
5243
Willy Tarreaubaaee002006-06-26 02:48:02 +02005244/*
5245 * Local variables:
5246 * c-indent-level: 8
5247 * c-basic-offset: 8
5248 * End:
5249 */