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