xref: /netbsd-src/external/bsd/libevent/dist/include/event2/util.h (revision 7e68cdd7306a8b6c32d6a32c16ba01e5a2ddc083)
1 /*	$NetBSD: util.h,v 1.5 2021/04/07 03:36:48 christos 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 EVENT2_UTIL_H_INCLUDED_
29 #define EVENT2_UTIL_H_INCLUDED_
30 
31 /** @file event2/util.h
32 
33   Common convenience functions for cross-platform portability and
34   related socket manipulations.
35 
36  */
37 #include <event2/visibility.h>
38 
39 #ifdef __cplusplus
40 extern "C" {
41 #endif
42 
43 #include <event2/event-config.h>
44 #ifdef EVENT__HAVE_SYS_TIME_H
45 #include <sys/time.h>
46 #endif
47 #ifdef EVENT__HAVE_STDINT_H
48 #include <stdint.h>
49 #elif defined(EVENT__HAVE_INTTYPES_H)
50 #include <inttypes.h>
51 #endif
52 #ifdef EVENT__HAVE_SYS_TYPES_H
53 #include <sys/types.h>
54 #endif
55 #ifdef EVENT__HAVE_STDDEF_H
56 #include <stddef.h>
57 #endif
58 #ifdef _MSC_VER
59 #include <BaseTsd.h>
60 #endif
61 #include <stdarg.h>
62 #ifdef EVENT__HAVE_NETDB_H
63 #include <netdb.h>
64 #endif
65 
66 #ifdef _WIN32
67 #include <winsock2.h>
68 #ifdef EVENT__HAVE_GETADDRINFO
69 /* for EAI_* definitions. */
70 #include <ws2tcpip.h>
71 #endif
72 #else
73 #ifdef EVENT__HAVE_ERRNO_H
74 #include <errno.h>
75 #endif
76 #include <sys/socket.h>
77 #endif
78 
79 #include <time.h>
80 
81 /* Some openbsd autoconf versions get the name of this macro wrong. */
82 #if defined(EVENT__SIZEOF_VOID__) && !defined(EVENT__SIZEOF_VOID_P)
83 #define EVENT__SIZEOF_VOID_P EVENT__SIZEOF_VOID__
84 #endif
85 
86 /**
87  * @name Standard integer types.
88  *
89  * Integer type definitions for types that are supposed to be defined in the
90  * C99-specified stdint.h.  Shamefully, some platforms do not include
91  * stdint.h, so we need to replace it.  (If you are on a platform like this,
92  * your C headers are now over 10 years out of date.  You should bug them to
93  * do something about this.)
94  *
95  * We define:
96  *
97  * <dl>
98  *   <dt>ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t</dt>
99  *      <dd>unsigned integer types of exactly 64, 32, 16, and 8 bits
100  *          respectively.</dd>
101  *    <dt>ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t</dt>
102  *      <dd>signed integer types of exactly 64, 32, 16, and 8 bits
103  *          respectively.</dd>
104  *    <dt>ev_uintptr_t, ev_intptr_t</dt>
105  *      <dd>unsigned/signed integers large enough
106  *      to hold a pointer without loss of bits.</dd>
107  *    <dt>ev_ssize_t</dt>
108  *      <dd>A signed type of the same size as size_t</dd>
109  *    <dt>ev_off_t</dt>
110  *      <dd>A signed type typically used to represent offsets within a
111  *      (potentially large) file</dd>
112  *
113  * @{
114  */
115 #ifdef EVENT__HAVE_UINT64_T
116 #define ev_uint64_t uint64_t
117 #define ev_int64_t int64_t
118 #elif defined(_WIN32)
119 #define ev_uint64_t unsigned __int64
120 #define ev_int64_t signed __int64
121 #elif EVENT__SIZEOF_LONG_LONG == 8
122 #define ev_uint64_t unsigned long long
123 #define ev_int64_t long long
124 #elif EVENT__SIZEOF_LONG == 8
125 #define ev_uint64_t unsigned long
126 #define ev_int64_t long
127 #elif defined(EVENT_IN_DOXYGEN_)
128 #define ev_uint64_t ...
129 #define ev_int64_t ...
130 #else
131 #error "No way to define ev_uint64_t"
132 #endif
133 
134 #ifdef EVENT__HAVE_UINT32_T
135 #define ev_uint32_t uint32_t
136 #define ev_int32_t int32_t
137 #elif defined(_WIN32)
138 #define ev_uint32_t unsigned int
139 #define ev_int32_t signed int
140 #elif EVENT__SIZEOF_LONG == 4
141 #define ev_uint32_t unsigned long
142 #define ev_int32_t signed long
143 #elif EVENT__SIZEOF_INT == 4
144 #define ev_uint32_t unsigned int
145 #define ev_int32_t signed int
146 #elif defined(EVENT_IN_DOXYGEN_)
147 #define ev_uint32_t ...
148 #define ev_int32_t ...
149 #else
150 #error "No way to define ev_uint32_t"
151 #endif
152 
153 #ifdef EVENT__HAVE_UINT16_T
154 #define ev_uint16_t uint16_t
155 #define ev_int16_t  int16_t
156 #elif defined(_WIN32)
157 #define ev_uint16_t unsigned short
158 #define ev_int16_t  signed short
159 #elif EVENT__SIZEOF_INT == 2
160 #define ev_uint16_t unsigned int
161 #define ev_int16_t  signed int
162 #elif EVENT__SIZEOF_SHORT == 2
163 #define ev_uint16_t unsigned short
164 #define ev_int16_t  signed short
165 #elif defined(EVENT_IN_DOXYGEN_)
166 #define ev_uint16_t ...
167 #define ev_int16_t ...
168 #else
169 #error "No way to define ev_uint16_t"
170 #endif
171 
172 #ifdef EVENT__HAVE_UINT8_T
173 #define ev_uint8_t uint8_t
174 #define ev_int8_t int8_t
175 #elif defined(EVENT_IN_DOXYGEN_)
176 #define ev_uint8_t ...
177 #define ev_int8_t ...
178 #else
179 #define ev_uint8_t unsigned char
180 #define ev_int8_t signed char
181 #endif
182 
183 #ifdef EVENT__HAVE_UINTPTR_T
184 #define ev_uintptr_t uintptr_t
185 #define ev_intptr_t intptr_t
186 #elif EVENT__SIZEOF_VOID_P <= 4
187 #define ev_uintptr_t ev_uint32_t
188 #define ev_intptr_t ev_int32_t
189 #elif EVENT__SIZEOF_VOID_P <= 8
190 #define ev_uintptr_t ev_uint64_t
191 #define ev_intptr_t ev_int64_t
192 #elif defined(EVENT_IN_DOXYGEN_)
193 #define ev_uintptr_t ...
194 #define ev_intptr_t ...
195 #else
196 #error "No way to define ev_uintptr_t"
197 #endif
198 
199 #ifdef EVENT__ssize_t
200 #define ev_ssize_t EVENT__ssize_t
201 #else
202 #define ev_ssize_t ssize_t
203 #endif
204 
205 /* Note that we define ev_off_t based on the compile-time size of off_t that
206  * we used to build Libevent, and not based on the current size of off_t.
207  * (For example, we don't define ev_off_t to off_t.).  We do this because
208  * some systems let you build your software with different off_t sizes
209  * at runtime, and so putting in any dependency on off_t would risk API
210  * mismatch.
211  */
212 #ifdef _WIN32
213 #define ev_off_t ev_int64_t
214 #elif EVENT__SIZEOF_OFF_T == 8
215 #define ev_off_t ev_int64_t
216 #elif EVENT__SIZEOF_OFF_T == 4
217 #define ev_off_t ev_int32_t
218 #elif defined(EVENT_IN_DOXYGEN_)
219 #define ev_off_t ...
220 #else
221 #define ev_off_t off_t
222 #endif
223 /**@}*/
224 
225 /* Limits for integer types.
226 
227    We're making two assumptions here:
228      - The compiler does constant folding properly.
229      - The platform does signed arithmetic in two's complement.
230 */
231 
232 /**
233    @name Limits for integer types
234 
235    These macros hold the largest or smallest values possible for the
236    ev_[u]int*_t types.
237 
238    @{
239 */
240 #ifndef EVENT__HAVE_STDINT_H
241 #define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
242 #define EV_INT64_MAX  ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
243 #define EV_INT64_MIN  ((-EV_INT64_MAX) - 1)
244 #define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
245 #define EV_INT32_MAX  ((ev_int32_t) 0x7fffffffL)
246 #define EV_INT32_MIN  ((-EV_INT32_MAX) - 1)
247 #define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
248 #define EV_INT16_MAX  ((ev_int16_t) 0x7fffL)
249 #define EV_INT16_MIN  ((-EV_INT16_MAX) - 1)
250 #define EV_UINT8_MAX  255
251 #define EV_INT8_MAX   127
252 #define EV_INT8_MIN   ((-EV_INT8_MAX) - 1)
253 #else
254 #define EV_UINT64_MAX UINT64_MAX
255 #define EV_INT64_MAX  INT64_MAX
256 #define EV_INT64_MIN  INT64_MIN
257 #define EV_UINT32_MAX UINT32_MAX
258 #define EV_INT32_MAX  INT32_MAX
259 #define EV_INT32_MIN  INT32_MIN
260 #define EV_UINT16_MAX UINT16_MAX
261 #define EV_INT16_MIN  INT16_MIN
262 #define EV_INT16_MAX  INT16_MAX
263 #define EV_UINT8_MAX  UINT8_MAX
264 #define EV_INT8_MAX   INT8_MAX
265 #define EV_INT8_MIN   INT8_MIN
266 /** @} */
267 #endif
268 
269 
270 /**
271    @name Limits for SIZE_T and SSIZE_T
272 
273    @{
274 */
275 #if EVENT__SIZEOF_SIZE_T == 8
276 #define EV_SIZE_MAX EV_UINT64_MAX
277 #define EV_SSIZE_MAX EV_INT64_MAX
278 #elif EVENT__SIZEOF_SIZE_T == 4
279 #define EV_SIZE_MAX EV_UINT32_MAX
280 #define EV_SSIZE_MAX EV_INT32_MAX
281 #elif defined(EVENT_IN_DOXYGEN_)
282 #define EV_SIZE_MAX ...
283 #define EV_SSIZE_MAX ...
284 #else
285 #error "No way to define SIZE_MAX"
286 #endif
287 
288 #define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
289 /**@}*/
290 
291 #ifdef _WIN32
292 #define ev_socklen_t int
293 #elif defined(EVENT__socklen_t)
294 #define ev_socklen_t EVENT__socklen_t
295 #else
296 #define ev_socklen_t socklen_t
297 #endif
298 
299 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
300 #if !defined(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
301  && !defined(ss_family)
302 #define ss_family __ss_family
303 #endif
304 #endif
305 
306 /**
307  * A type wide enough to hold the output of "socket()" or "accept()".  On
308  * Windows, this is an intptr_t; elsewhere, it is an int. */
309 #ifdef _WIN32
310 #define evutil_socket_t intptr_t
311 #else
312 #define evutil_socket_t int
313 #endif
314 
315 /**
316  * Structure to hold information about a monotonic timer
317  *
318  * Use this with evutil_configure_monotonic_time() and
319  * evutil_gettime_monotonic().
320  *
321  * This is an opaque structure; you can allocate one using
322  * evutil_monotonic_timer_new().
323  *
324  * @see evutil_monotonic_timer_new(), evutil_monotonic_timer_free(),
325  * evutil_configure_monotonic_time(), evutil_gettime_monotonic()
326  */
327 struct evutil_monotonic_timer
328 #ifdef EVENT_IN_DOXYGEN_
329 {/*Empty body so that doxygen will generate documentation here.*/}
330 #endif
331 ;
332 
333 #define EV_MONOT_PRECISE  1
334 #define EV_MONOT_FALLBACK 2
335 
336 /** Format a date string using RFC 1123 format (used in HTTP).
337  * If `tm` is NULL, current system's time will be used.
338  * The number of characters written will be returned.
339  * One should check if the return value is smaller than `datelen` to check if
340  * the result is truncated or not.
341  */
342 EVENT2_EXPORT_SYMBOL int
343 evutil_date_rfc1123(char *date, const size_t datelen, const struct tm *tm);
344 
345 /** Allocate a new struct evutil_monotonic_timer for use with the
346  * evutil_configure_monotonic_time() and evutil_gettime_monotonic()
347  * functions.  You must configure the timer with
348  * evutil_configure_monotonic_time() before using it.
349  */
350 EVENT2_EXPORT_SYMBOL
351 struct evutil_monotonic_timer * evutil_monotonic_timer_new(void);
352 
353 /** Free a struct evutil_monotonic_timer that was allocated using
354  * evutil_monotonic_timer_new().
355  */
356 EVENT2_EXPORT_SYMBOL
357 void evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer);
358 
359 /** Set up a struct evutil_monotonic_timer; flags can include
360  * EV_MONOT_PRECISE and EV_MONOT_FALLBACK.
361  */
362 EVENT2_EXPORT_SYMBOL
363 int evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
364                                     int flags);
365 
366 /** Query the current monotonic time from a struct evutil_monotonic_timer
367  * previously configured with evutil_configure_monotonic_time().  Monotonic
368  * time is guaranteed never to run in reverse, but is not necessarily epoch-
369  * based, or relative to any other definite point.  Use it to make reliable
370  * measurements of elapsed time between events even when the system time
371  * may be changed.
372  *
373  * It is not safe to use this funtion on the same timer from multiple
374  * threads.
375  */
376 EVENT2_EXPORT_SYMBOL
377 int evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
378                              struct timeval *tp);
379 
380 /** Create two new sockets that are connected to each other.
381 
382     On Unix, this simply calls socketpair().  On Windows, it uses the
383     loopback network interface on 127.0.0.1, and only
384     AF_INET,SOCK_STREAM are supported.
385 
386     (This may fail on some Windows hosts where firewall software has cleverly
387     decided to keep 127.0.0.1 from talking to itself.)
388 
389     Parameters and return values are as for socketpair()
390 */
391 EVENT2_EXPORT_SYMBOL
392 int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
393 /** Do platform-specific operations as needed to make a socket nonblocking.
394 
395     @param sock The socket to make nonblocking
396     @return 0 on success, -1 on failure
397  */
398 EVENT2_EXPORT_SYMBOL
399 int evutil_make_socket_nonblocking(evutil_socket_t sock);
400 
401 /** Do platform-specific operations to make a listener socket reusable.
402 
403     Specifically, we want to make sure that another program will be able
404     to bind this address right after we've closed the listener.
405 
406     This differs from Windows's interpretation of "reusable", which
407     allows multiple listeners to bind the same address at the same time.
408 
409     @param sock The socket to make reusable
410     @return 0 on success, -1 on failure
411  */
412 EVENT2_EXPORT_SYMBOL
413 int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
414 
415 /** Do platform-specific operations to make a listener port reusable.
416 
417     Specifically, we want to make sure that multiple programs which also
418     set the same socket option will be able to bind, listen at the same time.
419 
420     This is a feature available only to Linux 3.9+
421 
422     @param sock The socket to make reusable
423     @return 0 on success, -1 on failure
424  */
425 EVENT2_EXPORT_SYMBOL
426 int evutil_make_listen_socket_reuseable_port(evutil_socket_t sock);
427 
428 /** Set ipv6 only bind socket option to make listener work only in ipv6 sockets.
429 
430     According to RFC3493 and most Linux distributions, default value for the
431     sockets is to work in IPv4-mapped mode. In IPv4-mapped mode, it is not possible
432     to bind same port from different IPv4 and IPv6 handlers.
433 
434     @param sock The socket to make in ipv6only working mode
435     @return 0 on success, -1 on failure
436  */
437 EVENT2_EXPORT_SYMBOL
438 int evutil_make_listen_socket_ipv6only(evutil_socket_t sock);
439 
440 /** Do platform-specific operations as needed to close a socket upon a
441     successful execution of one of the exec*() functions.
442 
443     @param sock The socket to be closed
444     @return 0 on success, -1 on failure
445  */
446 EVENT2_EXPORT_SYMBOL
447 int evutil_make_socket_closeonexec(evutil_socket_t sock);
448 
449 /** Do the platform-specific call needed to close a socket returned from
450     socket() or accept().
451 
452     @param sock The socket to be closed
453     @return 0 on success (whether the operation is supported or not),
454             -1 on failure
455  */
456 EVENT2_EXPORT_SYMBOL
457 int evutil_closesocket(evutil_socket_t sock);
458 #define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
459 
460 /** Do platform-specific operations, if possible, to make a tcp listener
461  *  socket defer accept()s until there is data to read.
462  *
463  *  Not all platforms support this.  You don't want to do this for every
464  *  listener socket: only the ones that implement a protocol where the
465  *  client transmits before the server needs to respond.
466  *
467  *  @param sock The listening socket to to make deferred
468  *  @return 0 on success (whether the operation is supported or not),
469  *       -1 on failure
470 */
471 EVENT2_EXPORT_SYMBOL
472 int evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock);
473 
474 #ifdef _WIN32
475 /** Return the most recent socket error.  Not idempotent on all platforms. */
476 #define EVUTIL_SOCKET_ERROR() WSAGetLastError()
477 /** Replace the most recent socket error with errcode */
478 #define EVUTIL_SET_SOCKET_ERROR(errcode)		\
479 	do { WSASetLastError(errcode); } while (0)
480 /** Return the most recent socket error to occur on sock. */
481 EVENT2_EXPORT_SYMBOL
482 int evutil_socket_geterror(evutil_socket_t sock);
483 /** Convert a socket error to a string. */
484 EVENT2_EXPORT_SYMBOL
485 const char *evutil_socket_error_to_string(int errcode);
486 #define EVUTIL_INVALID_SOCKET INVALID_SOCKET
487 #elif defined(EVENT_IN_DOXYGEN_)
488 /**
489    @name Socket error functions
490 
491    These functions are needed for making programs compatible between
492    Windows and Unix-like platforms.
493 
494    You see, Winsock handles socket errors differently from the rest of
495    the world.  Elsewhere, a socket error is like any other error and is
496    stored in errno.  But winsock functions require you to retrieve the
497    error with a special function, and don't let you use strerror for
498    the error codes.  And handling EWOULDBLOCK is ... different.
499 
500    @{
501 */
502 /** Return the most recent socket error.  Not idempotent on all platforms. */
503 #define EVUTIL_SOCKET_ERROR() ...
504 /** Replace the most recent socket error with errcode */
505 #define EVUTIL_SET_SOCKET_ERROR(errcode) ...
506 /** Return the most recent socket error to occur on sock. */
507 #define evutil_socket_geterror(sock) ...
508 /** Convert a socket error to a string. */
509 #define evutil_socket_error_to_string(errcode) ...
510 #define EVUTIL_INVALID_SOCKET -1
511 /**@}*/
512 #else /** !EVENT_IN_DOXYGEN_ && !_WIN32 */
513 #define EVUTIL_SOCKET_ERROR() (errno)
514 #define EVUTIL_SET_SOCKET_ERROR(errcode)		\
515 		do { errno = (errcode); } while (0)
516 #define evutil_socket_geterror(sock) (errno)
517 #define evutil_socket_error_to_string(errcode) (strerror(errcode))
518 #define EVUTIL_INVALID_SOCKET -1
519 #endif /** !_WIN32 */
520 
521 
522 /**
523  * @name Manipulation macros for struct timeval.
524  *
525  * We define replacements
526  * for timeradd, timersub, timerclear, timercmp, and timerisset.
527  *
528  * @{
529  */
530 #ifdef EVENT__HAVE_TIMERADD
531 #define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
532 #define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
533 #else
534 #define evutil_timeradd(tvp, uvp, vvp)					\
535 	do {								\
536 		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
537 		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
538 		if ((vvp)->tv_usec >= 1000000) {			\
539 			(vvp)->tv_sec++;				\
540 			(vvp)->tv_usec -= 1000000;			\
541 		}							\
542 	} while (0)
543 #define	evutil_timersub(tvp, uvp, vvp)					\
544 	do {								\
545 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
546 		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
547 		if ((vvp)->tv_usec < 0) {				\
548 			(vvp)->tv_sec--;				\
549 			(vvp)->tv_usec += 1000000;			\
550 		}							\
551 	} while (0)
552 #endif /* !EVENT__HAVE_TIMERADD */
553 
554 #ifdef EVENT__HAVE_TIMERCLEAR
555 #define evutil_timerclear(tvp) timerclear(tvp)
556 #else
557 #define	evutil_timerclear(tvp)	(tvp)->tv_sec = (tvp)->tv_usec = 0
558 #endif
559 /**@}*/
560 
561 /** Return true iff the tvp is related to uvp according to the relational
562  * operator cmp.  Recognized values for cmp are ==, <=, <, >=, and >. */
563 #define	evutil_timercmp(tvp, uvp, cmp)					\
564 	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
565 	 ((tvp)->tv_usec cmp (uvp)->tv_usec) :				\
566 	 ((tvp)->tv_sec cmp (uvp)->tv_sec))
567 
568 #ifdef EVENT__HAVE_TIMERISSET
569 #define evutil_timerisset(tvp) timerisset(tvp)
570 #else
571 #define	evutil_timerisset(tvp)	((tvp)->tv_sec || (tvp)->tv_usec)
572 #endif
573 
574 /** Replacement for offsetof on platforms that don't define it. */
575 #ifdef offsetof
576 #define evutil_offsetof(type, field) offsetof(type, field)
577 #else
578 #define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
579 #endif
580 
581 /* big-int related functions */
582 /** Parse a 64-bit value from a string.  Arguments are as for strtol. */
583 EVENT2_EXPORT_SYMBOL
584 ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
585 
586 /** Replacement for gettimeofday on platforms that lack it. */
587 #ifdef EVENT__HAVE_GETTIMEOFDAY
588 #define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
589 #else
590 struct timezone;
591 EVENT2_EXPORT_SYMBOL
592 int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
593 #endif
594 
595 /** Replacement for snprintf to get consistent behavior on platforms for
596     which the return value of snprintf does not conform to C99.
597  */
598 EVENT2_EXPORT_SYMBOL
599 int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
600 #ifdef __GNUC__
601 	__attribute__((format(printf, 3, 4)))
602 #endif
603 ;
604 /** Replacement for vsnprintf to get consistent behavior on platforms for
605     which the return value of snprintf does not conform to C99.
606  */
607 EVENT2_EXPORT_SYMBOL
608 int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
609 #ifdef __GNUC__
610 	__attribute__((format(printf, 3, 0)))
611 #endif
612 ;
613 
614 /** Replacement for inet_ntop for platforms which lack it. */
615 EVENT2_EXPORT_SYMBOL
616 const char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
617 /** Variation of inet_pton that also parses IPv6 scopes. Public for
618     unit tests. No reason to call this directly.
619  */
620 EVENT2_EXPORT_SYMBOL
621 int evutil_inet_pton_scope(int af, const char *src, void *dst,
622 	unsigned *indexp);
623 /** Replacement for inet_pton for platforms which lack it. */
624 EVENT2_EXPORT_SYMBOL
625 int evutil_inet_pton(int af, const char *src, void *dst);
626 struct sockaddr;
627 
628 /** Parse an IPv4 or IPv6 address, with optional port, from a string.
629 
630     Recognized formats are:
631     - [IPv6Address]:port
632     - [IPv6Address]
633     - IPv6Address
634     - IPv4Address:port
635     - IPv4Address
636 
637     If no port is specified, the port in the output is set to 0.
638 
639     @param str The string to parse.
640     @param out A struct sockaddr to hold the result.  This should probably be
641        a struct sockaddr_storage.
642     @param outlen A pointer to the number of bytes that that 'out' can safely
643        hold.  Set to the number of bytes used in 'out' on success.
644     @return -1 if the address is not well-formed, if the port is out of range,
645        or if out is not large enough to hold the result.  Otherwise returns
646        0 on success.
647 */
648 EVENT2_EXPORT_SYMBOL
649 int evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
650 
651 /** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
652  * preceeds sa2, or greater than 0 if sa1 follows sa2.  If include_port is
653  * true, consider the port as well as the address.  Only implemented for
654  * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
655  * the same between Libevent versions. */
656 EVENT2_EXPORT_SYMBOL
657 int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
658     int include_port);
659 
660 /** As strcasecmp, but always compares the characters in locale-independent
661     ASCII.  That's useful if you're handling data in ASCII-based protocols.
662  */
663 EVENT2_EXPORT_SYMBOL
664 int evutil_ascii_strcasecmp(const char *str1, const char *str2);
665 /** As strncasecmp, but always compares the characters in locale-independent
666     ASCII.  That's useful if you're handling data in ASCII-based protocols.
667  */
668 EVENT2_EXPORT_SYMBOL
669 int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
670 
671 /* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
672  * if this system has no getaddrinfo(). */
673 #ifdef EVENT__HAVE_STRUCT_ADDRINFO
674 #define evutil_addrinfo addrinfo
675 #else
676 /** A definition of struct addrinfo for systems that lack it.
677 
678     (This is just an alias for struct addrinfo if the system defines
679     struct addrinfo.)
680 */
681 struct evutil_addrinfo {
682 	int     ai_flags;     /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
683 	int     ai_family;    /* PF_xxx */
684 	int     ai_socktype;  /* SOCK_xxx */
685 	int     ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
686 	size_t  ai_addrlen;   /* length of ai_addr */
687 	char   *ai_canonname; /* canonical name for nodename */
688 	struct sockaddr  *ai_addr; /* binary address */
689 	struct evutil_addrinfo  *ai_next; /* next structure in linked list */
690 };
691 #endif
692 /** @name evutil_getaddrinfo() error codes
693 
694     These values are possible error codes for evutil_getaddrinfo() and
695     related functions.
696 
697     @{
698 */
699 #if defined(EAI_ADDRFAMILY) && defined(EVENT__HAVE_GETADDRINFO)
700 #define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
701 #else
702 #define EVUTIL_EAI_ADDRFAMILY -901
703 #endif
704 #if defined(EAI_AGAIN) && defined(EVENT__HAVE_GETADDRINFO)
705 #define EVUTIL_EAI_AGAIN EAI_AGAIN
706 #else
707 #define EVUTIL_EAI_AGAIN -902
708 #endif
709 #if defined(EAI_BADFLAGS) && defined(EVENT__HAVE_GETADDRINFO)
710 #define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
711 #else
712 #define EVUTIL_EAI_BADFLAGS -903
713 #endif
714 #if defined(EAI_FAIL) && defined(EVENT__HAVE_GETADDRINFO)
715 #define EVUTIL_EAI_FAIL EAI_FAIL
716 #else
717 #define EVUTIL_EAI_FAIL -904
718 #endif
719 #if defined(EAI_FAMILY) && defined(EVENT__HAVE_GETADDRINFO)
720 #define EVUTIL_EAI_FAMILY EAI_FAMILY
721 #else
722 #define EVUTIL_EAI_FAMILY -905
723 #endif
724 #if defined(EAI_MEMORY) && defined(EVENT__HAVE_GETADDRINFO)
725 #define EVUTIL_EAI_MEMORY EAI_MEMORY
726 #else
727 #define EVUTIL_EAI_MEMORY -906
728 #endif
729 /* This test is a bit complicated, since some MS SDKs decide to
730  * remove NODATA or redefine it to be the same as NONAME, in a
731  * fun interpretation of RFC 2553 and RFC 3493. */
732 #if defined(EAI_NODATA) && defined(EVENT__HAVE_GETADDRINFO) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
733 #define EVUTIL_EAI_NODATA EAI_NODATA
734 #else
735 #define EVUTIL_EAI_NODATA -907
736 #endif
737 #if defined(EAI_NONAME) && defined(EVENT__HAVE_GETADDRINFO)
738 #define EVUTIL_EAI_NONAME EAI_NONAME
739 #else
740 #define EVUTIL_EAI_NONAME -908
741 #endif
742 #if defined(EAI_SERVICE) && defined(EVENT__HAVE_GETADDRINFO)
743 #define EVUTIL_EAI_SERVICE EAI_SERVICE
744 #else
745 #define EVUTIL_EAI_SERVICE -909
746 #endif
747 #if defined(EAI_SOCKTYPE) && defined(EVENT__HAVE_GETADDRINFO)
748 #define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
749 #else
750 #define EVUTIL_EAI_SOCKTYPE -910
751 #endif
752 #if defined(EAI_SYSTEM) && defined(EVENT__HAVE_GETADDRINFO)
753 #define EVUTIL_EAI_SYSTEM EAI_SYSTEM
754 #else
755 #define EVUTIL_EAI_SYSTEM -911
756 #endif
757 
758 #define EVUTIL_EAI_CANCEL -90001
759 
760 #if defined(AI_PASSIVE) && defined(EVENT__HAVE_GETADDRINFO)
761 #define EVUTIL_AI_PASSIVE AI_PASSIVE
762 #else
763 #define EVUTIL_AI_PASSIVE 0x1000
764 #endif
765 #if defined(AI_CANONNAME) && defined(EVENT__HAVE_GETADDRINFO)
766 #define EVUTIL_AI_CANONNAME AI_CANONNAME
767 #else
768 #define EVUTIL_AI_CANONNAME 0x2000
769 #endif
770 #if defined(AI_NUMERICHOST) && defined(EVENT__HAVE_GETADDRINFO)
771 #define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
772 #else
773 #define EVUTIL_AI_NUMERICHOST 0x4000
774 #endif
775 #if defined(AI_NUMERICSERV) && defined(EVENT__HAVE_GETADDRINFO)
776 #define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
777 #else
778 #define EVUTIL_AI_NUMERICSERV 0x8000
779 #endif
780 #if defined(AI_V4MAPPED) && defined(EVENT__HAVE_GETADDRINFO)
781 #define EVUTIL_AI_V4MAPPED AI_V4MAPPED
782 #else
783 #define EVUTIL_AI_V4MAPPED 0x10000
784 #endif
785 #if defined(AI_ALL) && defined(EVENT__HAVE_GETADDRINFO)
786 #define EVUTIL_AI_ALL AI_ALL
787 #else
788 #define EVUTIL_AI_ALL 0x20000
789 #endif
790 #if defined(AI_ADDRCONFIG) && defined(EVENT__HAVE_GETADDRINFO)
791 #define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
792 #else
793 #define EVUTIL_AI_ADDRCONFIG 0x40000
794 #endif
795 /**@}*/
796 
797 struct evutil_addrinfo;
798 /**
799  * This function clones getaddrinfo for systems that don't have it.  For full
800  * details, see RFC 3493, section 6.1.
801  *
802  * Limitations:
803  * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
804  *   gethostbyname, with their attendant issues.
805  * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
806  *
807  * For a nonblocking variant, see evdns_getaddrinfo.
808  */
809 EVENT2_EXPORT_SYMBOL
810 int evutil_getaddrinfo(const char *nodename, const char *servname,
811     const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
812 
813 /** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
814 EVENT2_EXPORT_SYMBOL
815 void evutil_freeaddrinfo(struct evutil_addrinfo *ai);
816 
817 EVENT2_EXPORT_SYMBOL
818 const char *evutil_gai_strerror(int err);
819 
820 /** Generate n bytes of secure pseudorandom data, and store them in buf.
821  *
822  * Current versions of Libevent use an ARC4-based random number generator,
823  * seeded using the platform's entropy source (/dev/urandom on Unix-like
824  * systems; CryptGenRandom on Windows).  This is not actually as secure as it
825  * should be: ARC4 is a pretty lousy cipher, and the current implementation
826  * provides only rudimentary prediction- and backtracking-resistance.  Don't
827  * use this for serious cryptographic applications.
828  */
829 EVENT2_EXPORT_SYMBOL
830 void evutil_secure_rng_get_bytes(void *buf, size_t n);
831 
832 /**
833  * Seed the secure random number generator if needed, and return 0 on
834  * success or -1 on failure.
835  *
836  * It is okay to call this function more than once; it will still return
837  * 0 if the RNG has been successfully seeded and -1 if it can't be
838  * seeded.
839  *
840  * Ordinarily you don't need to call this function from your own code;
841  * Libevent will seed the RNG itself the first time it needs good random
842  * numbers.  You only need to call it if (a) you want to double-check
843  * that one of the seeding methods did succeed, or (b) you plan to drop
844  * the capability to seed (by chrooting, or dropping capabilities, or
845  * whatever), and you want to make sure that seeding happens before your
846  * program loses the ability to do it.
847  */
848 EVENT2_EXPORT_SYMBOL
849 int evutil_secure_rng_init(void);
850 
851 /**
852  * Set a filename to use in place of /dev/urandom for seeding the secure
853  * PRNG. Return 0 on success, -1 on failure.
854  *
855  * Call this function BEFORE calling any other initialization or RNG
856  * functions.
857  *
858  * (This string will _NOT_ be copied internally. Do not free it while any
859  * user of the secure RNG might be running. Don't pass anything other than a
860  * real /dev/...random device file here, or you might lose security.)
861  *
862  * This API is unstable, and might change in a future libevent version.
863  */
864 EVENT2_EXPORT_SYMBOL
865 int evutil_secure_rng_set_urandom_device_file(char *fname);
866 
867 #if !defined(EVENT__HAVE_ARC4RANDOM) || defined(EVENT__HAVE_ARC4RANDOM_ADDRANDOM)
868 /** Seed the random number generator with extra random bytes.
869 
870     You should almost never need to call this function; it should be
871     sufficient to invoke evutil_secure_rng_init(), or let Libevent take
872     care of calling evutil_secure_rng_init() on its own.
873 
874     If you call this function as a _replacement_ for the regular
875     entropy sources, then you need to be sure that your input
876     contains a fairly large amount of strong entropy.  Doing so is
877     notoriously hard: most people who try get it wrong.  Watch out!
878 
879     @param dat a buffer full of a strong source of random numbers
880     @param datlen the number of bytes to read from datlen
881  */
882 EVENT2_EXPORT_SYMBOL
883 void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
884 #endif
885 
886 #ifdef __cplusplus
887 }
888 #endif
889 
890 #endif /* EVENT1_EVUTIL_H_INCLUDED_ */
891