2 * Copyright (c) 2007-2010 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 _EVENT2_UTIL_H_
27 #define _EVENT2_UTIL_H_
29 /** @file event2/util.h
31 Common convenience functions for cross-platform portability and
32 related socket manipulations.
40 #include <event2/event-config.h>
41 #ifdef _EVENT_HAVE_SYS_TIME_H
44 #ifdef _EVENT_HAVE_STDINT_H
46 #elif defined(_EVENT_HAVE_INTTYPES_H)
49 #ifdef _EVENT_HAVE_SYS_TYPES_H
50 #include <sys/types.h>
52 #ifdef _EVENT_HAVE_STDDEF_H
59 #ifdef _EVENT_HAVE_NETDB_H
60 #if !defined(_GNU_SOURCE)
69 #include <sys/socket.h>
72 /* Integer type definitions for types that are supposed to be defined in the
73 * C99-specified stdint.h. Shamefully, some platforms do not include
74 * stdint.h, so we need to replace it. (If you are on a platform like this,
75 * your C headers are now over 10 years out of date. You should bug them to
76 * do something about this.)
79 * ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t -- unsigned integer
80 * types of exactly 64, 32, 16, and 8 bits respectively.
81 * ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t -- signed integer
82 * types of exactly 64, 32, 16, and 8 bits respectively.
83 * ev_uintptr_t, ev_intptr_t -- unsigned/signed integers large enough
84 * to hold a pointer without loss of bits.
86 #ifdef _EVENT_HAVE_UINT64_T
87 #define ev_uint64_t uint64_t
88 #define ev_int64_t int64_t
90 #define ev_uint64_t unsigned __int64
91 #define ev_int64_t signed __int64
92 #elif _EVENT_SIZEOF_LONG_LONG == 8
93 #define ev_uint64_t unsigned long long
94 #define ev_int64_t long long
95 #elif _EVENT_SIZEOF_LONG == 8
96 #define ev_uint64_t unsigned long
97 #define ev_int64_t long
99 #error "No way to define ev_uint64_t"
102 #ifdef _EVENT_HAVE_UINT32_T
103 #define ev_uint32_t uint32_t
104 #define ev_int32_t int32_t
106 #define ev_uint32_t unsigned int
107 #define ev_int32_t signed int
108 #elif _EVENT_SIZEOF_LONG == 4
109 #define ev_uint32_t unsigned long
110 #define ev_int32_t signed long
111 #elif _EVENT_SIZEOF_INT == 4
112 #define ev_uint32_t unsigned int
113 #define ev_int32_t signed int
115 #error "No way to define ev_uint32_t"
118 #ifdef _EVENT_HAVE_UINT16_T
119 #define ev_uint16_t uint16_t
120 #define ev_int16_t int16_t
122 #define ev_uint16_t unsigned short
123 #define ev_int16_t signed short
124 #elif _EVENT_SIZEOF_INT == 2
125 #define ev_uint16_t unsigned int
126 #define ev_int16_t signed int
127 #elif _EVENT_SIZEOF_SHORT == 2
128 #define ev_uint16_t unsigned short
129 #define ev_int16_t signed short
131 #error "No way to define ev_uint16_t"
134 #ifdef _EVENT_HAVE_UINT8_T
135 #define ev_uint8_t uint8_t
136 #define ev_int8_t int8_t
138 #define ev_uint8_t unsigned char
139 #define ev_int8_t signed char
142 /* Some openbsd autoconf versions get the name of this macro wrong. */
143 #if defined(_EVENT_SIZEOF_VOID__) && !defined(_EVENT_SIZEOF_VOID_P)
144 #define _EVENT_SIZEOF_VOID_P _EVENT_SIZEOF_VOID__
147 #ifdef _EVENT_HAVE_UINTPTR_T
148 #define ev_uintptr_t uintptr_t
149 #define ev_intptr_t intptr_t
150 #elif _EVENT_SIZEOF_VOID_P <= 4
151 #define ev_uintptr_t ev_uint32_t
152 #define ev_intptr_t ev_int32_t
153 #elif _EVENT_SIZEOF_VOID_P <= 8
154 #define ev_uintptr_t ev_uint64_t
155 #define ev_intptr_t ev_int64_t
157 #error "No way to define ev_uintptr_t"
160 #ifdef _EVENT_ssize_t
161 #define ev_ssize_t _EVENT_ssize_t
163 #define ev_ssize_t ssize_t
167 #define ev_off_t ev_int64_t
169 #define ev_off_t off_t
172 /* Limits for integer types.
174 We're making two assumptions here:
175 - The compiler does constant folding properly.
176 - The platform does signed arithmetic in two's complement.
179 #define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
180 #define EV_INT64_MAX ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
181 #define EV_INT64_MIN ((-EV_INT64_MAX) - 1)
182 #define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
183 #define EV_INT32_MAX ((ev_int32_t) 0x7fffffffL)
184 #define EV_INT32_MIN ((-EV_INT32_MAX) - 1)
185 #define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
186 #define EV_INT16_MAX ((ev_int16_t) 0x7fffL)
187 #define EV_INT16_MIN ((-EV_INT16_MAX) - 1)
188 #define EV_UINT8_MAX 255
189 #define EV_INT8_MAX 127
190 #define EV_INT8_MIN ((-EV_INT8_MAX) - 1)
192 #if _EVENT_SIZEOF_SIZE_T == 8
193 #define EV_SIZE_MAX EV_UINT64_MAX
194 #define EV_SSIZE_MAX EV_INT64_MAX
195 #elif _EVENT_SIZEOF_SIZE_T == 4
196 #define EV_SIZE_MAX EV_UINT32_MAX
197 #define EV_SSIZE_MAX EV_INT32_MAX
199 #error "No way to define SIZE_MAX"
202 #define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
205 #define ev_socklen_t int
206 #elif defined(_EVENT_socklen_t)
207 #define ev_socklen_t _EVENT_socklen_t
209 #define ev_socklen_t socklen_t
212 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
213 #if !defined(_EVENT_HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
214 && !defined(ss_family)
215 #define ss_family __ss_family
220 /** A type wide enough to hold the output of "socket()" or "accept()". On
221 * Windows, this is an intptr_t; elsewhere, it is an int. */
222 #define evutil_socket_t intptr_t
224 #define evutil_socket_t int
227 /** Create two new sockets that are connected to each other. On Unix, this
228 simply calls socketpair(). On Windows, it uses the loopback network
229 interface on 127.0.0.1, and only AF_INET,SOCK_STREAM are supported.
231 (This may fail on some Windows hosts where firewall software has cleverly
232 decided to keep 127.0.0.1 from talking to itself.)
234 Parameters and return values are as for socketpair()
236 int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
237 /** Do platform-specific operations as needed to make a socket nonblocking.
239 @param sock The socket to make nonblocking
240 @return 0 on success, -1 on failure
242 int evutil_make_socket_nonblocking(evutil_socket_t sock);
244 /** Do platform-specific operations on a listener socket to make sure that
245 another program will be able to bind this address right after we've
248 @param sock The socket to make reusable
249 @return 0 on success, -1 on failure
251 int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
253 /** Do platform-specific operations as needed to close a socket upon a
254 successful execution of one of the exec*() functions.
256 @param sock The socket to be closed
257 @return 0 on success, -1 on failure
259 int evutil_make_socket_closeonexec(evutil_socket_t sock);
261 /** Do the platform-specific call needed to close a socket returned from
262 socket() or accept().
264 @param sock The socket to be closed
265 @return 0 on success, -1 on failure
267 int evutil_closesocket(evutil_socket_t sock);
268 #define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
270 /* Winsock handles socket errors differently from the rest of the world.
271 * Elsewhere, a socket error is like any other error and is stored in errno.
272 * But winsock functions require you to retrieve the error with a special
273 * function, and don't let you use strerror for the error codes. And handling
274 * EWOULDBLOCK is ... different. */
277 /** Return the most recent socket error. Not idempotent on all platforms. */
278 #define EVUTIL_SOCKET_ERROR() WSAGetLastError()
279 /** Replace the most recent socket error with errcode */
280 #define EVUTIL_SET_SOCKET_ERROR(errcode) \
281 do { WSASetLastError(errcode); } while (0)
282 /** Return the most recent socket error to occur on sock. */
283 int evutil_socket_geterror(evutil_socket_t sock);
284 /** Convert a socket error to a string. */
285 const char *evutil_socket_error_to_string(int errcode);
287 #define EVUTIL_SOCKET_ERROR() (errno)
288 #define EVUTIL_SET_SOCKET_ERROR(errcode) \
289 do { errno = (errcode); } while (0)
290 #define evutil_socket_geterror(sock) (errno)
291 #define evutil_socket_error_to_string(errcode) (strerror(errcode))
295 * Manipulation macros for struct timeval. We define replacements
296 * for timeradd, timersub, timerclear, timercmp, and timerisset.
298 #ifdef _EVENT_HAVE_TIMERADD
299 #define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
300 #define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
302 #define evutil_timeradd(tvp, uvp, vvp) \
304 (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \
305 (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \
306 if ((vvp)->tv_usec >= 1000000) { \
308 (vvp)->tv_usec -= 1000000; \
311 #define evutil_timersub(tvp, uvp, vvp) \
313 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
314 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
315 if ((vvp)->tv_usec < 0) { \
317 (vvp)->tv_usec += 1000000; \
320 #endif /* !_EVENT_HAVE_HAVE_TIMERADD */
322 #ifdef _EVENT_HAVE_TIMERCLEAR
323 #define evutil_timerclear(tvp) timerclear(tvp)
325 #define evutil_timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0
328 /** Return true iff the tvp is related to uvp according to the relational
329 * operator cmp. Recognized values for cmp are ==, <=, <, >=, and >. */
330 #define evutil_timercmp(tvp, uvp, cmp) \
331 (((tvp)->tv_sec == (uvp)->tv_sec) ? \
332 ((tvp)->tv_usec cmp (uvp)->tv_usec) : \
333 ((tvp)->tv_sec cmp (uvp)->tv_sec))
335 #ifdef _EVENT_HAVE_TIMERISSET
336 #define evutil_timerisset(tvp) timerisset(tvp)
338 #define evutil_timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
341 /* Replacement for offsetof on platforms that don't define it. */
343 #define evutil_offsetof(type, field) offsetof(type, field)
345 #define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
348 /* big-int related functions */
349 /** Parse a 64-bit value from a string. Arguments are as for strtol. */
350 ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
352 /* Replacement for gettimeofday on platforms that lack it. */
353 #ifdef _EVENT_HAVE_GETTIMEOFDAY
354 #define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
357 int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
360 /** Replacement for snprintf to get consistent behavior on platforms for
361 which the return value of snprintf does not conform to C99.
363 int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
365 __attribute__((format(printf, 3, 4)))
368 int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap);
370 /** Replacement for inet_ntop for platforms which lack it. */
371 const char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
372 /** Replacement for inet_pton for platforms which lack it. */
373 int evutil_inet_pton(int af, const char *src, void *dst);
376 /** Parse an IPv4 or IPv6 address, with optional port, from a string.
378 Recognized formats are:
385 If no port is specified, the port in the output is set to 0.
387 @param str The string to parse.
388 @param out A struct sockaddr to hold the result. This should probably be
389 a struct sockaddr_storage.
390 @param outlen A pointer to the number of bytes that that 'out' can safely
391 hold. Set to the number of bytes used in 'out' on success.
392 @return -1 if the address is not well-formed, if the port is out of range,
393 or if out is not large enough to hold the result. Otherwise returns
396 int evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
398 /** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
399 * preceeds sa2, or greater than 0 if sa1 follows sa2. If include_port is
400 * true, consider the port as well as the address. Only implemented for
401 * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
402 * the same between Libevent versions. */
403 int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
406 /** As strcasecmp, but always compares the characters in locale-independent
407 ASCII. That's useful if you're handling data in ASCII-based protocols.
409 int evutil_ascii_strcasecmp(const char *str1, const char *str2);
410 /** As strncasecmp, but always compares the characters in locale-independent
411 ASCII. That's useful if you're handling data in ASCII-based protocols.
413 int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
415 /* Here we define evutil_addrinfo to the native addrinfo type, or redefinte it
416 * if this system has no getaddrinfo(). */
417 #ifdef _EVENT_HAVE_STRUCT_ADDRINFO
418 #define evutil_addrinfo addrinfo
420 struct evutil_addrinfo {
421 int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
422 int ai_family; /* PF_xxx */
423 int ai_socktype; /* SOCK_xxx */
424 int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
425 size_t ai_addrlen; /* length of ai_addr */
426 char *ai_canonname; /* canonical name for nodename */
427 struct sockaddr *ai_addr; /* binary address */
428 struct evutil_addrinfo *ai_next; /* next structure in linked list */
431 #ifdef EAI_ADDRFAMILY
432 #define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
434 #define EVUTIL_EAI_ADDRFAMILY -901
437 #define EVUTIL_EAI_AGAIN EAI_AGAIN
439 #define EVUTIL_EAI_AGAIN -902
442 #define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
444 #define EVUTIL_EAI_BADFLAGS -903
447 #define EVUTIL_EAI_FAIL EAI_FAIL
449 #define EVUTIL_EAI_FAIL -904
452 #define EVUTIL_EAI_FAMILY EAI_FAMILY
454 #define EVUTIL_EAI_FAMILY -905
457 #define EVUTIL_EAI_MEMORY EAI_MEMORY
459 #define EVUTIL_EAI_MEMORY -906
461 /* This test is a bit complicated, since some MS SDKs decide to
462 * remove NODATA or redefine it to be the same as NONAME, in a
463 * fun interpretation of RFC 2553 and RFC 3493. */
464 #if defined(EAI_NODATA) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
465 #define EVUTIL_EAI_NODATA EAI_NODATA
467 #define EVUTIL_EAI_NODATA -907
470 #define EVUTIL_EAI_NONAME EAI_NONAME
472 #define EVUTIL_EAI_NONAME -908
475 #define EVUTIL_EAI_SERVICE EAI_SERVICE
477 #define EVUTIL_EAI_SERVICE -909
480 #define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
482 #define EVUTIL_EAI_SOCKTYPE -910
485 #define EVUTIL_EAI_SYSTEM EAI_SYSTEM
487 #define EVUTIL_EAI_SYSTEM -911
490 #define EVUTIL_EAI_CANCEL -90001
493 #define EVUTIL_AI_PASSIVE AI_PASSIVE
495 #define EVUTIL_AI_PASSIVE 0x1000
498 #define EVUTIL_AI_CANONNAME AI_CANONNAME
500 #define EVUTIL_AI_CANONNAME 0x2000
502 #ifdef AI_NUMERICHOST
503 #define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
505 #define EVUTIL_AI_NUMERICHOST 0x4000
507 #ifdef AI_NUMERICSERV
508 #define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
510 #define EVUTIL_AI_NUMERICSERV 0x8000
513 #define EVUTIL_AI_V4MAPPED AI_V4MAPPED
515 #define EVUTIL_AI_V4MAPPED 0x10000
518 #define EVUTIL_AI_ALL AI_ALL
520 #define EVUTIL_AI_ALL 0x20000
523 #define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
525 #define EVUTIL_AI_ADDRCONFIG 0x40000
528 struct evutil_addrinfo;
529 /* This function clones getaddrinfo for systems that don't have it. For full
530 * details, see RFC 3493, section 6.1.
533 * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
534 * gethostbyname, with their attendant issues.
535 * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
537 * For a nonblocking variant, see evdns_getaddrinfo.
539 int evutil_getaddrinfo(const char *nodename, const char *servname,
540 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
542 /* Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
543 void evutil_freeaddrinfo(struct evutil_addrinfo *ai);
545 const char *evutil_gai_strerror(int err);
547 /* Generate n bytes of secure pseudorandom data, and store them in buf.
549 * By default, Libevent uses an ARC4-based random number generator, seeded
550 * using the platform's entropy source (/dev/urandom on Unix-like systems;
551 * CryptGenRandom on Windows).
553 void evutil_secure_rng_get_bytes(void *buf, size_t n);
556 * Seed the secure random number generator if needed, and return 0 on
557 * success or -1 on failure.
559 * It is okay to call this function more than once; it will still return
560 * 0 if the RNG has been successfully seeded and -1 if it can't be
563 * Ordinarily you don't need to call this function from your own code;
564 * Libevent will seed the RNG itself the first time it needs good random
565 * numbers. You only need to call it if (a) you want to double-check
566 * that one of the seeding methods did succeed, or (b) you plan to drop
567 * the capability to seed (by chrooting, or dropping capabilities, or
568 * whatever), and you want to make sure that seeding happens before your
569 * program loses the ability to do it.
571 int evutil_secure_rng_init(void);
573 /** Seed the random number generator with extra random bytes.
575 You should almost never need to call this function; it should be
576 sufficient to invoke evutil_secure_rng_init(), or let Libevent take
577 care of calling evutil_secure_rng_init() on its own.
579 If you call this function as a _replacement_ for the regular
580 entropy sources, then you need to be sure that your input
581 contains a fairly large amount of strong entropy. Doing so is
582 notoriously hard: most people who try get it wrong. Watch out!
584 @param dat a buffer full of a strong source of random numbers
585 @param datlen the number of bytes to read from datlen
587 void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
593 #endif /* _EVUTIL_H_ */