1047f369cy/*
2047f369cy * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
3047f369cy *
4047f369cy * Redistribution and use in source and binary forms, with or without
5047f369cy * modification, are permitted provided that the following conditions
6047f369cy * are met:
7047f369cy * 1. Redistributions of source code must retain the above copyright
8047f369cy *    notice, this list of conditions and the following disclaimer.
9047f369cy * 2. Redistributions in binary form must reproduce the above copyright
10047f369cy *    notice, this list of conditions and the following disclaimer in the
11047f369cy *    documentation and/or other materials provided with the distribution.
12047f369cy * 3. The name of the author may not be used to endorse or promote products
13047f369cy *    derived from this software without specific prior written permission.
14047f369cy *
15047f369cy * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16047f369cy * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17047f369cy * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18047f369cy * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19047f369cy * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20047f369cy * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21047f369cy * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22047f369cy * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23047f369cy * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24047f369cy * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25047f369cy */
26047f369cy#ifndef EVENT2_UTIL_H_INCLUDED_
27047f369cy#define EVENT2_UTIL_H_INCLUDED_
28047f369cy
29047f369cy/** @file event2/util.h
30047f369cy
31047f369cy  Common convenience functions for cross-platform portability and
32047f369cy  related socket manipulations.
33047f369cy
34047f369cy */
35047f369cy#include <event2/visibility.h>
36047f369cy
37047f369cy#ifdef __cplusplus
38047f369cyextern "C" {
39047f369cy#endif
40047f369cy
41047f369cy#include <event2/event-config.h>
42047f369cy#ifdef EVENT__HAVE_SYS_TIME_H
43047f369cy#include <sys/time.h>
44047f369cy#endif
45047f369cy#ifdef EVENT__HAVE_STDINT_H
46047f369cy#include <stdint.h>
47047f369cy#elif defined(EVENT__HAVE_INTTYPES_H)
48047f369cy#include <inttypes.h>
49047f369cy#endif
50047f369cy#ifdef EVENT__HAVE_SYS_TYPES_H
51047f369cy#include <sys/types.h>
52047f369cy#endif
53047f369cy#ifdef EVENT__HAVE_STDDEF_H
54047f369cy#include <stddef.h>
55047f369cy#endif
56047f369cy#ifdef _MSC_VER
57047f369cy#include <BaseTsd.h>
58047f369cy#endif
59047f369cy#include <stdarg.h>
60047f369cy#ifdef EVENT__HAVE_NETDB_H
61047f369cy#if !defined(_GNU_SOURCE)
62047f369cy#define _GNU_SOURCE
63047f369cy#endif
64047f369cy#include <netdb.h>
65047f369cy#endif
66047f369cy
67047f369cy#ifdef _WIN32
68047f369cy#include <winsock2.h>
69047f369cy#ifdef EVENT__HAVE_GETADDRINFO
70047f369cy/* for EAI_* definitions. */
71047f369cy#include <ws2tcpip.h>
72047f369cy#endif
73047f369cy#else
74047f369cy#include <sys/socket.h>
75047f369cy#endif
76047f369cy
77047f369cy/* Some openbsd autoconf versions get the name of this macro wrong. */
78047f369cy#if defined(EVENT__SIZEOF_VOID__) && !defined(EVENT__SIZEOF_VOID_P)
79047f369cy#define EVENT__SIZEOF_VOID_P EVENT__SIZEOF_VOID__
80047f369cy#endif
81047f369cy
82047f369cy/**
83047f369cy * @name Standard integer types.
84047f369cy *
85047f369cy * Integer type definitions for types that are supposed to be defined in the
86047f369cy * C99-specified stdint.h.  Shamefully, some platforms do not include
87047f369cy * stdint.h, so we need to replace it.  (If you are on a platform like this,
88047f369cy * your C headers are now over 10 years out of date.  You should bug them to
89047f369cy * do something about this.)
90047f369cy *
91047f369cy * We define:
92047f369cy *
93047f369cy * <dl>
94047f369cy *   <dt>ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t</dt>
95047f369cy *      <dd>unsigned integer types of exactly 64, 32, 16, and 8 bits
96047f369cy *          respectively.</dd>
97047f369cy *    <dt>ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t</dt>
98047f369cy *      <dd>signed integer types of exactly 64, 32, 16, and 8 bits
99047f369cy *          respectively.</dd>
100047f369cy *    <dt>ev_uintptr_t, ev_intptr_t</dt>
101047f369cy *      <dd>unsigned/signed integers large enough
102047f369cy *      to hold a pointer without loss of bits.</dd>
103047f369cy *    <dt>ev_ssize_t</dt>
104047f369cy *      <dd>A signed type of the same size as size_t</dd>
105047f369cy *    <dt>ev_off_t</dt>
106047f369cy *      <dd>A signed type typically used to represent offsets within a
107047f369cy *      (potentially large) file</dd>
108047f369cy *
109047f369cy * @{
110047f369cy */
111047f369cy#ifdef EVENT__HAVE_UINT64_T
112047f369cy#define ev_uint64_t uint64_t
113047f369cy#define ev_int64_t int64_t
114047f369cy#elif defined(_WIN32)
115047f369cy#define ev_uint64_t unsigned __int64
116047f369cy#define ev_int64_t signed __int64
117047f369cy#elif EVENT__SIZEOF_LONG_LONG == 8
118047f369cy#define ev_uint64_t unsigned long long
119047f369cy#define ev_int64_t long long
120047f369cy#elif EVENT__SIZEOF_LONG == 8
121047f369cy#define ev_uint64_t unsigned long
122047f369cy#define ev_int64_t long
123047f369cy#elif defined(EVENT_IN_DOXYGEN_)
124047f369cy#define ev_uint64_t ...
125047f369cy#define ev_int64_t ...
126047f369cy#else
127047f369cy#error "No way to define ev_uint64_t"
128047f369cy#endif
129047f369cy
130047f369cy#ifdef EVENT__HAVE_UINT32_T
131047f369cy#define ev_uint32_t uint32_t
132047f369cy#define ev_int32_t int32_t
133047f369cy#elif defined(_WIN32)
134047f369cy#define ev_uint32_t unsigned int
135047f369cy#define ev_int32_t signed int
136047f369cy#elif EVENT__SIZEOF_LONG == 4
137047f369cy#define ev_uint32_t unsigned long
138047f369cy#define ev_int32_t signed long
139047f369cy#elif EVENT__SIZEOF_INT == 4
140047f369cy#define ev_uint32_t unsigned int
141047f369cy#define ev_int32_t signed int
142047f369cy#elif defined(EVENT_IN_DOXYGEN_)
143047f369cy#define ev_uint32_t ...
144047f369cy#define ev_int32_t ...
145047f369cy#else
146047f369cy#error "No way to define ev_uint32_t"
147047f369cy#endif
148047f369cy
149047f369cy#ifdef EVENT__HAVE_UINT16_T
150047f369cy#define ev_uint16_t uint16_t
151047f369cy#define ev_int16_t  int16_t
152047f369cy#elif defined(_WIN32)
153047f369cy#define ev_uint16_t unsigned short
154047f369cy#define ev_int16_t  signed short
155047f369cy#elif EVENT__SIZEOF_INT == 2
156047f369cy#define ev_uint16_t unsigned int
157047f369cy#define ev_int16_t  signed int
158047f369cy#elif EVENT__SIZEOF_SHORT == 2
159047f369cy#define ev_uint16_t unsigned short
160047f369cy#define ev_int16_t  signed short
161047f369cy#elif defined(EVENT_IN_DOXYGEN_)
162047f369cy#define ev_uint16_t ...
163047f369cy#define ev_int16_t ...
164047f369cy#else
165047f369cy#error "No way to define ev_uint16_t"
166047f369cy#endif
167047f369cy
168047f369cy#ifdef EVENT__HAVE_UINT8_T
169047f369cy#define ev_uint8_t uint8_t
170047f369cy#define ev_int8_t int8_t
171047f369cy#elif defined(EVENT_IN_DOXYGEN_)
172047f369cy#define ev_uint8_t ...
173047f369cy#define ev_int8_t ...
174047f369cy#else
175047f369cy#define ev_uint8_t unsigned char
176047f369cy#define ev_int8_t signed char
177047f369cy#endif
178047f369cy
179047f369cy#ifdef EVENT__HAVE_UINTPTR_T
180047f369cy#define ev_uintptr_t uintptr_t
181047f369cy#define ev_intptr_t intptr_t
182047f369cy#elif EVENT__SIZEOF_VOID_P <= 4
183047f369cy#define ev_uintptr_t ev_uint32_t
184047f369cy#define ev_intptr_t ev_int32_t
185047f369cy#elif EVENT__SIZEOF_VOID_P <= 8
186047f369cy#define ev_uintptr_t ev_uint64_t
187047f369cy#define ev_intptr_t ev_int64_t
188047f369cy#elif defined(EVENT_IN_DOXYGEN_)
189047f369cy#define ev_uintptr_t ...
190047f369cy#define ev_intptr_t ...
191047f369cy#else
192047f369cy#error "No way to define ev_uintptr_t"
193047f369cy#endif
194047f369cy
195047f369cy#ifdef EVENT__ssize_t
196047f369cy#define ev_ssize_t EVENT__ssize_t
197047f369cy#else
198047f369cy#define ev_ssize_t ssize_t
199047f369cy#endif
200047f369cy
201047f369cy/* Note that we define ev_off_t based on the compile-time size of off_t that
202047f369cy * we used to build Libevent, and not based on the current size of off_t.
203047f369cy * (For example, we don't define ev_off_t to off_t.).  We do this because
204047f369cy * some systems let you build your software with different off_t sizes
205047f369cy * at runtime, and so putting in any dependency on off_t would risk API
206047f369cy * mismatch.
207047f369cy */
208047f369cy#ifdef _WIN32
209047f369cy#define ev_off_t ev_int64_t
210047f369cy#elif EVENT__SIZEOF_OFF_T == 8
211047f369cy#define ev_off_t ev_int64_t
212047f369cy#elif EVENT__SIZEOF_OFF_T == 4
213047f369cy#define ev_off_t ev_int32_t
214047f369cy#elif defined(EVENT_IN_DOXYGEN_)
215047f369cy#define ev_off_t ...
216047f369cy#else
217047f369cy#define ev_off_t off_t
218047f369cy#endif
219047f369cy/**@}*/
220047f369cy
221047f369cy/* Limits for integer types.
222047f369cy
223047f369cy   We're making two assumptions here:
224047f369cy     - The compiler does constant folding properly.
225047f369cy     - The platform does signed arithmetic in two's complement.
226047f369cy*/
227047f369cy
228047f369cy/**
229047f369cy   @name Limits for integer types
230047f369cy
231047f369cy   These macros hold the largest or smallest values possible for the
232047f369cy   ev_[u]int*_t types.
233047f369cy
234047f369cy   @{
235047f369cy*/
236047f369cy#define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
237047f369cy#define EV_INT64_MAX  ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
238047f369cy#define EV_INT64_MIN  ((-EV_INT64_MAX) - 1)
239047f369cy#define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
240047f369cy#define EV_INT32_MAX  ((ev_int32_t) 0x7fffffffL)
241047f369cy#define EV_INT32_MIN  ((-EV_INT32_MAX) - 1)
242047f369cy#define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
243047f369cy#define EV_INT16_MAX  ((ev_int16_t) 0x7fffL)
244047f369cy#define EV_INT16_MIN  ((-EV_INT16_MAX) - 1)
245047f369cy#define EV_UINT8_MAX  255
246047f369cy#define EV_INT8_MAX   127
247047f369cy#define EV_INT8_MIN   ((-EV_INT8_MAX) - 1)
248047f369cy/** @} */
249047f369cy
250047f369cy/**
251047f369cy   @name Limits for SIZE_T and SSIZE_T
252047f369cy
253047f369cy   @{
254047f369cy*/
255047f369cy#if EVENT__SIZEOF_SIZE_T == 8
256047f369cy#define EV_SIZE_MAX EV_UINT64_MAX
257047f369cy#define EV_SSIZE_MAX EV_INT64_MAX
258047f369cy#elif EVENT__SIZEOF_SIZE_T == 4
259047f369cy#define EV_SIZE_MAX EV_UINT32_MAX
260047f369cy#define EV_SSIZE_MAX EV_INT32_MAX
261047f369cy#elif defined(EVENT_IN_DOXYGEN_)
262047f369cy#define EV_SIZE_MAX ...
263047f369cy#define EV_SSIZE_MAX ...
264047f369cy#else
265047f369cy#error "No way to define SIZE_MAX"
266047f369cy#endif
267047f369cy
268047f369cy#define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
269047f369cy/**@}*/
270047f369cy
271047f369cy#ifdef _WIN32
272047f369cy#define ev_socklen_t int
273047f369cy#elif defined(EVENT__socklen_t)
274047f369cy#define ev_socklen_t EVENT__socklen_t
275047f369cy#else
276047f369cy#define ev_socklen_t socklen_t
277047f369cy#endif
278047f369cy
279047f369cy#ifdef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
280047f369cy#if !defined(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
281047f369cy && !defined(ss_family)
282047f369cy#define ss_family __ss_family
283047f369cy#endif
284047f369cy#endif
285047f369cy
286047f369cy/**
287047f369cy * A type wide enough to hold the output of "socket()" or "accept()".  On
288047f369cy * Windows, this is an intptr_t; elsewhere, it is an int. */
289047f369cy#ifdef _WIN32
290047f369cy#define evutil_socket_t intptr_t
291047f369cy#else
292047f369cy#define evutil_socket_t int
293047f369cy#endif
294047f369cy
295f63afe2cy/**
296f63afe2cy * Structure to hold information about a monotonic timer
297f63afe2cy *
298f63afe2cy * Use this with evutil_configure_monotonic_time() and
299f63afe2cy * evutil_gettime_monotonic().
300f63afe2cy *
301f63afe2cy * This is an opaque structure; you can allocate one using
302f63afe2cy * evutil_monotonic_timer_new().
303f63afe2cy *
304f63afe2cy * @see evutil_monotonic_timer_new(), evutil_monotonic_timer_free(),
305f63afe2cy * evutil_configure_monotonic_time(), evutil_gettime_monotonic()
306f63afe2cy */
307f63afe2cystruct evutil_monotonic_timer
308f63afe2cy#ifdef EVENT_IN_DOXYGEN_
309f63afe2cy{/*Empty body so that doxygen will generate documentation here.*/}
310f63afe2cy#endif
311f63afe2cy;
312f63afe2cy
313f63afe2cy#define EV_MONOT_PRECISE  1
314f63afe2cy#define EV_MONOT_FALLBACK 2
315f63afe2cy
316f63afe2cy/** Allocate a new struct evutil_monotonic_timer for use with the
317f63afe2cy * evutil_configure_monotonic_time() and evutil_gettime_monotonic()
318f63afe2cy * functions.  You must configure the timer with
319f63afe2cy * evutil_configure_monotonic_time() before using it.
320f63afe2cy */
321f63afe2cyEVENT2_EXPORT_SYMBOL
322f63afe2cystruct evutil_monotonic_timer * evutil_monotonic_timer_new(void);
323f63afe2cy
324f63afe2cy/** Free a struct evutil_monotonic_timer that was allocated using
325f63afe2cy * evutil_monotonic_timer_new().
326f63afe2cy */
327f63afe2cyEVENT2_EXPORT_SYMBOL
328f63afe2cyvoid evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer);
329f63afe2cy
330f63afe2cy/** Set up a struct evutil_monotonic_timer; flags can include
331f63afe2cy * EV_MONOT_PRECISE and EV_MONOT_FALLBACK.
332f63afe2cy */
333f63afe2cyEVENT2_EXPORT_SYMBOL
334f63afe2cyint evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
335f63afe2cy                                    int flags);
336f63afe2cy
337f63afe2cy/** Query the current monotonic time from a struct evutil_monotonic_timer
338f63afe2cy * previously configured with evutil_configure_monotonic_time().  Monotonic
339f63afe2cy * time is guaranteed never to run in reverse, but is not necessarily epoch-
340f63afe2cy * based, or relative to any other definite point.  Use it to make reliable
341f63afe2cy * measurements of elapsed time between events even when the system time
342f63afe2cy * may be changed.
343f63afe2cy *
344f63afe2cy * It is not safe to use this funtion on the same timer from multiple
345f63afe2cy * threads.
346f63afe2cy */
347f63afe2cyEVENT2_EXPORT_SYMBOL
348f63afe2cyint evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
349f63afe2cy                             struct timeval *tp);
350f63afe2cy
351047f369cy/** Create two new sockets that are connected to each other.
352047f369cy
353047f369cy    On Unix, this simply calls socketpair().  On Windows, it uses the
354047f369cy    loopback network interface on 127.0.0.1, and only
355047f369cy    AF_INET,SOCK_STREAM are supported.
356047f369cy
357047f369cy    (This may fail on some Windows hosts where firewall software has cleverly
358047f369cy    decided to keep 127.0.0.1 from talking to itself.)
359047f369cy
360047f369cy    Parameters and return values are as for socketpair()
361047f369cy*/
362047f369cyEVENT2_EXPORT_SYMBOL
363047f369cyint evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
364047f369cy/** Do platform-specific operations as needed to make a socket nonblocking.
365047f369cy
366047f369cy    @param sock The socket to make nonblocking
367047f369cy    @return 0 on success, -1 on failure
368047f369cy */
369047f369cyEVENT2_EXPORT_SYMBOL
370047f369cyint evutil_make_socket_nonblocking(evutil_socket_t sock);
371047f369cy
372047f369cy/** Do platform-specific operations to make a listener socket reusable.
373047f369cy
374047f369cy    Specifically, we want to make sure that another program will be able
375047f369cy    to bind this address right after we've closed the listener.
376047f369cy
377047f369cy    This differs from Windows's interpretation of "reusable", which
378047f369cy    allows multiple listeners to bind the same address at the same time.
379047f369cy
380047f369cy    @param sock The socket to make reusable
381047f369cy    @return 0 on success, -1 on failure
382047f369cy */
383047f369cyEVENT2_EXPORT_SYMBOL
384047f369cyint evutil_make_listen_socket_reuseable(evutil_socket_t sock);
385047f369cy
386f63afe2cy/** Do platform-specific operations to make a listener port reusable.
387f63afe2cy
388f63afe2cy    Specifically, we want to make sure that multiple programs which also
389f63afe2cy    set the same socket option will be able to bind, listen at the same time.
390f63afe2cy
391f63afe2cy    This is a feature available only to Linux 3.9+
392f63afe2cy
393f63afe2cy    @param sock The socket to make reusable
394f63afe2cy    @return 0 on success, -1 on failure
395f63afe2cy */
396f63afe2cyEVENT2_EXPORT_SYMBOL
397f63afe2cyint evutil_make_listen_socket_reuseable_port(evutil_socket_t sock);
398f63afe2cy
399047f369cy/** Do platform-specific operations as needed to close a socket upon a
400047f369cy    successful execution of one of the exec*() functions.
401047f369cy
402047f369cy    @param sock The socket to be closed
403047f369cy    @return 0 on success, -1 on failure
404047f369cy */
405047f369cyEVENT2_EXPORT_SYMBOL
406047f369cyint evutil_make_socket_closeonexec(evutil_socket_t sock);
407047f369cy
408047f369cy/** Do the platform-specific call needed to close a socket returned from
409047f369cy    socket() or accept().
410047f369cy
411047f369cy    @param sock The socket to be closed
412047f369cy    @return 0 on success, -1 on failure
413047f369cy */
414047f369cyEVENT2_EXPORT_SYMBOL
415047f369cyint evutil_closesocket(evutil_socket_t sock);
416047f369cy#define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
417047f369cy
418047f369cy/** Do platform-specific operations, if possible, to make a tcp listener
419047f369cy *  socket defer accept()s until there is data to read.
420047f369cy *
421047f369cy *  Not all platforms support this.  You don't want to do this for every
422047f369cy *  listener socket: only the ones that implement a protocol where the
423047f369cy *  client transmits before the server needs to respond.
424047f369cy *
425047f369cy *  @param sock The listening socket to to make deferred
426047f369cy *  @return 0 on success (whether the operation is supported or not),
427047f369cy *       -1 on failure
428047f369cy*/
429047f369cyEVENT2_EXPORT_SYMBOL
430047f369cyint evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock);
431047f369cy
432047f369cy#ifdef _WIN32
433047f369cy/** Return the most recent socket error.  Not idempotent on all platforms. */
434047f369cy#define EVUTIL_SOCKET_ERROR() WSAGetLastError()
435047f369cy/** Replace the most recent socket error with errcode */
436047f369cy#define EVUTIL_SET_SOCKET_ERROR(errcode)		\
437047f369cy	do { WSASetLastError(errcode); } while (0)
438047f369cy/** Return the most recent socket error to occur on sock. */
439047f369cyEVENT2_EXPORT_SYMBOL
440047f369cyint evutil_socket_geterror(evutil_socket_t sock);
441047f369cy/** Convert a socket error to a string. */
442047f369cyEVENT2_EXPORT_SYMBOL
443047f369cyconst char *evutil_socket_error_to_string(int errcode);
444047f369cy#elif defined(EVENT_IN_DOXYGEN_)
445047f369cy/**
446047f369cy   @name Socket error functions
447047f369cy
448047f369cy   These functions are needed for making programs compatible between
449047f369cy   Windows and Unix-like platforms.
450047f369cy
451047f369cy   You see, Winsock handles socket errors differently from the rest of
452047f369cy   the world.  Elsewhere, a socket error is like any other error and is
453047f369cy   stored in errno.  But winsock functions require you to retrieve the
454047f369cy   error with a special function, and don't let you use strerror for
455047f369cy   the error codes.  And handling EWOULDBLOCK is ... different.
456047f369cy
457047f369cy   @{
458047f369cy*/
459047f369cy/** Return the most recent socket error.  Not idempotent on all platforms. */
460047f369cy#define EVUTIL_SOCKET_ERROR() ...
461047f369cy/** Replace the most recent socket error with errcode */
462047f369cy#define EVUTIL_SET_SOCKET_ERROR(errcode) ...
463047f369cy/** Return the most recent socket error to occur on sock. */
464047f369cy#define evutil_socket_geterror(sock) ...
465047f369cy/** Convert a socket error to a string. */
466047f369cy#define evutil_socket_error_to_string(errcode) ...
467047f369cy/**@}*/
468047f369cy#else
469047f369cy#define EVUTIL_SOCKET_ERROR() (errno)
470047f369cy#define EVUTIL_SET_SOCKET_ERROR(errcode)		\
471047f369cy		do { errno = (errcode); } while (0)
472047f369cy#define evutil_socket_geterror(sock) (errno)
473047f369cy#define evutil_socket_error_to_string(errcode) (strerror(errcode))
474047f369cy#endif
475047f369cy
476047f369cy
477047f369cy/**
478047f369cy * @name Manipulation macros for struct timeval.
479047f369cy *
480047f369cy * We define replacements
481047f369cy * for timeradd, timersub, timerclear, timercmp, and timerisset.
482047f369cy *
483047f369cy * @{
484047f369cy */
485047f369cy#ifdef EVENT__HAVE_TIMERADD
486047f369cy#define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
487047f369cy#define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
488047f369cy#else
489047f369cy#define evutil_timeradd(tvp, uvp, vvp)					\
490047f369cy	do {								\
491047f369cy		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
492047f369cy		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
493047f369cy		if ((vvp)->tv_usec >= 1000000) {			\
494047f369cy			(vvp)->tv_sec++;				\
495047f369cy			(vvp)->tv_usec -= 1000000;			\
496047f369cy		}							\
497047f369cy	} while (0)
498047f369cy#define	evutil_timersub(tvp, uvp, vvp)					\
499047f369cy	do {								\
500047f369cy		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
501047f369cy		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
502047f369cy		if ((vvp)->tv_usec < 0) {				\
503047f369cy			(vvp)->tv_sec--;				\
504047f369cy			(vvp)->tv_usec += 1000000;			\
505047f369cy		}							\
506047f369cy	} while (0)
507047f369cy#endif /* !EVENT__HAVE_TIMERADD */
508047f369cy
509047f369cy#ifdef EVENT__HAVE_TIMERCLEAR
510047f369cy#define evutil_timerclear(tvp) timerclear(tvp)
511047f369cy#else
512047f369cy#define	evutil_timerclear(tvp)	(tvp)->tv_sec = (tvp)->tv_usec = 0
513047f369cy#endif
514047f369cy/**@}*/
515047f369cy
516047f369cy/** Return true iff the tvp is related to uvp according to the relational
517047f369cy * operator cmp.  Recognized values for cmp are ==, <=, <, >=, and >. */
518047f369cy#define	evutil_timercmp(tvp, uvp, cmp)					\
519047f369cy	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
520047f369cy	 ((tvp)->tv_usec cmp (uvp)->tv_usec) :				\
521047f369cy	 ((tvp)->tv_sec cmp (uvp)->tv_sec))
522047f369cy
523047f369cy#ifdef EVENT__HAVE_TIMERISSET
524047f369cy#define evutil_timerisset(tvp) timerisset(tvp)
525047f369cy#else
526047f369cy#define	evutil_timerisset(tvp)	((tvp)->tv_sec || (tvp)->tv_usec)
527047f369cy#endif
528047f369cy
529047f369cy/** Replacement for offsetof on platforms that don't define it. */
530047f369cy#ifdef offsetof
531047f369cy#define evutil_offsetof(type, field) offsetof(type, field)
532047f369cy#else
533047f369cy#define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
534047f369cy#endif
535047f369cy
536047f369cy/* big-int related functions */
537047f369cy/** Parse a 64-bit value from a string.  Arguments are as for strtol. */
538047f369cyEVENT2_EXPORT_SYMBOL
539047f369cyev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
540047f369cy
541047f369cy/** Replacement for gettimeofday on platforms that lack it. */
542047f369cy#ifdef EVENT__HAVE_GETTIMEOFDAY
543047f369cy#define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
544047f369cy#else
545047f369cystruct timezone;
546047f369cyEVENT2_EXPORT_SYMBOL
547047f369cyint evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
548047f369cy#endif
549047f369cy
550047f369cy/** Replacement for snprintf to get consistent behavior on platforms for
551047f369cy    which the return value of snprintf does not conform to C99.
552047f369cy */
553047f369cyEVENT2_EXPORT_SYMBOL
554047f369cyint evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
555047f369cy#ifdef __GNUC__
556047f369cy	__attribute__((format(printf, 3, 4)))
557047f369cy#endif
558047f369cy;
559047f369cy/** Replacement for vsnprintf to get consistent behavior on platforms for
560047f369cy    which the return value of snprintf does not conform to C99.
561047f369cy */
562047f369cyEVENT2_EXPORT_SYMBOL
563047f369cyint evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
564047f369cy#ifdef __GNUC__
565047f369cy	__attribute__((format(printf, 3, 0)))
566047f369cy#endif
567047f369cy;
568047f369cy
569047f369cy/** Replacement for inet_ntop for platforms which lack it. */
570047f369cyEVENT2_EXPORT_SYMBOL
571047f369cyconst char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
572047f369cy/** Replacement for inet_pton for platforms which lack it. */
573047f369cyEVENT2_EXPORT_SYMBOL
574047f369cyint evutil_inet_pton(int af, const char *src, void *dst);
575047f369cystruct sockaddr;
576047f369cy
577047f369cy/** Parse an IPv4 or IPv6 address, with optional port, from a string.
578047f369cy
579047f369cy    Recognized formats are:
580047f369cy    - [IPv6Address]:port
581047f369cy    - [IPv6Address]
582047f369cy    - IPv6Address
583047f369cy    - IPv4Address:port
584047f369cy    - IPv4Address
585047f369cy
586047f369cy    If no port is specified, the port in the output is set to 0.
587047f369cy
588047f369cy    @param str The string to parse.
589047f369cy    @param out A struct sockaddr to hold the result.  This should probably be
590047f369cy       a struct sockaddr_storage.
591047f369cy    @param outlen A pointer to the number of bytes that that 'out' can safely
592047f369cy       hold.  Set to the number of bytes used in 'out' on success.
593047f369cy    @return -1 if the address is not well-formed, if the port is out of range,
594047f369cy       or if out is not large enough to hold the result.  Otherwise returns
595047f369cy       0 on success.
596047f369cy*/
597047f369cyEVENT2_EXPORT_SYMBOL
598047f369cyint evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
599047f369cy
600047f369cy/** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
601047f369cy * preceeds sa2, or greater than 0 if sa1 follows sa2.  If include_port is
602047f369cy * true, consider the port as well as the address.  Only implemented for
603047f369cy * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
604047f369cy * the same between Libevent versions. */
605047f369cyEVENT2_EXPORT_SYMBOL
606047f369cyint evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
607047f369cy    int include_port);
608047f369cy
609047f369cy/** As strcasecmp, but always compares the characters in locale-independent
610047f369cy    ASCII.  That's useful if you're handling data in ASCII-based protocols.
611047f369cy */
612047f369cyEVENT2_EXPORT_SYMBOL
613047f369cyint evutil_ascii_strcasecmp(const char *str1, const char *str2);
614047f369cy/** As strncasecmp, but always compares the characters in locale-independent
615047f369cy    ASCII.  That's useful if you're handling data in ASCII-based protocols.
616047f369cy */
617047f369cyEVENT2_EXPORT_SYMBOL
618047f369cyint evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
619047f369cy
620047f369cy/* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
621047f369cy * if this system has no getaddrinfo(). */
622047f369cy#ifdef EVENT__HAVE_STRUCT_ADDRINFO
623047f369cy#define evutil_addrinfo addrinfo
624047f369cy#else
625047f369cy/** A definition of struct addrinfo for systems that lack it.
626047f369cy
627047f369cy    (This is just an alias for struct addrinfo if the system defines
628047f369cy    struct addrinfo.)
629047f369cy*/
630047f369cystruct evutil_addrinfo {
631047f369cy	int     ai_flags;     /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
632047f369cy	int     ai_family;    /* PF_xxx */
633047f369cy	int     ai_socktype;  /* SOCK_xxx */
634047f369cy	int     ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
635047f369cy	size_t  ai_addrlen;   /* length of ai_addr */
636047f369cy	char   *ai_canonname; /* canonical name for nodename */
637047f369cy	struct sockaddr  *ai_addr; /* binary address */
638047f369cy	struct evutil_addrinfo  *ai_next; /* next structure in linked list */
639047f369cy};
640047f369cy#endif
641047f369cy/** @name evutil_getaddrinfo() error codes
642047f369cy
643047f369cy    These values are possible error codes for evutil_getaddrinfo() and
644047f369cy    related functions.
645047f369cy
646047f369cy    @{
647047f369cy*/
648047f369cy#if defined(EAI_ADDRFAMILY) && defined(EVENT__HAVE_GETADDRINFO)
649047f369cy#define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
650047f369cy#else
651047f369cy#define EVUTIL_EAI_ADDRFAMILY -901
652047f369cy#endif
653047f369cy#if defined(EAI_AGAIN) && defined(EVENT__HAVE_GETADDRINFO)
654047f369cy#define EVUTIL_EAI_AGAIN EAI_AGAIN
655047f369cy#else
656047f369cy#define EVUTIL_EAI_AGAIN -902
657047f369cy#endif
658047f369cy#if defined(EAI_BADFLAGS) && defined(EVENT__HAVE_GETADDRINFO)
659047f369cy#define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
660047f369cy#else
661047f369cy#define EVUTIL_EAI_BADFLAGS -903
662047f369cy#endif
663047f369cy#if defined(EAI_FAIL) && defined(EVENT__HAVE_GETADDRINFO)
664047f369cy#define EVUTIL_EAI_FAIL EAI_FAIL
665047f369cy#else
666047f369cy#define EVUTIL_EAI_FAIL -904
667047f369cy#endif
668047f369cy#if defined(EAI_FAMILY) && defined(EVENT__HAVE_GETADDRINFO)
669047f369cy#define EVUTIL_EAI_FAMILY EAI_FAMILY
670047f369cy#else
671047f369cy#define EVUTIL_EAI_FAMILY -905
672047f369cy#endif
673047f369cy#if defined(EAI_MEMORY) && defined(EVENT__HAVE_GETADDRINFO)
674047f369cy#define EVUTIL_EAI_MEMORY EAI_MEMORY
675047f369cy#else
676047f369cy#define EVUTIL_EAI_MEMORY -906
677047f369cy#endif
678047f369cy/* This test is a bit complicated, since some MS SDKs decide to
679047f369cy * remove NODATA or redefine it to be the same as NONAME, in a
680047f369cy * fun interpretation of RFC 2553 and RFC 3493. */
681047f369cy#if defined(EAI_NODATA) && defined(EVENT__HAVE_GETADDRINFO) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
682047f369cy#define EVUTIL_EAI_NODATA EAI_NODATA
683047f369cy#else
684047f369cy#define EVUTIL_EAI_NODATA -907
685047f369cy#endif
686047f369cy#if defined(EAI_NONAME) && defined(EVENT__HAVE_GETADDRINFO)
687047f369cy#define EVUTIL_EAI_NONAME EAI_NONAME
688047f369cy#else
689047f369cy#define EVUTIL_EAI_NONAME -908
690047f369cy#endif
691047f369cy#if defined(EAI_SERVICE) && defined(EVENT__HAVE_GETADDRINFO)
692047f369cy#define EVUTIL_EAI_SERVICE EAI_SERVICE
693047f369cy#else
694047f369cy#define EVUTIL_EAI_SERVICE -909
695047f369cy#endif
696047f369cy#if defined(EAI_SOCKTYPE) && defined(EVENT__HAVE_GETADDRINFO)
697047f369cy#define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
698047f369cy#else
699047f369cy#define EVUTIL_EAI_SOCKTYPE -910
700047f369cy#endif
701047f369cy#if defined(EAI_SYSTEM) && defined(EVENT__HAVE_GETADDRINFO)
702047f369cy#define EVUTIL_EAI_SYSTEM EAI_SYSTEM
703047f369cy#else
704047f369cy#define EVUTIL_EAI_SYSTEM -911
705047f369cy#endif
706047f369cy
707047f369cy#define EVUTIL_EAI_CANCEL -90001
708047f369cy
709047f369cy#if defined(AI_PASSIVE) && defined(EVENT__HAVE_GETADDRINFO)
710047f369cy#define EVUTIL_AI_PASSIVE AI_PASSIVE
711047f369cy#else
712047f369cy#define EVUTIL_AI_PASSIVE 0x1000
713047f369cy#endif
714047f369cy#if defined(AI_CANONNAME) && defined(EVENT__HAVE_GETADDRINFO)
715047f369cy#define EVUTIL_AI_CANONNAME AI_CANONNAME
716047f369cy#else
717047f369cy#define EVUTIL_AI_CANONNAME 0x2000
718047f369cy#endif
719047f369cy#if defined(AI_NUMERICHOST) && defined(EVENT__HAVE_GETADDRINFO)
720047f369cy#define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
721047f369cy#else
722047f369cy#define EVUTIL_AI_NUMERICHOST 0x4000
723047f369cy#endif
724047f369cy#if defined(AI_NUMERICSERV) && defined(EVENT__HAVE_GETADDRINFO)
725047f369cy#define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
726047f369cy#else
727047f369cy#define EVUTIL_AI_NUMERICSERV 0x8000
728047f369cy#endif
729047f369cy#if defined(AI_V4MAPPED) && defined(EVENT__HAVE_GETADDRINFO)
730047f369cy#define EVUTIL_AI_V4MAPPED AI_V4MAPPED
731047f369cy#else
732047f369cy#define EVUTIL_AI_V4MAPPED 0x10000
733047f369cy#endif
734047f369cy#if defined(AI_ALL) && defined(EVENT__HAVE_GETADDRINFO)
735047f369cy#define EVUTIL_AI_ALL AI_ALL
736047f369cy#else
737047f369cy#define EVUTIL_AI_ALL 0x20000
738047f369cy#endif
739047f369cy#if defined(AI_ADDRCONFIG) && defined(EVENT__HAVE_GETADDRINFO)
740047f369cy#define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
741047f369cy#else
742047f369cy#define EVUTIL_AI_ADDRCONFIG 0x40000
743047f369cy#endif
744047f369cy/**@}*/
745047f369cy
746047f369cystruct evutil_addrinfo;
747047f369cy/**
748047f369cy * This function clones getaddrinfo for systems that don't have it.  For full
749047f369cy * details, see RFC 3493, section 6.1.
750047f369cy *
751047f369cy * Limitations:
752047f369cy * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
753047f369cy *   gethostbyname, with their attendant issues.
754047f369cy * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
755047f369cy *
756047f369cy * For a nonblocking variant, see evdns_getaddrinfo.
757047f369cy */
758047f369cyEVENT2_EXPORT_SYMBOL
759047f369cyint evutil_getaddrinfo(const char *nodename, const char *servname,
760047f369cy    const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
761047f369cy
762047f369cy/** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
763047f369cyEVENT2_EXPORT_SYMBOL
764047f369cyvoid evutil_freeaddrinfo(struct evutil_addrinfo *ai);
765047f369cy
766047f369cyEVENT2_EXPORT_SYMBOL
767047f369cyconst char *evutil_gai_strerror(int err);
768047f369cy
769047f369cy/** Generate n bytes of secure pseudorandom data, and store them in buf.
770047f369cy *
771047f369cy * Current versions of Libevent use an ARC4-based random number generator,
772047f369cy * seeded using the platform's entropy source (/dev/urandom on Unix-like
773047f369cy * systems; CryptGenRandom on Windows).  This is not actually as secure as it
774047f369cy * should be: ARC4 is a pretty lousy cipher, and the current implementation
775047f369cy * provides only rudimentary prediction- and backtracking-resistance.  Don't
776047f369cy * use this for serious cryptographic applications.
777047f369cy */
778047f369cyEVENT2_EXPORT_SYMBOL
779047f369cyvoid evutil_secure_rng_get_bytes(void *buf, size_t n);
780047f369cy
781047f369cy/**
782047f369cy * Seed the secure random number generator if needed, and return 0 on
783047f369cy * success or -1 on failure.
784047f369cy *
785047f369cy * It is okay to call this function more than once; it will still return
786047f369cy * 0 if the RNG has been successfully seeded and -1 if it can't be
787047f369cy * seeded.
788047f369cy *
789047f369cy * Ordinarily you don't need to call this function from your own code;
790047f369cy * Libevent will seed the RNG itself the first time it needs good random
791047f369cy * numbers.  You only need to call it if (a) you want to double-check
792047f369cy * that one of the seeding methods did succeed, or (b) you plan to drop
793047f369cy * the capability to seed (by chrooting, or dropping capabilities, or
794047f369cy * whatever), and you want to make sure that seeding happens before your
795047f369cy * program loses the ability to do it.
796047f369cy */
797047f369cyEVENT2_EXPORT_SYMBOL
798047f369cyint evutil_secure_rng_init(void);
799047f369cy
800047f369cy/**
801047f369cy * Set a filename to use in place of /dev/urandom for seeding the secure
802047f369cy * PRNG. Return 0 on success, -1 on failure.
803047f369cy *
804047f369cy * Call this function BEFORE calling any other initialization or RNG
805047f369cy * functions.
806047f369cy *
807047f369cy * (This string will _NOT_ be copied internally. Do not free it while any
808047f369cy * user of the secure RNG might be running. Don't pass anything other than a
809047f369cy * real /dev/...random device file here, or you might lose security.)
810047f369cy *
811047f369cy * This API is unstable, and might change in a future libevent version.
812047f369cy */
813047f369cyEVENT2_EXPORT_SYMBOL
814047f369cyint evutil_secure_rng_set_urandom_device_file(char *fname);
815047f369cy
816047f369cy/** Seed the random number generator with extra random bytes.
817047f369cy
818047f369cy    You should almost never need to call this function; it should be
819047f369cy    sufficient to invoke evutil_secure_rng_init(), or let Libevent take
820047f369cy    care of calling evutil_secure_rng_init() on its own.
821047f369cy
822047f369cy    If you call this function as a _replacement_ for the regular
823047f369cy    entropy sources, then you need to be sure that your input
824047f369cy    contains a fairly large amount of strong entropy.  Doing so is
825047f369cy    notoriously hard: most people who try get it wrong.  Watch out!
826047f369cy
827047f369cy    @param dat a buffer full of a strong source of random numbers
828047f369cy    @param datlen the number of bytes to read from datlen
829047f369cy */
830047f369cyEVENT2_EXPORT_SYMBOL
831047f369cyvoid evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
832047f369cy
833047f369cy#ifdef __cplusplus
834047f369cy}
835047f369cy#endif
836047f369cy
837047f369cy#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
838