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