1 /*
2  * include/haproxy/tools.h
3  * This files contains some general purpose functions and macros.
4  *
5  * Copyright (C) 2000-2020 Willy Tarreau - w@1wt.eu
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation, version 2.1
10  * exclusively.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21 
22 #ifndef _HAPROXY_TOOLS_H
23 #define _HAPROXY_TOOLS_H
24 
25 #ifdef USE_BACKTRACE
26 #define _GNU_SOURCE
27 #include <execinfo.h>
28 #endif
29 
30 #include <string.h>
31 #include <stdio.h>
32 #include <time.h>
33 #include <stdarg.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/un.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40 #include <import/eb32sctree.h>
41 #include <import/eb32tree.h>
42 #include <haproxy/api.h>
43 #include <haproxy/chunk.h>
44 #include <haproxy/intops.h>
45 #include <haproxy/namespace-t.h>
46 #include <haproxy/protocol-t.h>
47 #include <haproxy/tools-t.h>
48 
49 /****** string-specific macros and functions ******/
50 /* if a > max, then bound <a> to <max>. The macro returns the new <a> */
51 #define UBOUND(a, max)	({ typeof(a) b = (max); if ((a) > b) (a) = b; (a); })
52 
53 /* if a < min, then bound <a> to <min>. The macro returns the new <a> */
54 #define LBOUND(a, min)	({ typeof(a) b = (min); if ((a) < b) (a) = b; (a); })
55 
56 #define SWAP(a, b) do { typeof(a) t; t = a; a = b; b = t; } while(0)
57 
58 /*
59  * copies at most <size-1> chars from <src> to <dst>. Last char is always
60  * set to 0, unless <size> is 0. The number of chars copied is returned
61  * (excluding the terminating zero).
62  * This code has been optimized for size and speed : on x86, it's 45 bytes
63  * long, uses only registers, and consumes only 4 cycles per char.
64  */
65 extern int strlcpy2(char *dst, const char *src, int size);
66 
67 /*
68  * This function simply returns a locally allocated string containing
69  * the ascii representation for number 'n' in decimal.
70  */
71 extern THREAD_LOCAL int itoa_idx; /* index of next itoa_str to use */
72 extern THREAD_LOCAL char itoa_str[][171];
73 extern char *ultoa_r(unsigned long n, char *buffer, int size);
74 extern char *lltoa_r(long long int n, char *buffer, int size);
75 extern char *sltoa_r(long n, char *buffer, int size);
76 extern const char *ulltoh_r(unsigned long long n, char *buffer, int size);
ultoa(unsigned long n)77 static inline const char *ultoa(unsigned long n)
78 {
79 	return ultoa_r(n, itoa_str[0], sizeof(itoa_str[0]));
80 }
81 
82 /*
83  * unsigned long long ASCII representation
84  *
85  * return the last char '\0' or NULL if no enough
86  * space in dst
87  */
88 char *ulltoa(unsigned long long n, char *dst, size_t size);
89 
90 
91 /*
92  * unsigned long ASCII representation
93  *
94  * return the last char '\0' or NULL if no enough
95  * space in dst
96  */
97 char *ultoa_o(unsigned long n, char *dst, size_t size);
98 
99 /*
100  * signed long ASCII representation
101  *
102  * return the last char '\0' or NULL if no enough
103  * space in dst
104  */
105 char *ltoa_o(long int n, char *dst, size_t size);
106 
107 /*
108  * signed long long ASCII representation
109  *
110  * return the last char '\0' or NULL if no enough
111  * space in dst
112  */
113 char *lltoa(long long n, char *dst, size_t size);
114 
115 /*
116  * write a ascii representation of a unsigned into dst,
117  * return a pointer to the last character
118  * Pad the ascii representation with '0', using size.
119  */
120 char *utoa_pad(unsigned int n, char *dst, size_t size);
121 
122 /*
123  * This function simply returns a locally allocated string containing the ascii
124  * representation for number 'n' in decimal, unless n is 0 in which case it
125  * returns the alternate string (or an empty string if the alternate string is
126  * NULL). It use is intended for limits reported in reports, where it's
127  * desirable not to display anything if there is no limit. Warning! it shares
128  * the same vector as ultoa_r().
129  */
130 extern const char *limit_r(unsigned long n, char *buffer, int size, const char *alt);
131 
132 /* returns a locally allocated string containing the ASCII representation of
133  * the number 'n' in decimal. Up to NB_ITOA_STR calls may be used in the same
134  * function call (eg: printf), shared with the other similar functions making
135  * use of itoa_str[].
136  */
U2A(unsigned long n)137 static inline const char *U2A(unsigned long n)
138 {
139 	const char *ret = ultoa_r(n, itoa_str[itoa_idx], sizeof(itoa_str[0]));
140 	if (++itoa_idx >= NB_ITOA_STR)
141 		itoa_idx = 0;
142 	return ret;
143 }
144 
145 /* returns a locally allocated string containing the HTML representation of
146  * the number 'n' in decimal. Up to NB_ITOA_STR calls may be used in the same
147  * function call (eg: printf), shared with the other similar functions making
148  * use of itoa_str[].
149  */
U2H(unsigned long long n)150 static inline const char *U2H(unsigned long long n)
151 {
152 	const char *ret = ulltoh_r(n, itoa_str[itoa_idx], sizeof(itoa_str[0]));
153 	if (++itoa_idx >= NB_ITOA_STR)
154 		itoa_idx = 0;
155 	return ret;
156 }
157 
158 /* returns a locally allocated string containing the ASCII representation of
159  * the number 'n' in decimal. Up to NB_ITOA_STR calls may be used in the same
160  * function call (eg: printf), shared with the other similar functions making
161  * use of itoa_str[].
162  */
LIM2A(unsigned long n,const char * alt)163 static inline const char *LIM2A(unsigned long n, const char *alt)
164 {
165 	const char *ret = limit_r(n, itoa_str[itoa_idx], sizeof(itoa_str[0]), alt);
166 	if (++itoa_idx >= NB_ITOA_STR)
167 		itoa_idx = 0;
168 	return ret;
169 }
170 
171 /* returns a locally allocated string containing the quoted encoding of the
172  * input string. The output may be truncated to QSTR_SIZE chars, but it is
173  * guaranteed that the string will always be properly terminated. Quotes are
174  * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
175  * always be at least 4 chars.
176  */
177 const char *qstr(const char *str);
178 
179 /* returns <str> or its quote-encoded equivalent if it contains at least one
180  * quote or a comma. This is aimed at build CSV-compatible strings.
181  */
cstr(const char * str)182 static inline const char *cstr(const char *str)
183 {
184 	const char *p = str;
185 
186 	while (*p) {
187 		if (*p == ',' || *p == '"')
188 			return qstr(str);
189 		p++;
190 	}
191 	return str;
192 }
193 
194 /*
195  * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
196  */
197 extern int ishex(char s);
198 
199 /*
200  * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
201  * invalid character is found, a pointer to it is returned. If everything is
202  * fine, NULL is returned.
203  */
204 extern const char *invalid_char(const char *name);
205 
206 /*
207  * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
208  * If an invalid character is found, a pointer to it is returned.
209  * If everything is fine, NULL is returned.
210  */
211 extern const char *invalid_domainchar(const char *name);
212 
213 /*
214  * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
215  * If an invalid character is found, a pointer to it is returned.
216  * If everything is fine, NULL is returned.
217  */
218 extern const char *invalid_prefix_char(const char *name);
219 
220 /* returns true if <c> is an identifier character, that is, a digit, a letter,
221  * or '-', '+', '_', ':' or '.'. This is usable for proxy names, server names,
222  * ACL names, sample fetch names, and converter names.
223  */
is_idchar(char c)224 static inline int is_idchar(char c)
225 {
226 	return isalnum((unsigned char)c) ||
227 	       c == '.' || c == '_' || c == '-' || c == '+' || c == ':';
228 }
229 
230 /*
231  * converts <str> to a locally allocated struct sockaddr_storage *, and a
232  * port range consisting in two integers. The low and high end are always set
233  * even if the port is unspecified, in which case (0,0) is returned. The low
234  * port is set in the sockaddr. Thus, it is enough to check the size of the
235  * returned range to know if an array must be allocated or not. The format is
236  * "addr[:[port[-port]]]", where "addr" can be a dotted IPv4 address, an IPv6
237  * address, a host name, or empty or "*" to indicate INADDR_ANY. If an IPv6
238  * address wants to ignore port, it must be terminated by a trailing colon (':').
239  * The IPv6 '::' address is IN6ADDR_ANY, so in order to bind to a given port on
240  * IPv6, use ":::port". NULL is returned if the host part cannot be resolved.
241  * If <pfx> is non-null, it is used as a string prefix before any path-based
242  * address (typically the path to a unix socket).
243  */
244 struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
245                                       struct protocol **proto, char **err,
246                                       const char *pfx, char **fqdn, unsigned int opts);
247 
248 /* converts <str> to a struct in_addr containing a network mask. It can be
249  * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
250  * if the conversion succeeds otherwise zero.
251  */
252 int str2mask(const char *str, struct in_addr *mask);
253 
254 /* converts <str> to a struct in6_addr containing a network mask. It can be
255  * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
256  * if the conversion succeeds otherwise zero.
257  */
258 int str2mask6(const char *str, struct in6_addr *mask);
259 
260 /* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
261  * succeeds otherwise non-zero.
262  */
263 int cidr2dotted(int cidr, struct in_addr *mask);
264 
265 /*
266  * converts <str> to two struct in_addr* which must be pre-allocated.
267  * The format is "addr[/mask]", where "addr" cannot be empty, and mask
268  * is optional and either in the dotted or CIDR notation.
269  * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
270  */
271 int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask);
272 
273 /* str2ip and str2ip2:
274  *
275  * converts <str> to a struct sockaddr_storage* provided by the caller. The
276  * caller must have zeroed <sa> first, and may have set sa->ss_family to force
277  * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
278  * the function tries to guess the address family from the syntax. If the
279  * family is forced and the format doesn't match, an error is returned. The
280  * string is assumed to contain only an address, no port. The address can be a
281  * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
282  * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
283  * The return address will only have the address family and the address set,
284  * all other fields remain zero. The string is not supposed to be modified.
285  * The IPv6 '::' address is IN6ADDR_ANY.
286  *
287  * str2ip2:
288  *
289  * If <resolve> is set, this function try to resolve DNS, otherwise, it returns
290  * NULL result.
291  */
292 struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve);
str2ip(const char * str,struct sockaddr_storage * sa)293 static inline struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
294 {
295 	return str2ip2(str, sa, 1);
296 }
297 
298 /*
299  * converts <str> to two struct in6_addr* which must be pre-allocated.
300  * The format is "addr[/mask]", where "addr" cannot be empty, and mask
301  * is an optional number of bits (128 being the default).
302  * Returns 1 if OK, 0 if error.
303  */
304 int str62net(const char *str, struct in6_addr *addr, unsigned char *mask);
305 
306 /*
307  * Parse IP address found in url.
308  */
309 int url2ipv4(const char *addr, struct in_addr *dst);
310 
311 /*
312  * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
313  */
314 int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out);
315 
316 /* Tries to convert a sockaddr_storage address to text form. Upon success, the
317  * address family is returned so that it's easy for the caller to adapt to the
318  * output format. Zero is returned if the address family is not supported. -1
319  * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
320  * supported.
321  */
322 int addr_to_str(const struct sockaddr_storage *addr, char *str, int size);
323 
324 /* Tries to convert a sockaddr_storage port to text form. Upon success, the
325  * address family is returned so that it's easy for the caller to adapt to the
326  * output format. Zero is returned if the address family is not supported. -1
327  * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
328  * supported.
329  */
330 int port_to_str(const struct sockaddr_storage *addr, char *str, int size);
331 
332 /* check if the given address is local to the system or not. It will return
333  * -1 when it's not possible to know, 0 when the address is not local, 1 when
334  * it is. We don't want to iterate over all interfaces for this (and it is not
335  * portable). So instead we try to bind in UDP to this address on a free non
336  * privileged port and to connect to the same address, port 0 (connect doesn't
337  * care). If it succeeds, we own the address. Note that non-inet addresses are
338  * considered local since they're most likely AF_UNIX.
339  */
340 int addr_is_local(const struct netns_entry *ns,
341                   const struct sockaddr_storage *orig);
342 
343 /* will try to encode the string <string> replacing all characters tagged in
344  * <map> with the hexadecimal representation of their ASCII-code (2 digits)
345  * prefixed by <escape>, and will store the result between <start> (included)
346  * and <stop> (excluded), and will always terminate the string with a '\0'
347  * before <stop>. The position of the '\0' is returned if the conversion
348  * completes. If bytes are missing between <start> and <stop>, then the
349  * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
350  * cannot even be stored so we return <start> without writing the 0.
351  * The input string must also be zero-terminated.
352  */
353 extern const char hextab[];
354 char *encode_string(char *start, char *stop,
355 		    const char escape, const long *map,
356 		    const char *string);
357 
358 /*
359  * Same behavior, except that it encodes chunk <chunk> instead of a string.
360  */
361 char *encode_chunk(char *start, char *stop,
362                    const char escape, const long *map,
363                    const struct buffer *chunk);
364 
365 /*
366  * Tries to prefix characters tagged in the <map> with the <escape>
367  * character. The input <string> must be zero-terminated. The result will
368  * be stored between <start> (included) and <stop> (excluded). This
369  * function will always try to terminate the resulting string with a '\0'
370  * before <stop>, and will return its position if the conversion
371  * completes.
372  */
373 char *escape_string(char *start, char *stop,
374 		    const char escape, const long *map,
375 		    const char *string);
376 
377 /*
378  * Tries to prefix characters tagged in the <map> with the <escape>
379  * character. <chunk> contains the input to be escaped. The result will be
380  * stored between <start> (included) and <stop> (excluded). The function
381  * will always try to terminate the resulting string with a '\0' before
382  * <stop>, and will return its position if the conversion completes.
383  */
384 char *escape_chunk(char *start, char *stop,
385                    const char escape, const long *map,
386                    const struct buffer *chunk);
387 
388 
389 /* Check a string for using it in a CSV output format. If the string contains
390  * one of the following four char <">, <,>, CR or LF, the string is
391  * encapsulated between <"> and the <"> are escaped by a <""> sequence.
392  * <str> is the input string to be escaped. The function assumes that
393  * the input string is null-terminated.
394  *
395  * If <quote> is 0, the result is returned escaped but without double quote.
396  * It is useful if the escaped string is used between double quotes in the
397  * format.
398  *
399  *    printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
400  *
401  * If <quote> is 1, the converter puts the quotes only if any character is
402  * escaped. If <quote> is 2, the converter always puts the quotes.
403  *
404  * <output> is a struct chunk used for storing the output string.
405  *
406  * The function returns the converted string on its output. If an error
407  * occurs, the function returns an empty string. This type of output is useful
408  * for using the function directly as printf() argument.
409  *
410  * If the output buffer is too short to contain the input string, the result
411  * is truncated.
412  *
413  * This function appends the encoding to the existing output chunk. Please
414  * use csv_enc() instead if you want to replace the output chunk.
415  */
416 const char *csv_enc_append(const char *str, int quote, struct buffer *output);
417 
418 /* same as above but the output chunk is reset first */
csv_enc(const char * str,int quote,struct buffer * output)419 static inline const char *csv_enc(const char *str, int quote,
420 				  struct buffer *output)
421 {
422 	chunk_reset(output);
423 	return csv_enc_append(str, quote, output);
424 }
425 
426 /* Decode an URL-encoded string in-place. The resulting string might
427  * be shorter. If some forbidden characters are found, the conversion is
428  * aborted, the string is truncated before the issue and non-zero is returned,
429  * otherwise the operation returns non-zero indicating success.
430  * If the 'in_form' argument is non-nul the string is assumed to be part of
431  * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
432  * turned to a space. If it's zero, this will only be done after a question
433  * mark ('?').
434  */
435 int url_decode(char *string, int in_form);
436 
437 unsigned int inetaddr_host(const char *text);
438 unsigned int inetaddr_host_lim(const char *text, const char *stop);
439 unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret);
440 
cut_crlf(char * s)441 static inline char *cut_crlf(char *s) {
442 
443 	while (*s != '\r' && *s != '\n') {
444 		char *p = s++;
445 
446 		if (!*p)
447 			return p;
448 	}
449 
450 	*s++ = '\0';
451 
452 	return s;
453 }
454 
ltrim(char * s,char c)455 static inline char *ltrim(char *s, char c) {
456 
457 	if (c)
458 		while (*s == c)
459 			s++;
460 
461 	return s;
462 }
463 
rtrim(char * s,char c)464 static inline char *rtrim(char *s, char c) {
465 
466 	char *p = s + strlen(s);
467 
468 	while (p-- > s)
469 		if (*p == c)
470 			*p = '\0';
471 		else
472 			break;
473 
474 	return s;
475 }
476 
alltrim(char * s,char c)477 static inline char *alltrim(char *s, char c) {
478 
479 	rtrim(s, c);
480 
481 	return ltrim(s, c);
482 }
483 
484 /* This function converts the time_t value <now> into a broken out struct tm
485  * which must be allocated by the caller. It is highly recommended to use this
486  * function instead of localtime() because that one requires a time_t* which
487  * is not always compatible with tv_sec depending on OS/hardware combinations.
488  */
get_localtime(const time_t now,struct tm * tm)489 static inline void get_localtime(const time_t now, struct tm *tm)
490 {
491 	localtime_r(&now, tm);
492 }
493 
494 /* This function converts the time_t value <now> into a broken out struct tm
495  * which must be allocated by the caller. It is highly recommended to use this
496  * function instead of gmtime() because that one requires a time_t* which
497  * is not always compatible with tv_sec depending on OS/hardware combinations.
498  */
get_gmtime(const time_t now,struct tm * tm)499 static inline void get_gmtime(const time_t now, struct tm *tm)
500 {
501 	gmtime_r(&now, tm);
502 }
503 
504 /* Counts a number of elapsed days since 01/01/0000 based solely on elapsed
505  * years and assuming the regular rule for leap years applies. It's fake but
506  * serves as a temporary origin. It's worth remembering that it's the first
507  * year of each period that is leap and not the last one, so for instance year
508  * 1 sees 366 days since year 0 was leap. For this reason we have to apply
509  * modular arithmetic which is why we offset the year by 399 before
510  * subtracting the excess at the end. No overflow here before ~11.7 million
511  * years.
512  */
days_since_zero(unsigned int y)513 static inline unsigned int days_since_zero(unsigned int y)
514 {
515 	return y * 365 + (y + 399) / 4 - (y + 399) / 100 + (y + 399) / 400
516 	       - 399 / 4 + 399 / 100;
517 }
518 
519 /* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
520  * It is meant as a portable replacement for timegm() for use with valid inputs.
521  * Returns undefined results for invalid dates (eg: months out of range 0..11).
522  */
523 extern time_t my_timegm(const struct tm *tm);
524 
525 /* This function parses a time value optionally followed by a unit suffix among
526  * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
527  * expected by the caller. The computation does its best to avoid overflows.
528  * The value is returned in <ret> if everything is fine, and a NULL is returned
529  * by the function. In case of error, a pointer to the error is returned and
530  * <ret> is left untouched.
531  */
532 extern const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags);
533 extern const char *parse_size_err(const char *text, unsigned *ret);
534 
535 /*
536  * Parse binary string written in hexadecimal (source) and store the decoded
537  * result into binstr and set binstrlen to the length of binstr. Memory for
538  * binstr is allocated by the function. In case of error, returns 0 with an
539  * error message in err.
540  */
541 int parse_binary(const char *source, char **binstr, int *binstrlen, char **err);
542 
543 /* copies at most <n> characters from <src> and always terminates with '\0' */
544 char *my_strndup(const char *src, int n);
545 
546 /*
547  * search needle in haystack
548  * returns the pointer if found, returns NULL otherwise
549  */
550 const void *my_memmem(const void *, size_t, const void *, size_t);
551 
552 /* get length of the initial segment consisting entirely of bytes within a given
553  * mask
554  */
555 size_t my_memspn(const void *, size_t, const void *, size_t);
556 
557 /* get length of the initial segment consisting entirely of bytes not within a
558  * given mask
559  */
560 size_t my_memcspn(const void *, size_t, const void *, size_t);
561 
562 /* This function returns the first unused key greater than or equal to <key> in
563  * ID tree <root>. Zero is returned if no place is found.
564  */
565 unsigned int get_next_id(struct eb_root *root, unsigned int key);
566 
567 /* dump the full tree to <file> in DOT format for debugging purposes. Will
568  * optionally highlight node <subj> if found, depending on operation <op> :
569  *    0 : nothing
570  *   >0 : insertion, node/leaf are surrounded in red
571  *   <0 : removal, node/leaf are dashed with no background
572  * Will optionally add "desc" as a label on the graph if set and non-null.
573  */
574 void eb32sc_to_file(FILE *file, struct eb_root *root, const struct eb32sc_node *subj,
575                     int op, const char *desc);
576 
577 /* This function compares a sample word possibly followed by blanks to another
578  * clean word. The compare is case-insensitive. 1 is returned if both are equal,
579  * otherwise zero. This intends to be used when checking HTTP headers for some
580  * values.
581  */
582 int word_match(const char *sample, int slen, const char *word, int wlen);
583 
584 /* Convert a fixed-length string to an IP address. Returns 0 in case of error,
585  * or the number of chars read in case of success.
586  */
587 int buf2ip(const char *buf, size_t len, struct in_addr *dst);
588 int buf2ip6(const char *buf, size_t len, struct in6_addr *dst);
589 
590 /* To be used to quote config arg positions. Returns the string at <ptr>
591  * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
592  * if ptr is NULL or empty. The string is locally allocated.
593  */
594 const char *quote_arg(const char *ptr);
595 
596 /* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
597 int get_std_op(const char *str);
598 
599 /* sets the address family to AF_UNSPEC so that is_addr() does not match */
clear_addr(struct sockaddr_storage * addr)600 static inline void clear_addr(struct sockaddr_storage *addr)
601 {
602 	addr->ss_family = AF_UNSPEC;
603 }
604 
605 /* returns non-zero if addr has a valid and non-null IPv4 or IPv6 address,
606  * otherwise zero.
607  */
is_inet_addr(const struct sockaddr_storage * addr)608 static inline int is_inet_addr(const struct sockaddr_storage *addr)
609 {
610 	int i;
611 
612 	switch (addr->ss_family) {
613 	case AF_INET:
614 		return *(int *)&((struct sockaddr_in *)addr)->sin_addr;
615 	case AF_INET6:
616 		for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
617 			if (((int *)&((struct sockaddr_in6 *)addr)->sin6_addr)[i] != 0)
618 				return ((int *)&((struct sockaddr_in6 *)addr)->sin6_addr)[i];
619 	}
620 	return 0;
621 }
622 
623 /* returns non-zero if addr has a valid and non-null IPv4 or IPv6 address,
624  * or is a unix address, otherwise returns zero.
625  */
is_addr(const struct sockaddr_storage * addr)626 static inline int is_addr(const struct sockaddr_storage *addr)
627 {
628 	if (addr->ss_family == AF_UNIX || addr->ss_family == AF_CUST_SOCKPAIR)
629 		return 1;
630 	else
631 		return is_inet_addr(addr);
632 }
633 
634 /* returns port in network byte order */
get_net_port(struct sockaddr_storage * addr)635 static inline int get_net_port(struct sockaddr_storage *addr)
636 {
637 	switch (addr->ss_family) {
638 	case AF_INET:
639 		return ((struct sockaddr_in *)addr)->sin_port;
640 	case AF_INET6:
641 		return ((struct sockaddr_in6 *)addr)->sin6_port;
642 	}
643 	return 0;
644 }
645 
646 /* returns port in host byte order */
get_host_port(struct sockaddr_storage * addr)647 static inline int get_host_port(struct sockaddr_storage *addr)
648 {
649 	switch (addr->ss_family) {
650 	case AF_INET:
651 		return ntohs(((struct sockaddr_in *)addr)->sin_port);
652 	case AF_INET6:
653 		return ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
654 	}
655 	return 0;
656 }
657 
658 /* returns address len for <addr>'s family, 0 for unknown families */
get_addr_len(const struct sockaddr_storage * addr)659 static inline int get_addr_len(const struct sockaddr_storage *addr)
660 {
661 	switch (addr->ss_family) {
662 	case AF_INET:
663 		return sizeof(struct sockaddr_in);
664 	case AF_INET6:
665 		return sizeof(struct sockaddr_in6);
666 	case AF_UNIX:
667 		return sizeof(struct sockaddr_un);
668 	}
669 	return 0;
670 }
671 
672 /* set port in host byte order */
set_net_port(struct sockaddr_storage * addr,int port)673 static inline int set_net_port(struct sockaddr_storage *addr, int port)
674 {
675 	switch (addr->ss_family) {
676 	case AF_INET:
677 		((struct sockaddr_in *)addr)->sin_port = port;
678 		break;
679 	case AF_INET6:
680 		((struct sockaddr_in6 *)addr)->sin6_port = port;
681 		break;
682 	}
683 	return 0;
684 }
685 
686 /* set port in network byte order */
set_host_port(struct sockaddr_storage * addr,int port)687 static inline int set_host_port(struct sockaddr_storage *addr, int port)
688 {
689 	switch (addr->ss_family) {
690 	case AF_INET:
691 		((struct sockaddr_in *)addr)->sin_port = htons(port);
692 		break;
693 	case AF_INET6:
694 		((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
695 		break;
696 	}
697 	return 0;
698 }
699 
700 /* Convert mask from bit length form to in_addr form.
701  * This function never fails.
702  */
703 void len2mask4(int len, struct in_addr *addr);
704 
705 /* Convert mask from bit length form to in6_addr form.
706  * This function never fails.
707  */
708 void len2mask6(int len, struct in6_addr *addr);
709 
710 /* Return true if IPv4 address is part of the network */
711 extern int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net);
712 
713 /* Return true if IPv6 address is part of the network */
714 extern int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net);
715 
716 /* Map IPv4 address on IPv6 address, as specified in RFC 3513. */
717 extern void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr);
718 
719 /* Map IPv6 address on IPv4 address, as specified in RFC 3513.
720  * Return true if conversion is possible and false otherwise.
721  */
722 extern int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr);
723 
724 /* compare two struct sockaddr_storage and return:
725  *  0 (true)  if the addr is the same in both
726  *  1 (false) if the addr is not the same in both
727  */
728 int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2);
729 
730 /* copy ip from <source> into <dest>
731  * the caller must clear <dest> before calling.
732  * Returns a pointer to the destination
733  */
734 struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest);
735 
736 char *human_time(int t, short hz_div);
737 
738 extern const char *monthname[];
739 
740 /* date2str_log: write a date in the format :
741  * 	sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
742  *		tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
743  *		tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
744  *
745  * without using sprintf. return a pointer to the last char written (\0) or
746  * NULL if there isn't enough space.
747  */
748 char *date2str_log(char *dest, const struct tm *tm, const struct timeval *date, size_t size);
749 
750 /* Return the GMT offset for a specific local time.
751  * Both t and tm must represent the same time.
752  * The string returned has the same format as returned by strftime(... "%z", tm).
753  * Offsets are kept in an internal cache for better performances.
754  */
755 const char *get_gmt_offset(time_t t, struct tm *tm);
756 
757 /* gmt2str_log: write a date in the format :
758  * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
759  * return a pointer to the last char written (\0) or
760  * NULL if there isn't enough space.
761  */
762 char *gmt2str_log(char *dst, struct tm *tm, size_t size);
763 
764 /* localdate2str_log: write a date in the format :
765  * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
766  * Both t and tm must represent the same time.
767  * return a pointer to the last char written (\0) or
768  * NULL if there isn't enough space.
769  */
770 char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size);
771 
772 /* These 3 functions parses date string and fills the
773  * corresponding broken-down time in <tm>. In success case,
774  * it returns 1, otherwise, it returns 0.
775  */
776 int parse_http_date(const char *date, int len, struct tm *tm);
777 int parse_imf_date(const char *date, int len, struct tm *tm);
778 int parse_rfc850_date(const char *date, int len, struct tm *tm);
779 int parse_asctime_date(const char *date, int len, struct tm *tm);
780 
781 /* Dynamically allocates a string of the proper length to hold the formatted
782  * output. NULL is returned on error. The caller is responsible for freeing the
783  * memory area using free(). The resulting string is returned in <out> if the
784  * pointer is not NULL. A previous version of <out> might be used to build the
785  * new string, and it will be freed before returning if it is not NULL, which
786  * makes it possible to build complex strings from iterative calls without
787  * having to care about freeing intermediate values, as in the example below :
788  *
789  *     memprintf(&err, "invalid argument: '%s'", arg);
790  *     ...
791  *     memprintf(&err, "parser said : <%s>\n", *err);
792  *     ...
793  *     free(*err);
794  *
795  * This means that <err> must be initialized to NULL before first invocation.
796  * The return value also holds the allocated string, which eases error checking
797  * and immediate consumption. If the output pointer is not used, NULL must be
798  * passed instead and it will be ignored. The returned message will then also
799  * be NULL so that the caller does not have to bother with freeing anything.
800  *
801  * It is also convenient to use it without any free except the last one :
802  *    err = NULL;
803  *    if (!fct1(err)) report(*err);
804  *    if (!fct2(err)) report(*err);
805  *    if (!fct3(err)) report(*err);
806  *    free(*err);
807  *
808  * memprintf relies on memvprintf. This last version can be called from any
809  * function with variadic arguments.
810  */
811 char *memvprintf(char **out, const char *format, va_list args)
812 	__attribute__ ((format(printf, 2, 0)));
813 
814 char *memprintf(char **out, const char *format, ...)
815 	__attribute__ ((format(printf, 2, 3)));
816 
817 /* Used to add <level> spaces before each line of <out>, unless there is only one line.
818  * The input argument is automatically freed and reassigned. The result will have to be
819  * freed by the caller.
820  * Example of use :
821  *   parse(cmd, &err); (callee: memprintf(&err, ...))
822  *   fprintf(stderr, "Parser said: %s\n", indent_error(&err));
823  *   free(err);
824  */
825 char *indent_msg(char **out, int level);
826 int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first);
827 
828 /* removes environment variable <name> from the environment as found in
829  * environ. This is only provided as an alternative for systems without
830  * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
831  * The principle is to scan environ for each occurrence of variable name
832  * <name> and to replace the matching pointers with the last pointer of
833  * the array (since variables are not ordered).
834  * It always returns 0 (success).
835  */
836 int my_unsetenv(const char *name);
837 
838 /* Convert occurrences of environment variables in the input string to their
839  * corresponding value. A variable is identified as a series of alphanumeric
840  * characters or underscores following a '$' sign. The <in> string must be
841  * free()able. NULL returns NULL. The resulting string might be reallocated if
842  * some expansion is made.
843  */
844 char *env_expand(char *in);
845 uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr);
846 size_t sanitize_for_printing(char *line, size_t pos, size_t width);
847 
848 /* debugging macro to emit messages using write() on fd #-1 so that strace sees
849  * them.
850  */
851 #define fddebug(msg...) do { char *_m = NULL; memprintf(&_m, ##msg); if (_m) write(-1, _m, strlen(_m)); free(_m); } while (0)
852 
853 /* displays a <len> long memory block at <buf>, assuming first byte of <buf>
854  * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
855  * each line. It may be NULL if unused. The output is emitted to file <out>.
856  */
857 void debug_hexdump(FILE *out, const char *pfx, const char *buf, unsigned int baseaddr, int len);
858 
859 /* this is used to emit call traces when building with TRACE=1 */
860 __attribute__((format(printf, 1, 2)))
861 void calltrace(char *fmt, ...);
862 
863 /* same as strstr() but case-insensitive */
864 const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2);
865 
866 /* after increasing a pointer value, it can exceed the first buffer
867  * size. This function transform the value of <ptr> according with
868  * the expected position. <chunks> is an array of the one or two
869  * available chunks. The first value is the start of the first chunk,
870  * the second value if the end+1 of the first chunks. The third value
871  * is NULL or the start of the second chunk and the fourth value is
872  * the end+1 of the second chunk. The function returns 1 if does a
873  * wrap, else returns 0.
874  */
fix_pointer_if_wrap(const char ** chunks,const char ** ptr)875 static inline int fix_pointer_if_wrap(const char **chunks, const char **ptr)
876 {
877 	if (*ptr < chunks[1])
878 		return 0;
879 	if (!chunks[2])
880 		return 0;
881 	*ptr = chunks[2] + ( *ptr - chunks[1] );
882 	return 1;
883 }
884 
885 /************************* Composite address manipulation *********************
886  * Composite addresses are simply unsigned long data in which the higher bits
887  * represent a pointer, and the two lower bits are flags. There are several
888  * places where we just want to associate one or two flags to a pointer (eg,
889  * to type it), and these functions permit this. The pointer is necessarily a
890  * 32-bit aligned pointer, as its two lower bits will be cleared and replaced
891  * with the flags.
892  *****************************************************************************/
893 
894 /* Masks the two lower bits of a composite address and converts it to a
895  * pointer. This is used to mix some bits with some aligned pointers to
896  * structs and to retrieve the original (32-bit aligned) pointer.
897  */
caddr_to_ptr(unsigned long caddr)898 static inline void *caddr_to_ptr(unsigned long caddr)
899 {
900 	return (void *)(caddr & ~3UL);
901 }
902 
903 /* Only retrieves the two lower bits of a composite address. This is used to mix
904  * some bits with some aligned pointers to structs and to retrieve the original
905  * data (2 bits).
906  */
caddr_to_data(unsigned long caddr)907 static inline unsigned int caddr_to_data(unsigned long caddr)
908 {
909 	return (caddr & 3UL);
910 }
911 
912 /* Combines the aligned pointer whose 2 lower bits will be masked with the bits
913  * from <data> to form a composite address. This is used to mix some bits with
914  * some aligned pointers to structs and to retrieve the original (32-bit aligned)
915  * pointer.
916  */
caddr_from_ptr(void * ptr,unsigned int data)917 static inline unsigned long caddr_from_ptr(void *ptr, unsigned int data)
918 {
919 	return (((unsigned long)ptr) & ~3UL) + (data & 3);
920 }
921 
922 /* sets the 2 bits of <data> in the <caddr> composite address */
caddr_set_flags(unsigned long caddr,unsigned int data)923 static inline unsigned long caddr_set_flags(unsigned long caddr, unsigned int data)
924 {
925 	return caddr | (data & 3);
926 }
927 
928 /* clears the 2 bits of <data> in the <caddr> composite address */
caddr_clr_flags(unsigned long caddr,unsigned int data)929 static inline unsigned long caddr_clr_flags(unsigned long caddr, unsigned int data)
930 {
931 	return caddr & ~(unsigned long)(data & 3);
932 }
933 
934 unsigned char utf8_next(const char *s, int len, unsigned int *c);
935 
utf8_return_code(unsigned int code)936 static inline unsigned char utf8_return_code(unsigned int code)
937 {
938 	return code & 0xf0;
939 }
940 
utf8_return_length(unsigned char code)941 static inline unsigned char utf8_return_length(unsigned char code)
942 {
943 	return code & 0x0f;
944 }
945 
946 /* returns a 64-bit a timestamp with the finest resolution available. The
947  * unit is intentionally not specified. It's mostly used to compare dates.
948  */
949 #if defined(__i386__) || defined(__x86_64__)
rdtsc()950 static inline unsigned long long rdtsc()
951 {
952      unsigned int a, d;
953      asm volatile("rdtsc" : "=a" (a), "=d" (d));
954      return a + ((unsigned long long)d << 32);
955 }
956 #else
rdtsc()957 static inline unsigned long long rdtsc()
958 {
959 	struct timeval tv;
960 	gettimeofday(&tv, NULL);
961 	return tv.tv_sec * 1000000 + tv.tv_usec;
962 }
963 #endif
964 
965 /* append a copy of string <str> (in a wordlist) at the end of the list <li>
966  * On failure : return 0 and <err> filled with an error message.
967  * The caller is responsible for freeing the <err> and <str> copy
968  * memory area using free()
969  */
970 struct list;
971 int list_append_word(struct list *li, const char *str, char **err);
972 
973 int dump_text(struct buffer *out, const char *buf, int bsize);
974 int dump_binary(struct buffer *out, const char *buf, int bsize);
975 int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
976                    int *line, int ptr);
977 void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n);
978 void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe);
979 int may_access(const void *ptr);
980 const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr);
981 const char *get_exec_path();
982 
983 #if defined(USE_BACKTRACE)
984 /* Note that this may result in opening libgcc() on first call, so it may need
985  * to have been called once before chrooting.
986  */
my_backtrace(void ** buffer,int max)987 static forceinline int my_backtrace(void **buffer, int max)
988 {
989 #ifdef HA_HAVE_WORKING_BACKTRACE
990 	return backtrace(buffer, max);
991 #else
992 	const struct frame {
993 		const struct frame *next;
994 		void *ra;
995 	} *frame;
996 	int count;
997 
998 	frame = __builtin_frame_address(0);
999 	for (count = 0; count < max && may_access(frame) && may_access(frame->ra);) {
1000 		buffer[count++] = frame->ra;
1001 		frame = frame->next;
1002 	}
1003 	return count;
1004 #endif
1005 }
1006 #endif
1007 
1008 /* same as realloc() except that ptr is also freed upon failure */
my_realloc2(void * ptr,size_t size)1009 static inline void *my_realloc2(void *ptr, size_t size)
1010 {
1011 	void *ret;
1012 
1013 	ret = realloc(ptr, size);
1014 	if (!ret && size)
1015 		free(ptr);
1016 	return ret;
1017 }
1018 
1019 int parse_dotted_uints(const char *s, unsigned int **nums, size_t *sz);
1020 
1021 /* PRNG */
1022 void ha_generate_uuid(struct buffer *output);
1023 void ha_random_seed(const unsigned char *seed, size_t len);
1024 void ha_random_jump96(uint32_t dist);
1025 uint64_t ha_random64();
1026 
ha_random32()1027 static inline uint32_t ha_random32()
1028 {
1029 	return ha_random64() >> 32;
1030 }
1031 
ha_random()1032 static inline int32_t ha_random()
1033 {
1034 	return ha_random32() >> 1;
1035 }
1036 
1037 #endif /* _HAPROXY_TOOLS_H */
1038