2 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
26 #ifndef UTIL_INTERNAL_H_INCLUDED_
27 #define UTIL_INTERNAL_H_INCLUDED_
29 #include "event2/event-config.h"
30 #include "evconfig-private.h"
34 /* For EVUTIL_ASSERT */
35 #include "log-internal.h"
38 #ifdef EVENT__HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
41 #ifdef EVENT__HAVE_SYS_EVENTFD_H
42 #include <sys/eventfd.h>
44 #include "event2/util.h"
46 #include "time-internal.h"
47 #include "ipv6-internal.h"
53 /* If we need magic to say "inline", get it for free internally. */
55 #define inline EVENT__inline
57 #ifdef EVENT____func__
58 #define __func__ EVENT____func__
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.
68 #define EVUTIL_NIL_CONDITION_(condition) do { \
69 (void)sizeof(!(condition)); \
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. */
82 #if EAGAIN == EWOULDBLOCK
83 #define EVUTIL_ERR_IS_EAGAIN(e) \
86 #define EVUTIL_ERR_IS_EAGAIN(e) \
87 ((e) == EAGAIN || (e) == EWOULDBLOCK)
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)
100 /* True iff e is an error that means the connection was refused */
101 #define EVUTIL_ERR_CONNECT_REFUSED(e) \
102 ((e) == ECONNREFUSED)
107 #define EVUTIL_ERR_IS_EAGAIN(e) \
108 ((e) == WSAEWOULDBLOCK || (e) == EAGAIN)
110 #define EVUTIL_ERR_RW_RETRIABLE(e) \
111 ((e) == WSAEWOULDBLOCK || \
114 #define EVUTIL_ERR_CONNECT_RETRIABLE(e) \
115 ((e) == WSAEWOULDBLOCK || \
117 (e) == WSAEINPROGRESS || \
120 #define EVUTIL_ERR_ACCEPT_RETRIABLE(e) \
121 EVUTIL_ERR_RW_RETRIABLE(e)
123 #define EVUTIL_ERR_CONNECT_REFUSED(e) \
124 ((e) == WSAECONNREFUSED)
128 /* Arguments for shutdown() */
130 #define EVUTIL_SHUT_RD SHUT_RD
132 #define EVUTIL_SHUT_RD 0
135 #define EVUTIL_SHUT_WR SHUT_WR
137 #define EVUTIL_SHUT_WR 1
140 #define EVUTIL_SHUT_BOTH SHUT_BOTH
142 #define EVUTIL_SHUT_BOTH 2
145 /* Helper: Verify that all the elements in 'dlist' are internally consistent.
146 * Checks for circular lists and bad prev/next pointers.
149 * EVUTIL_ASSERT_LIST_OK(eventlist, event, ev_next);
151 #define EVUTIL_ASSERT_LIST_OK(dlist, type, field) do { \
152 struct type *elm1, *elm2, **nextp; \
153 if (LIST_EMPTY((dlist))) \
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); \
166 EVUTIL_ASSERT(elm1 != elm2); \
167 elm2 = LIST_NEXT(elm2, field); \
170 /* Now check next and prev pointers for consistency. */ \
171 nextp = &LIST_FIRST((dlist)); \
172 elm1 = LIST_FIRST((dlist)); \
174 EVUTIL_ASSERT(*nextp == elm1); \
175 EVUTIL_ASSERT(nextp == elm1->field.le_prev); \
176 nextp = &LIST_NEXT(elm1, field); \
181 /* Helper: Verify that all the elements in a TAILQ are internally consistent.
182 * Checks for circular lists and bad prev/next pointers.
185 * EVUTIL_ASSERT_TAILQ_OK(activelist, event, ev_active_next);
187 #define EVUTIL_ASSERT_TAILQ_OK(tailq, type, field) do { \
188 struct type *elm1, *elm2, **nextp; \
189 if (TAILQ_EMPTY((tailq))) \
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); \
202 EVUTIL_ASSERT(elm1 != elm2); \
203 elm2 = TAILQ_NEXT(elm2, field); \
206 /* Now check next and prev pointers for consistency. */ \
207 nextp = &TAILQ_FIRST((tailq)); \
208 elm1 = TAILQ_FIRST((tailq)); \
210 EVUTIL_ASSERT(*nextp == elm1); \
211 EVUTIL_ASSERT(nextp == elm1->field.tqe_prev); \
212 nextp = &TAILQ_NEXT(elm1, field); \
215 EVUTIL_ASSERT(nextp == (tailq)->tqh_last); \
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.
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
);
233 /** Remove all trailing horizontal whitespace (space or tab) from the end of a
235 void evutil_rtrim_lws_(char *);
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:
244 struct supertype common;
248 void fn(struct supertype *super) {
249 struct subtype *sub = EVUTIL_UPCAST(super, struct subtype, common);
253 #define EVUTIL_UPCAST(ptr, type, field) \
254 ((type *)(((char*)(ptr)) - evutil_offsetof(type, field)))
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.)
259 int evutil_open_closeonexec_(const char *pathname
, int flags
, unsigned mode
);
261 int evutil_read_file_(const char *filename
, char **content_out
, size_t *len_out
,
264 int evutil_socket_connect_(evutil_socket_t
*fd_ptr
, const struct sockaddr
*sa
, int socklen
);
266 int evutil_socket_finished_connecting_(evutil_socket_t fd
);
268 int evutil_ersatz_socketpair_(int, int , int, evutil_socket_t
[]);
270 int evutil_resolve_(int family
, const char *hostname
, struct sockaddr
*sa
,
271 ev_socklen_t
*socklen
, int port
);
273 const char *evutil_getenv_(const char *name
);
275 /* Structure to hold the state of our weak random number generator.
277 struct evutil_weakrand_state
{
281 #define EVUTIL_WEAKRAND_MAX EV_INT32_MAX
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.
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.
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
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
);
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)
308 #define EVUTIL_UNLIKELY(p) (p)
311 /* Replacement for assert() that calls event_errx on failure. */
313 #define EVUTIL_ASSERT(cond) EVUTIL_NIL_CONDITION_(cond)
314 #define EVUTIL_FAILURE_CHECK(cond) 0
316 #define EVUTIL_ASSERT(cond) \
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__); \
330 #define EVUTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
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.
337 struct sockaddr_storage
{
339 struct sockaddr ss_sa
;
340 struct sockaddr_in ss_sin
;
341 struct sockaddr_in6 ss_sin6
;
342 char ss_padding
[128];
345 #define ss_family ss_union.ss_sa.sa_family
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
351 #define EVUTIL_EAI_NEED_RESOLVE -90002
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
);
361 void evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn
);
363 struct evutil_addrinfo
*evutil_new_addrinfo_(struct sockaddr
*sa
,
364 ev_socklen_t socklen
, const struct evutil_addrinfo
*hints
);
365 struct evutil_addrinfo
*evutil_addrinfo_append_(struct evutil_addrinfo
*first
,
366 struct evutil_addrinfo
*append
);
367 void evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo
*hints
);
368 int evutil_getaddrinfo_common_(const char *nodename
, const char *servname
,
369 struct evutil_addrinfo
*hints
, struct evutil_addrinfo
**res
, int *portnum
);
371 int evutil_getaddrinfo_async_(struct evdns_base
*dns_base
,
372 const char *nodename
, const char *servname
,
373 const struct evutil_addrinfo
*hints_in
,
374 void (*cb
)(int, struct evutil_addrinfo
*, void *), void *arg
);
376 /** Return true iff sa is a looback address. (That is, it is 127.0.0.1/8, or
378 int evutil_sockaddr_is_loopback_(const struct sockaddr
*sa
);
382 Formats a sockaddr sa into a string buffer of size outlen stored in out.
383 Returns a pointer to out. Always writes something into out, so it's safe
384 to use the output of this function without checking it for NULL.
386 const char *evutil_format_sockaddr_port_(const struct sockaddr
*sa
, char *out
, size_t outlen
);
388 int evutil_hex_char_to_int_(char c
);
391 void evutil_free_secure_rng_globals_(void);
392 void evutil_free_globals_(void);
395 HMODULE
evutil_load_windows_system_library_(const TCHAR
*library_name
);
399 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
400 #define EV_U64_FMT "%I64u"
401 #define EV_I64_FMT "%I64d"
402 #define EV_I64_ARG(x) ((__int64)(x))
403 #define EV_U64_ARG(x) ((unsigned __int64)(x))
405 #define EV_U64_FMT "%llu"
406 #define EV_I64_FMT "%lld"
407 #define EV_I64_ARG(x) ((long long)(x))
408 #define EV_U64_ARG(x) ((unsigned long long)(x))
413 #define EV_SOCK_FMT EV_I64_FMT
414 #define EV_SOCK_ARG(x) EV_I64_ARG((x))
416 #define EV_SOCK_FMT "%d"
417 #define EV_SOCK_ARG(x) (x)
420 #if defined(__STDC__) && defined(__STDC_VERSION__)
421 #if (__STDC_VERSION__ >= 199901L)
422 #define EV_SIZE_FMT "%zu"
423 #define EV_SSIZE_FMT "%zd"
424 #define EV_SIZE_ARG(x) (x)
425 #define EV_SSIZE_ARG(x) (x)
430 #if (EVENT__SIZEOF_SIZE_T <= EVENT__SIZEOF_LONG)
431 #define EV_SIZE_FMT "%lu"
432 #define EV_SSIZE_FMT "%ld"
433 #define EV_SIZE_ARG(x) ((unsigned long)(x))
434 #define EV_SSIZE_ARG(x) ((long)(x))
436 #define EV_SIZE_FMT EV_U64_FMT
437 #define EV_SSIZE_FMT EV_I64_FMT
438 #define EV_SIZE_ARG(x) EV_U64_ARG(x)
439 #define EV_SSIZE_ARG(x) EV_I64_ARG(x)
443 evutil_socket_t
evutil_socket_(int domain
, int type
, int protocol
);
444 evutil_socket_t
evutil_accept4_(evutil_socket_t sockfd
, struct sockaddr
*addr
,
445 ev_socklen_t
*addrlen
, int flags
);
447 /* used by one of the test programs.. */
449 int evutil_make_internal_pipe_(evutil_socket_t fd
[2]);
450 evutil_socket_t
evutil_eventfd_(unsigned initval
, int flags
);
453 #define EVUTIL_SOCK_NONBLOCK SOCK_NONBLOCK
455 #define EVUTIL_SOCK_NONBLOCK 0x4000000
458 #define EVUTIL_SOCK_CLOEXEC SOCK_CLOEXEC
460 #define EVUTIL_SOCK_CLOEXEC 0x80000000
463 #define EVUTIL_EFD_NONBLOCK EFD_NONBLOCK
465 #define EVUTIL_EFD_NONBLOCK 0x4000
468 #define EVUTIL_EFD_CLOEXEC EFD_CLOEXEC
470 #define EVUTIL_EFD_CLOEXEC 0x8000
473 void evutil_memclear_(void *mem
, size_t len
);