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