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