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