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