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