1 /*	$NetBSD: util-internal.h,v 1.3 2015/01/29 07:26:02 spz 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 _EVENT_UTIL_INTERNAL_H
28 #define _EVENT_UTIL_INTERNAL_H
29 
30 #include "event2/event-config.h"
31 #include <errno.h>
32 
33 /* For EVUTIL_ASSERT */
34 #include "log-internal.h"
35 #include <stdio.h>
36 #include <stdlib.h>
37 #ifdef _EVENT_HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #include "event2/util.h"
41 
42 #include "ipv6-internal.h"
43 
44 #ifdef __cplusplus
45 extern "C" {
46 #endif
47 
48 /* If we need magic to say "inline", get it for free internally. */
49 #ifdef _EVENT_inline
50 #define inline _EVENT_inline
51 #endif
52 #ifdef _EVENT___func__
53 #define __func__ _EVENT___func__
54 #endif
55 
56 /* A good no-op to use in macro definitions. */
57 #define _EVUTIL_NIL_STMT ((void)0)
58 /* A no-op that tricks the compiler into thinking a condition is used while
59  * definitely not making any code for it.  Used to compile out asserts while
60  * avoiding "unused variable" warnings.  The "!" forces the compiler to
61  * do the sizeof() on an int, in case "condition" is a bitfield value.
62  */
63 #define _EVUTIL_NIL_CONDITION(condition) do { \
64 	(void)sizeof(!(condition));  \
65 } while(/*CONSTCOND*/0)
66 
67 /* Internal use only: macros to match patterns of error codes in a
68    cross-platform way.  We need these macros because of two historical
69    reasons: first, nonblocking IO functions are generally written to give an
70    error on the "blocked now, try later" case, so sometimes an error from a
71    read, write, connect, or accept means "no error; just wait for more
72    data," and we need to look at the error code.  Second, Windows defines
73    a different set of error codes for sockets. */
74 
75 #ifndef WIN32
76 
77 /* True iff e is an error that means a read/write operation can be retried. */
78 #define EVUTIL_ERR_RW_RETRIABLE(e)				\
79 	((e) == EINTR || (e) == EAGAIN)
80 /* True iff e is an error that means an connect can be retried. */
81 #define EVUTIL_ERR_CONNECT_RETRIABLE(e)			\
82 	((e) == EINTR || (e) == EINPROGRESS)
83 /* True iff e is an error that means a accept can be retried. */
84 #define EVUTIL_ERR_ACCEPT_RETRIABLE(e)			\
85 	((e) == EINTR || (e) == EAGAIN || (e) == ECONNABORTED)
86 
87 /* True iff e is an error that means the connection was refused */
88 #define EVUTIL_ERR_CONNECT_REFUSED(e)					\
89 	((e) == ECONNREFUSED)
90 
91 #else
92 
93 #define EVUTIL_ERR_RW_RETRIABLE(e)					\
94 	((e) == WSAEWOULDBLOCK ||					\
95 	    (e) == WSAEINTR)
96 
97 #define EVUTIL_ERR_CONNECT_RETRIABLE(e)					\
98 	((e) == WSAEWOULDBLOCK ||					\
99 	    (e) == WSAEINTR ||						\
100 	    (e) == WSAEINPROGRESS ||					\
101 	    (e) == WSAEINVAL)
102 
103 #define EVUTIL_ERR_ACCEPT_RETRIABLE(e)			\
104 	EVUTIL_ERR_RW_RETRIABLE(e)
105 
106 #define EVUTIL_ERR_CONNECT_REFUSED(e)					\
107 	((e) == WSAECONNREFUSED)
108 
109 #endif
110 
111 #ifdef _EVENT_socklen_t
112 #define socklen_t _EVENT_socklen_t
113 #endif
114 
115 /* Arguments for shutdown() */
116 #ifdef SHUT_RD
117 #define EVUTIL_SHUT_RD SHUT_RD
118 #else
119 #define EVUTIL_SHUT_RD 0
120 #endif
121 #ifdef SHUT_WR
122 #define EVUTIL_SHUT_WR SHUT_WR
123 #else
124 #define EVUTIL_SHUT_WR 1
125 #endif
126 #ifdef SHUT_BOTH
127 #define EVUTIL_SHUT_BOTH SHUT_BOTH
128 #else
129 #define EVUTIL_SHUT_BOTH 2
130 #endif
131 
132 /* Locale-independent replacements for some ctypes functions.  Use these
133  * when you care about ASCII's notion of character types, because you are about
134  * to send those types onto the wire.
135  */
136 int EVUTIL_ISALPHA(char c);
137 int EVUTIL_ISALNUM(char c);
138 int EVUTIL_ISSPACE(char c);
139 int EVUTIL_ISDIGIT(char c);
140 int EVUTIL_ISXDIGIT(char c);
141 int EVUTIL_ISPRINT(char c);
142 int EVUTIL_ISLOWER(char c);
143 int EVUTIL_ISUPPER(char c);
144 char EVUTIL_TOUPPER(char c);
145 char EVUTIL_TOLOWER(char c);
146 
147 /** Helper macro.  If we know that a given pointer points to a field in a
148     structure, return a pointer to the structure itself.  Used to implement
149     our half-baked C OO.  Example:
150 
151     struct subtype {
152 	int x;
153 	struct supertype common;
154 	int y;
155     };
156     ...
157     void fn(struct supertype *super) {
158 	struct subtype *sub = EVUTIL_UPCAST(super, struct subtype, common);
159 	...
160     }
161  */
162 #define EVUTIL_UPCAST(ptr, type, field)				\
163 	((type *)(((char*)(ptr)) - evutil_offsetof(type, field)))
164 
165 /* As open(pathname, flags, mode), except that the file is always opened with
166  * the close-on-exec flag set. (And the mode argument is mandatory.)
167  */
168 int evutil_open_closeonexec(const char *pathname, int flags, unsigned mode);
169 
170 int evutil_read_file(const char *filename, char **content_out, size_t *len_out,
171     int is_binary);
172 
173 int evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen);
174 
175 int evutil_socket_finished_connecting(evutil_socket_t fd);
176 
177 int evutil_ersatz_socketpair(int, int , int, evutil_socket_t[]);
178 
179 int evutil_resolve(int family, const char *hostname, struct sockaddr *sa,
180     ev_socklen_t *socklen, int port);
181 
182 const char *evutil_getenv(const char *name);
183 
184 long _evutil_weakrand(void);
185 
186 /* Evaluates to the same boolean value as 'p', and hints to the compiler that
187  * we expect this value to be false. */
188 #if defined(__GNUC__) && __GNUC__ >= 3         /* gcc 3.0 or later */
189 #define EVUTIL_UNLIKELY(p) __builtin_expect(!!(p),0)
190 #else
191 #define EVUTIL_UNLIKELY(p) (p)
192 #endif
193 
194 /* Replacement for assert() that calls event_errx on failure. */
195 #ifdef NDEBUG
196 #define EVUTIL_ASSERT(cond) _EVUTIL_NIL_CONDITION(cond)
197 #define EVUTIL_FAILURE_CHECK(cond) 0
198 #else
199 #define EVUTIL_ASSERT(cond)						\
200 	do {								\
201 		if (EVUTIL_UNLIKELY(!(cond))) {				\
202 			event_errx(_EVENT_ERR_ABORT,			\
203 			    "%s:%d: Assertion %s failed in %s",		\
204 			    __FILE__,__LINE__,#cond,__func__);		\
205 			/* In case a user-supplied handler tries to */	\
206 			/* return control to us, log and abort here. */	\
207 			(void)fprintf(stderr,				\
208 			    "%s:%d: Assertion %s failed in %s",		\
209 			    __FILE__,__LINE__,#cond,__func__);		\
210 			abort();					\
211 		}							\
212 	} while (/*CONSTCOND*/0)
213 #define EVUTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
214 #endif
215 
216 #ifndef _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE
217 /* Replacement for sockaddr storage that we can use internally on platforms
218  * that lack it.  It is not space-efficient, but neither is sockaddr_storage.
219  */
220 struct sockaddr_storage {
221 	union {
222 		struct sockaddr ss_sa;
223 		struct sockaddr_in ss_sin;
224 		struct sockaddr_in6 ss_sin6;
225 		char ss_padding[128];
226 	} ss_union;
227 };
228 #define ss_family ss_union.ss_sa.sa_family
229 #endif
230 
231 /* Internal addrinfo error code.  This one is returned from only from
232  * evutil_getaddrinfo_common, when we are sure that we'll have to hit a DNS
233  * server. */
234 #define EVUTIL_EAI_NEED_RESOLVE      -90002
235 
236 struct evdns_base;
237 struct evdns_getaddrinfo_request;
238 typedef struct evdns_getaddrinfo_request* (*evdns_getaddrinfo_fn)(
239     struct evdns_base *base,
240     const char *nodename, const char *servname,
241     const struct evutil_addrinfo *hints_in,
242     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
243 
244 void evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn);
245 
246 struct evutil_addrinfo *evutil_new_addrinfo(struct sockaddr *sa,
247     ev_socklen_t socklen, const struct evutil_addrinfo *hints);
248 struct evutil_addrinfo *evutil_addrinfo_append(struct evutil_addrinfo *first,
249     struct evutil_addrinfo *append);
250 void evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints);
251 int evutil_getaddrinfo_common(const char *nodename, const char *servname,
252     struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum);
253 
254 int evutil_getaddrinfo_async(struct evdns_base *dns_base,
255     const char *nodename, const char *servname,
256     const struct evutil_addrinfo *hints_in,
257     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
258 
259 /** Return true iff sa is a looback address. (That is, it is 127.0.0.1/8, or
260  * ::1). */
261 int evutil_sockaddr_is_loopback(const struct sockaddr *sa);
262 
263 
264 /**
265     Formats a sockaddr sa into a string buffer of size outlen stored in out.
266     Returns a pointer to out.  Always writes something into out, so it's safe
267     to use the output of this function without checking it for NULL.
268  */
269 const char *evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen);
270 
271 long evutil_tv_to_msec(const struct timeval *tv);
272 
273 int evutil_hex_char_to_int(char c);
274 
275 #ifdef WIN32
276 HANDLE evutil_load_windows_system_library(const TCHAR *library_name);
277 #endif
278 
279 #ifndef EV_SIZE_FMT
280 #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
281 #define EV_U64_FMT "%I64u"
282 #define EV_I64_FMT "%I64d"
283 #define EV_I64_ARG(x) ((__int64)(x))
284 #define EV_U64_ARG(x) ((unsigned __int64)(x))
285 #else
286 #define EV_U64_FMT "%llu"
287 #define EV_I64_FMT "%lld"
288 #define EV_I64_ARG(x) ((long long)(x))
289 #define EV_U64_ARG(x) ((unsigned long long)(x))
290 #endif
291 #endif
292 
293 #ifdef _WIN32
294 #define EV_SOCK_FMT EV_I64_FMT
295 #define EV_SOCK_ARG(x) EV_I64_ARG((x))
296 #else
297 #define EV_SOCK_FMT "%d"
298 #define EV_SOCK_ARG(x) (x)
299 #endif
300 
301 #if defined(__STDC__) && defined(__STDC_VERSION__)
302 #if (__STDC_VERSION__ >= 199901L)
303 #define EV_SIZE_FMT "%zu"
304 #define EV_SSIZE_FMT "%zd"
305 #define EV_SIZE_ARG(x) (x)
306 #define EV_SSIZE_ARG(x) (x)
307 #endif
308 #endif
309 
310 #ifndef EV_SIZE_FMT
311 #if (_EVENT_SIZEOF_SIZE_T <= _EVENT_SIZEOF_LONG)
312 #define EV_SIZE_FMT "%lu"
313 #define EV_SSIZE_FMT "%ld"
314 #define EV_SIZE_ARG(x) ((unsigned long)(x))
315 #define EV_SSIZE_ARG(x) ((long)(x))
316 #else
317 #define EV_SIZE_FMT EV_U64_FMT
318 #define EV_SSIZE_FMT EV_I64_FMT
319 #define EV_SIZE_ARG(x) EV_U64_ARG(x)
320 #define EV_SSIZE_ARG(x) EV_I64_ARG(x)
321 #endif
322 #endif
323 
324 void evutil_memclear_(void *mem, size_t len);
325 
326 #ifdef __cplusplus
327 }
328 #endif
329 
330 #endif
331