xref: /netbsd-src/external/bsd/libevent/dist/util-internal.h (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: util-internal.h,v 1.4 2017/01/31 23:17:39 christos Exp $	*/
2 /*
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 #ifndef UTIL_INTERNAL_H_INCLUDED_
28 #define UTIL_INTERNAL_H_INCLUDED_
29 
30 #include "event2/event-config.h"
31 #include "evconfig-private.h"
32 
33 #include <errno.h>
34 
35 /* For EVUTIL_ASSERT */
36 #include "log-internal.h"
37 #include <stdio.h>
38 #include <stdlib.h>
39 #ifdef EVENT__HAVE_SYS_SOCKET_H
40 #include <sys/socket.h>
41 #endif
42 #ifdef EVENT__HAVE_SYS_EVENTFD_H
43 #include <sys/eventfd.h>
44 #endif
45 #include "event2/util.h"
46 
47 #include "time-internal.h"
48 #include "ipv6-internal.h"
49 
50 #ifdef __cplusplus
51 extern "C" {
52 #endif
53 
54 /* If we need magic to say "inline", get it for free internally. */
55 #ifdef EVENT__inline
56 #define inline EVENT__inline
57 #endif
58 #if defined(EVENT____func__) && !defined(__func__)
59 #define __func__ EVENT____func__
60 #endif
61 
62 /* A good no-op to use in macro definitions. */
63 #define EVUTIL_NIL_STMT_ ((void)0)
64 /* A no-op that tricks the compiler into thinking a condition is used while
65  * definitely not making any code for it.  Used to compile out asserts while
66  * avoiding "unused variable" warnings.  The "!" forces the compiler to
67  * do the sizeof() on an int, in case "condition" is a bitfield value.
68  */
69 #define EVUTIL_NIL_CONDITION_(condition) do { \
70 	(void)sizeof(!(condition));  \
71 } while(/*CONSTCOND*/0)
72 
73 /* Internal use only: macros to match patterns of error codes in a
74    cross-platform way.  We need these macros because of two historical
75    reasons: first, nonblocking IO functions are generally written to give an
76    error on the "blocked now, try later" case, so sometimes an error from a
77    read, write, connect, or accept means "no error; just wait for more
78    data," and we need to look at the error code.  Second, Windows defines
79    a different set of error codes for sockets. */
80 
81 #ifndef _WIN32
82 
83 #if EAGAIN == EWOULDBLOCK
84 #define EVUTIL_ERR_IS_EAGAIN(e) \
85 	((e) == EAGAIN)
86 #else
87 #define EVUTIL_ERR_IS_EAGAIN(e) \
88 	((e) == EAGAIN || (e) == EWOULDBLOCK)
89 #endif
90 
91 /* True iff e is an error that means a read/write operation can be retried. */
92 #define EVUTIL_ERR_RW_RETRIABLE(e)				\
93 	((e) == EINTR || EVUTIL_ERR_IS_EAGAIN(e))
94 /* True iff e is an error that means an connect can be retried. */
95 #define EVUTIL_ERR_CONNECT_RETRIABLE(e)			\
96 	((e) == EINTR || (e) == EINPROGRESS)
97 /* True iff e is an error that means a accept can be retried. */
98 #define EVUTIL_ERR_ACCEPT_RETRIABLE(e)			\
99 	((e) == EINTR || EVUTIL_ERR_IS_EAGAIN(e) || (e) == ECONNABORTED)
100 
101 /* True iff e is an error that means the connection was refused */
102 #define EVUTIL_ERR_CONNECT_REFUSED(e)					\
103 	((e) == ECONNREFUSED)
104 
105 #else
106 /* Win32 */
107 
108 #define EVUTIL_ERR_IS_EAGAIN(e) \
109 	((e) == WSAEWOULDBLOCK || (e) == EAGAIN)
110 
111 #define EVUTIL_ERR_RW_RETRIABLE(e)					\
112 	((e) == WSAEWOULDBLOCK ||					\
113 	    (e) == WSAEINTR)
114 
115 #define EVUTIL_ERR_CONNECT_RETRIABLE(e)					\
116 	((e) == WSAEWOULDBLOCK ||					\
117 	    (e) == WSAEINTR ||						\
118 	    (e) == WSAEINPROGRESS ||					\
119 	    (e) == WSAEINVAL)
120 
121 #define EVUTIL_ERR_ACCEPT_RETRIABLE(e)			\
122 	EVUTIL_ERR_RW_RETRIABLE(e)
123 
124 #define EVUTIL_ERR_CONNECT_REFUSED(e)					\
125 	((e) == WSAECONNREFUSED)
126 
127 #endif
128 
129 /* Arguments for shutdown() */
130 #ifdef SHUT_RD
131 #define EVUTIL_SHUT_RD SHUT_RD
132 #else
133 #define EVUTIL_SHUT_RD 0
134 #endif
135 #ifdef SHUT_WR
136 #define EVUTIL_SHUT_WR SHUT_WR
137 #else
138 #define EVUTIL_SHUT_WR 1 /* SD_SEND */
139 #endif
140 #ifdef SHUT_BOTH
141 #define EVUTIL_SHUT_BOTH SHUT_BOTH
142 #else
143 #define EVUTIL_SHUT_BOTH 2
144 #endif
145 
146 /* Helper: Verify that all the elements in 'dlist' are internally consistent.
147  * Checks for circular lists and bad prev/next pointers.
148  *
149  * Example usage:
150  *    EVUTIL_ASSERT_LIST_OK(eventlist, event, ev_next);
151  */
152 #define EVUTIL_ASSERT_LIST_OK(dlist, type, field) do {			\
153 		struct type *elm1, *elm2, **nextp;			\
154 		if (LIST_EMPTY((dlist)))				\
155 			break;						\
156 									\
157 		/* Check list for circularity using Floyd's */		\
158 		/* 'Tortoise and Hare' algorithm */			\
159 		elm1 = LIST_FIRST((dlist));				\
160 		elm2 = LIST_NEXT(elm1, field);				\
161 		while (elm1 && elm2) {					\
162 			EVUTIL_ASSERT(elm1 != elm2);			\
163 			elm1 = LIST_NEXT(elm1, field);			\
164 			elm2 = LIST_NEXT(elm2, field);			\
165 			if (!elm2)					\
166 				break;					\
167 			EVUTIL_ASSERT(elm1 != elm2);			\
168 			elm2 = LIST_NEXT(elm2, field);			\
169 		}							\
170 									\
171 		/* Now check next and prev pointers for consistency. */ \
172 		nextp = &LIST_FIRST((dlist));				\
173 		elm1 = LIST_FIRST((dlist));				\
174 		while (elm1) {						\
175 			EVUTIL_ASSERT(*nextp == elm1);			\
176 			EVUTIL_ASSERT(nextp == elm1->field.le_prev);	\
177 			nextp = &LIST_NEXT(elm1, field);		\
178 			elm1 = *nextp;					\
179 		}							\
180 	} while (0)
181 
182 /* Helper: Verify that all the elements in a TAILQ are internally consistent.
183  * Checks for circular lists and bad prev/next pointers.
184  *
185  * Example usage:
186  *    EVUTIL_ASSERT_TAILQ_OK(activelist, event, ev_active_next);
187  */
188 #define EVUTIL_ASSERT_TAILQ_OK(tailq, type, field) do {			\
189 		struct type *elm1, *elm2, **nextp;			\
190 		if (TAILQ_EMPTY((tailq)))				\
191 			break;						\
192 									\
193 		/* Check list for circularity using Floyd's */		\
194 		/* 'Tortoise and Hare' algorithm */			\
195 		elm1 = TAILQ_FIRST((tailq));				\
196 		elm2 = TAILQ_NEXT(elm1, field);				\
197 		while (elm1 && elm2) {					\
198 			EVUTIL_ASSERT(elm1 != elm2);			\
199 			elm1 = TAILQ_NEXT(elm1, field);			\
200 			elm2 = TAILQ_NEXT(elm2, field);			\
201 			if (!elm2)					\
202 				break;					\
203 			EVUTIL_ASSERT(elm1 != elm2);			\
204 			elm2 = TAILQ_NEXT(elm2, field);			\
205 		}							\
206 									\
207 		/* Now check next and prev pointers for consistency. */ \
208 		nextp = &TAILQ_FIRST((tailq));				\
209 		elm1 = TAILQ_FIRST((tailq));				\
210 		while (elm1) {						\
211 			EVUTIL_ASSERT(*nextp == elm1);			\
212 			EVUTIL_ASSERT(nextp == elm1->field.tqe_prev);	\
213 			nextp = &TAILQ_NEXT(elm1, field);		\
214 			elm1 = *nextp;					\
215 		}							\
216 		EVUTIL_ASSERT(nextp == (tailq)->tqh_last);		\
217 	} while (0)
218 
219 /* Locale-independent replacements for some ctypes functions.  Use these
220  * when you care about ASCII's notion of character types, because you are about
221  * to send those types onto the wire.
222  */
223 int EVUTIL_ISALPHA_(char c);
224 int EVUTIL_ISALNUM_(char c);
225 int EVUTIL_ISSPACE_(char c);
226 int EVUTIL_ISDIGIT_(char c);
227 int EVUTIL_ISXDIGIT_(char c);
228 int EVUTIL_ISPRINT_(char c);
229 int EVUTIL_ISLOWER_(char c);
230 int EVUTIL_ISUPPER_(char c);
231 char EVUTIL_TOUPPER_(char c);
232 char EVUTIL_TOLOWER_(char c);
233 
234 /** Remove all trailing horizontal whitespace (space or tab) from the end of a
235  * string */
236 void evutil_rtrim_lws_(char *);
237 
238 
239 /** Helper macro.  If we know that a given pointer points to a field in a
240     structure, return a pointer to the structure itself.  Used to implement
241     our half-baked C OO.  Example:
242 
243     struct subtype {
244 	int x;
245 	struct supertype common;
246 	int y;
247     };
248     ...
249     void fn(struct supertype *super) {
250 	struct subtype *sub = EVUTIL_UPCAST(super, struct subtype, common);
251 	...
252     }
253  */
254 #define EVUTIL_UPCAST(ptr, type, field)				\
255 	((type *)__UNCONST(((const char *)(ptr)) - evutil_offsetof(type, field)))
256 
257 /* As open(pathname, flags, mode), except that the file is always opened with
258  * the close-on-exec flag set. (And the mode argument is mandatory.)
259  */
260 int evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode);
261 
262 int evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
263     int is_binary);
264 
265 int evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen);
266 
267 int evutil_socket_finished_connecting_(evutil_socket_t fd);
268 
269 int evutil_ersatz_socketpair_(int, int , int, evutil_socket_t[]);
270 
271 int evutil_resolve_(int family, const char *hostname, struct sockaddr *sa,
272     ev_socklen_t *socklen, int port);
273 
274 const char *evutil_getenv_(const char *name);
275 
276 /* Structure to hold the state of our weak random number generator.
277  */
278 struct evutil_weakrand_state {
279 	ev_uint32_t seed;
280 };
281 
282 #define EVUTIL_WEAKRAND_MAX EV_INT32_MAX
283 
284 /* Initialize the state of a week random number generator based on 'seed'.  If
285  * the seed is 0, construct a new seed based on not-very-strong platform
286  * entropy, like the PID and the time of day.
287  *
288  * This function, and the other evutil_weakrand* functions, are meant for
289  * speed, not security or statistical strength.  If you need a RNG which an
290  * attacker can't predict, or which passes strong statistical tests, use the
291  * evutil_secure_rng* functions instead.
292  */
293 ev_uint32_t evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed);
294 /* Return a pseudorandom value between 0 and EVUTIL_WEAKRAND_MAX inclusive.
295  * Updates the state in 'seed' as needed -- this value must be protected by a
296  * lock.
297  */
298 ev_int32_t evutil_weakrand_(struct evutil_weakrand_state *seed);
299 /* Return a pseudorandom value x such that 0 <= x < top. top must be no more
300  * than EVUTIL_WEAKRAND_MAX. Updates the state in 'seed' as needed -- this
301  * value must be proteced by a lock */
302 ev_int32_t evutil_weakrand_range_(struct evutil_weakrand_state *seed, ev_int32_t top);
303 
304 /* Evaluates to the same boolean value as 'p', and hints to the compiler that
305  * we expect this value to be false. */
306 #if defined(__GNUC__) && __GNUC__ >= 3         /* gcc 3.0 or later */
307 #define EVUTIL_UNLIKELY(p) __builtin_expect(!!(p),0)
308 #else
309 #define EVUTIL_UNLIKELY(p) (p)
310 #endif
311 
312 /* Replacement for assert() that calls event_errx on failure. */
313 #ifdef NDEBUG
314 #define EVUTIL_ASSERT(cond) EVUTIL_NIL_CONDITION_(cond)
315 #define EVUTIL_FAILURE_CHECK(cond) 0
316 #else
317 #define EVUTIL_ASSERT(cond)						\
318 	do {								\
319 		if (EVUTIL_UNLIKELY(!(cond))) {				\
320 			event_errx(EVENT_ERR_ABORT_,			\
321 			    "%s:%d: Assertion %s failed in %s",		\
322 			    __FILE__,__LINE__,#cond,__func__);		\
323 			/* In case a user-supplied handler tries to */	\
324 			/* return control to us, log and abort here. */	\
325 			(void)fprintf(stderr,				\
326 			    "%s:%d: Assertion %s failed in %s",		\
327 			    __FILE__,__LINE__,#cond,__func__);		\
328 			abort();					\
329 		}							\
330 	} while (/*CONSTCOND*/0)
331 #define EVUTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
332 #endif
333 
334 #ifndef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE
335 /* Replacement for sockaddr storage that we can use internally on platforms
336  * that lack it.  It is not space-efficient, but neither is sockaddr_storage.
337  */
338 struct sockaddr_storage {
339 	union {
340 		struct sockaddr ss_sa;
341 		struct sockaddr_in ss_sin;
342 		struct sockaddr_in6 ss_sin6;
343 		char ss_padding[128];
344 	} ss_union;
345 };
346 #define ss_family ss_union.ss_sa.sa_family
347 #endif
348 
349 /* Internal addrinfo error code.  This one is returned from only from
350  * evutil_getaddrinfo_common_, when we are sure that we'll have to hit a DNS
351  * server. */
352 #define EVUTIL_EAI_NEED_RESOLVE      -90002
353 
354 struct evdns_base;
355 struct evdns_getaddrinfo_request;
356 typedef struct evdns_getaddrinfo_request* (*evdns_getaddrinfo_fn)(
357     struct evdns_base *base,
358     const char *nodename, const char *servname,
359     const struct evutil_addrinfo *hints_in,
360     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
361 void evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn);
362 typedef void (*evdns_getaddrinfo_cancel_fn)(
363     struct evdns_getaddrinfo_request *req);
364 void evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn);
365 
366 struct evutil_addrinfo *evutil_new_addrinfo_(struct sockaddr *sa,
367     ev_socklen_t socklen, const struct evutil_addrinfo *hints);
368 struct evutil_addrinfo *evutil_addrinfo_append_(struct evutil_addrinfo *first,
369     struct evutil_addrinfo *append);
370 void evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints);
371 int evutil_getaddrinfo_common_(const char *nodename, const char *servname,
372     struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum);
373 
374 struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
375     struct evdns_base *dns_base,
376     const char *nodename, const char *servname,
377     const struct evutil_addrinfo *hints_in,
378     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
379 void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data);
380 
381 /** Return true iff sa is a looback address. (That is, it is 127.0.0.1/8, or
382  * ::1). */
383 int evutil_sockaddr_is_loopback_(const struct sockaddr *sa);
384 
385 
386 /**
387     Formats a sockaddr sa into a string buffer of size outlen stored in out.
388     Returns a pointer to out.  Always writes something into out, so it's safe
389     to use the output of this function without checking it for NULL.
390  */
391 const char *evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen);
392 
393 int evutil_hex_char_to_int_(char c);
394 
395 
396 void evutil_free_secure_rng_globals_(void);
397 void evutil_free_globals_(void);
398 
399 #ifdef _WIN32
400 HMODULE evutil_load_windows_system_library_(const TCHAR *library_name);
401 #endif
402 
403 #ifndef EV_SIZE_FMT
404 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
405 #define EV_U64_FMT "%I64u"
406 #define EV_I64_FMT "%I64d"
407 #define EV_I64_ARG(x) ((__int64)(x))
408 #define EV_U64_ARG(x) ((unsigned __int64)(x))
409 #else
410 #define EV_U64_FMT "%llu"
411 #define EV_I64_FMT "%lld"
412 #define EV_I64_ARG(x) ((long long)(x))
413 #define EV_U64_ARG(x) ((unsigned long long)(x))
414 #endif
415 #endif
416 
417 #ifdef _WIN32
418 #define EV_SOCK_FMT EV_I64_FMT
419 #define EV_SOCK_ARG(x) EV_I64_ARG((x))
420 #else
421 #define EV_SOCK_FMT "%d"
422 #define EV_SOCK_ARG(x) (x)
423 #endif
424 
425 #if defined(__STDC__) && defined(__STDC_VERSION__) && !defined(__MINGW64_VERSION_MAJOR)
426 #if (__STDC_VERSION__ >= 199901L)
427 #define EV_SIZE_FMT "%zu"
428 #define EV_SSIZE_FMT "%zd"
429 #define EV_SIZE_ARG(x) (x)
430 #define EV_SSIZE_ARG(x) (x)
431 #endif
432 #endif
433 
434 #ifndef EV_SIZE_FMT
435 #if (EVENT__SIZEOF_SIZE_T <= EVENT__SIZEOF_LONG)
436 #define EV_SIZE_FMT "%lu"
437 #define EV_SSIZE_FMT "%ld"
438 #define EV_SIZE_ARG(x) ((unsigned long)(x))
439 #define EV_SSIZE_ARG(x) ((long)(x))
440 #else
441 #define EV_SIZE_FMT EV_U64_FMT
442 #define EV_SSIZE_FMT EV_I64_FMT
443 #define EV_SIZE_ARG(x) EV_U64_ARG(x)
444 #define EV_SSIZE_ARG(x) EV_I64_ARG(x)
445 #endif
446 #endif
447 
448 evutil_socket_t evutil_socket_(int domain, int type, int protocol);
449 evutil_socket_t evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
450     ev_socklen_t *addrlen, int flags);
451 
452     /* used by one of the test programs.. */
453 EVENT2_EXPORT_SYMBOL
454 int evutil_make_internal_pipe_(evutil_socket_t fd[2]);
455 evutil_socket_t evutil_eventfd_(unsigned initval, int flags);
456 
457 #ifdef SOCK_NONBLOCK
458 #define EVUTIL_SOCK_NONBLOCK SOCK_NONBLOCK
459 #else
460 #define EVUTIL_SOCK_NONBLOCK 0x4000000
461 #endif
462 #ifdef SOCK_CLOEXEC
463 #define EVUTIL_SOCK_CLOEXEC SOCK_CLOEXEC
464 #else
465 #define EVUTIL_SOCK_CLOEXEC 0x80000000
466 #endif
467 #ifdef EFD_NONBLOCK
468 #define EVUTIL_EFD_NONBLOCK EFD_NONBLOCK
469 #else
470 #define EVUTIL_EFD_NONBLOCK 0x4000
471 #endif
472 #ifdef EFD_CLOEXEC
473 #define EVUTIL_EFD_CLOEXEC EFD_CLOEXEC
474 #else
475 #define EVUTIL_EFD_CLOEXEC 0x8000
476 #endif
477 
478 void evutil_memclear_(void *mem, size_t len);
479 
480 #ifdef __cplusplus
481 }
482 #endif
483 
484 #endif
485