xref: /netbsd-src/external/bsd/ntp/dist/sntp/libevent/include/event2/util.h (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: util.h,v 1.5 2016/01/08 21:35:41 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 #ifndef EVENT2_UTIL_H_INCLUDED_
29 #define EVENT2_UTIL_H_INCLUDED_
30 
31 /** @file event2/util.h
32 
33   Common convenience functions for cross-platform portability and
34   related socket manipulations.
35 
36  */
37 #include <event2/visibility.h>
38 
39 #ifdef __cplusplus
40 extern "C" {
41 #endif
42 
43 #include <event2/event-config.h>
44 #ifdef EVENT__HAVE_SYS_TIME_H
45 #include <sys/time.h>
46 #endif
47 #ifdef EVENT__HAVE_STDINT_H
48 #include <stdint.h>
49 #elif defined(EVENT__HAVE_INTTYPES_H)
50 #include <inttypes.h>
51 #endif
52 #ifdef EVENT__HAVE_SYS_TYPES_H
53 #include <sys/types.h>
54 #endif
55 #ifdef EVENT__HAVE_STDDEF_H
56 #include <stddef.h>
57 #endif
58 #ifdef _MSC_VER
59 #include <BaseTsd.h>
60 #endif
61 #include <stdarg.h>
62 #ifdef EVENT__HAVE_NETDB_H
63 #if !defined(_GNU_SOURCE)
64 #define _GNU_SOURCE
65 #endif
66 #include <netdb.h>
67 #endif
68 
69 #ifdef _WIN32
70 #include <winsock2.h>
71 #ifdef EVENT__HAVE_GETADDRINFO
72 /* for EAI_* definitions. */
73 #include <ws2tcpip.h>
74 #endif
75 #else
76 #include <sys/socket.h>
77 #endif
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 #define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
239 #define EV_INT64_MAX  ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
240 #define EV_INT64_MIN  ((-EV_INT64_MAX) - 1)
241 #define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
242 #define EV_INT32_MAX  ((ev_int32_t) 0x7fffffffL)
243 #define EV_INT32_MIN  ((-EV_INT32_MAX) - 1)
244 #define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
245 #define EV_INT16_MAX  ((ev_int16_t) 0x7fffL)
246 #define EV_INT16_MIN  ((-EV_INT16_MAX) - 1)
247 #define EV_UINT8_MAX  255
248 #define EV_INT8_MAX   127
249 #define EV_INT8_MIN   ((-EV_INT8_MAX) - 1)
250 /** @} */
251 
252 /**
253    @name Limits for SIZE_T and SSIZE_T
254 
255    @{
256 */
257 #if EVENT__SIZEOF_SIZE_T == 8
258 #define EV_SIZE_MAX EV_UINT64_MAX
259 #define EV_SSIZE_MAX EV_INT64_MAX
260 #elif EVENT__SIZEOF_SIZE_T == 4
261 #define EV_SIZE_MAX EV_UINT32_MAX
262 #define EV_SSIZE_MAX EV_INT32_MAX
263 #elif defined(EVENT_IN_DOXYGEN_)
264 #define EV_SIZE_MAX ...
265 #define EV_SSIZE_MAX ...
266 #else
267 #error "No way to define SIZE_MAX"
268 #endif
269 
270 #define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
271 /**@}*/
272 
273 #ifdef _WIN32
274 #define ev_socklen_t int
275 #elif defined(EVENT__socklen_t)
276 #define ev_socklen_t EVENT__socklen_t
277 #else
278 #define ev_socklen_t socklen_t
279 #endif
280 
281 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
282 #if !defined(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
283  && !defined(ss_family)
284 #define ss_family __ss_family
285 #endif
286 #endif
287 
288 /**
289  * A type wide enough to hold the output of "socket()" or "accept()".  On
290  * Windows, this is an intptr_t; elsewhere, it is an int. */
291 #ifdef _WIN32
292 #define evutil_socket_t intptr_t
293 #else
294 #define evutil_socket_t int
295 #endif
296 
297 /**
298  * Structure to hold information about a monotonic timer
299  *
300  * Use this with evutil_configure_monotonic_time() and
301  * evutil_gettime_monotonic().
302  *
303  * This is an opaque structure; you can allocate one using
304  * evutil_monotonic_timer_new().
305  *
306  * @see evutil_monotonic_timer_new(), evutil_monotonic_timer_free(),
307  * evutil_configure_monotonic_time(), evutil_gettime_monotonic()
308  */
309 struct evutil_monotonic_timer
310 #ifdef EVENT_IN_DOXYGEN_
311 {/*Empty body so that doxygen will generate documentation here.*/}
312 #endif
313 ;
314 
315 #define EV_MONOT_PRECISE  1
316 #define EV_MONOT_FALLBACK 2
317 
318 /** Allocate a new struct evutil_monotonic_timer for use with the
319  * evutil_configure_monotonic_time() and evutil_gettime_monotonic()
320  * functions.  You must configure the timer with
321  * evutil_configure_monotonic_time() before using it.
322  */
323 EVENT2_EXPORT_SYMBOL
324 struct evutil_monotonic_timer * evutil_monotonic_timer_new(void);
325 
326 /** Free a struct evutil_monotonic_timer that was allocated using
327  * evutil_monotonic_timer_new().
328  */
329 EVENT2_EXPORT_SYMBOL
330 void evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer);
331 
332 /** Set up a struct evutil_monotonic_timer; flags can include
333  * EV_MONOT_PRECISE and EV_MONOT_FALLBACK.
334  */
335 EVENT2_EXPORT_SYMBOL
336 int evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
337                                     int flags);
338 
339 /** Query the current monotonic time from a struct evutil_monotonic_timer
340  * previously configured with evutil_configure_monotonic_time().  Monotonic
341  * time is guaranteed never to run in reverse, but is not necessarily epoch-
342  * based, or relative to any other definite point.  Use it to make reliable
343  * measurements of elapsed time between events even when the system time
344  * may be changed.
345  *
346  * It is not safe to use this funtion on the same timer from multiple
347  * threads.
348  */
349 EVENT2_EXPORT_SYMBOL
350 int evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
351                              struct timeval *tp);
352 
353 /** Create two new sockets that are connected to each other.
354 
355     On Unix, this simply calls socketpair().  On Windows, it uses the
356     loopback network interface on 127.0.0.1, and only
357     AF_INET,SOCK_STREAM are supported.
358 
359     (This may fail on some Windows hosts where firewall software has cleverly
360     decided to keep 127.0.0.1 from talking to itself.)
361 
362     Parameters and return values are as for socketpair()
363 */
364 EVENT2_EXPORT_SYMBOL
365 int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
366 /** Do platform-specific operations as needed to make a socket nonblocking.
367 
368     @param sock The socket to make nonblocking
369     @return 0 on success, -1 on failure
370  */
371 EVENT2_EXPORT_SYMBOL
372 int evutil_make_socket_nonblocking(evutil_socket_t sock);
373 
374 /** Do platform-specific operations to make a listener socket reusable.
375 
376     Specifically, we want to make sure that another program will be able
377     to bind this address right after we've closed the listener.
378 
379     This differs from Windows's interpretation of "reusable", which
380     allows multiple listeners to bind the same address at the same time.
381 
382     @param sock The socket to make reusable
383     @return 0 on success, -1 on failure
384  */
385 EVENT2_EXPORT_SYMBOL
386 int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
387 
388 /** Do platform-specific operations to make a listener port reusable.
389 
390     Specifically, we want to make sure that multiple programs which also
391     set the same socket option will be able to bind, listen at the same time.
392 
393     This is a feature available only to Linux 3.9+
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_port(evutil_socket_t sock);
400 
401 /** Do platform-specific operations as needed to close a socket upon a
402     successful execution of one of the exec*() functions.
403 
404     @param sock The socket to be closed
405     @return 0 on success, -1 on failure
406  */
407 EVENT2_EXPORT_SYMBOL
408 int evutil_make_socket_closeonexec(evutil_socket_t sock);
409 
410 /** Do the platform-specific call needed to close a socket returned from
411     socket() or accept().
412 
413     @param sock The socket to be closed
414     @return 0 on success, -1 on failure
415  */
416 EVENT2_EXPORT_SYMBOL
417 int evutil_closesocket(evutil_socket_t sock);
418 #define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
419 
420 /** Do platform-specific operations, if possible, to make a tcp listener
421  *  socket defer accept()s until there is data to read.
422  *
423  *  Not all platforms support this.  You don't want to do this for every
424  *  listener socket: only the ones that implement a protocol where the
425  *  client transmits before the server needs to respond.
426  *
427  *  @param sock The listening socket to to make deferred
428  *  @return 0 on success (whether the operation is supported or not),
429  *       -1 on failure
430 */
431 EVENT2_EXPORT_SYMBOL
432 int evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock);
433 
434 #ifdef _WIN32
435 /** Return the most recent socket error.  Not idempotent on all platforms. */
436 #define EVUTIL_SOCKET_ERROR() WSAGetLastError()
437 /** Replace the most recent socket error with errcode */
438 #define EVUTIL_SET_SOCKET_ERROR(errcode)		\
439 	do { WSASetLastError(errcode); } while (0)
440 /** Return the most recent socket error to occur on sock. */
441 EVENT2_EXPORT_SYMBOL
442 int evutil_socket_geterror(evutil_socket_t sock);
443 /** Convert a socket error to a string. */
444 EVENT2_EXPORT_SYMBOL
445 const char *evutil_socket_error_to_string(int errcode);
446 #elif defined(EVENT_IN_DOXYGEN_)
447 /**
448    @name Socket error functions
449 
450    These functions are needed for making programs compatible between
451    Windows and Unix-like platforms.
452 
453    You see, Winsock handles socket errors differently from the rest of
454    the world.  Elsewhere, a socket error is like any other error and is
455    stored in errno.  But winsock functions require you to retrieve the
456    error with a special function, and don't let you use strerror for
457    the error codes.  And handling EWOULDBLOCK is ... different.
458 
459    @{
460 */
461 /** Return the most recent socket error.  Not idempotent on all platforms. */
462 #define EVUTIL_SOCKET_ERROR() ...
463 /** Replace the most recent socket error with errcode */
464 #define EVUTIL_SET_SOCKET_ERROR(errcode) ...
465 /** Return the most recent socket error to occur on sock. */
466 #define evutil_socket_geterror(sock) ...
467 /** Convert a socket error to a string. */
468 #define evutil_socket_error_to_string(errcode) ...
469 /**@}*/
470 #else
471 #define EVUTIL_SOCKET_ERROR() (errno)
472 #define EVUTIL_SET_SOCKET_ERROR(errcode)		\
473 		do { errno = (errcode); } while (0)
474 #define evutil_socket_geterror(sock) (errno)
475 #define evutil_socket_error_to_string(errcode) (strerror(errcode))
476 #endif
477 
478 
479 /**
480  * @name Manipulation macros for struct timeval.
481  *
482  * We define replacements
483  * for timeradd, timersub, timerclear, timercmp, and timerisset.
484  *
485  * @{
486  */
487 #ifdef EVENT__HAVE_TIMERADD
488 #define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
489 #define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
490 #else
491 #define evutil_timeradd(tvp, uvp, vvp)					\
492 	do {								\
493 		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
494 		(vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
495 		if ((vvp)->tv_usec >= 1000000) {			\
496 			(vvp)->tv_sec++;				\
497 			(vvp)->tv_usec -= 1000000;			\
498 		}							\
499 	} while (0)
500 #define	evutil_timersub(tvp, uvp, vvp)					\
501 	do {								\
502 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
503 		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
504 		if ((vvp)->tv_usec < 0) {				\
505 			(vvp)->tv_sec--;				\
506 			(vvp)->tv_usec += 1000000;			\
507 		}							\
508 	} while (0)
509 #endif /* !EVENT__HAVE_TIMERADD */
510 
511 #ifdef EVENT__HAVE_TIMERCLEAR
512 #define evutil_timerclear(tvp) timerclear(tvp)
513 #else
514 #define	evutil_timerclear(tvp)	(tvp)->tv_sec = (tvp)->tv_usec = 0
515 #endif
516 /**@}*/
517 
518 /** Return true iff the tvp is related to uvp according to the relational
519  * operator cmp.  Recognized values for cmp are ==, <=, <, >=, and >. */
520 #define	evutil_timercmp(tvp, uvp, cmp)					\
521 	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
522 	 ((tvp)->tv_usec cmp (uvp)->tv_usec) :				\
523 	 ((tvp)->tv_sec cmp (uvp)->tv_sec))
524 
525 #ifdef EVENT__HAVE_TIMERISSET
526 #define evutil_timerisset(tvp) timerisset(tvp)
527 #else
528 #define	evutil_timerisset(tvp)	((tvp)->tv_sec || (tvp)->tv_usec)
529 #endif
530 
531 /** Replacement for offsetof on platforms that don't define it. */
532 #ifdef offsetof
533 #define evutil_offsetof(type, field) offsetof(type, field)
534 #else
535 #define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
536 #endif
537 
538 /* big-int related functions */
539 /** Parse a 64-bit value from a string.  Arguments are as for strtol. */
540 EVENT2_EXPORT_SYMBOL
541 ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
542 
543 /** Replacement for gettimeofday on platforms that lack it. */
544 #ifdef EVENT__HAVE_GETTIMEOFDAY
545 #define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
546 #else
547 struct timezone;
548 EVENT2_EXPORT_SYMBOL
549 int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
550 #endif
551 
552 /** Replacement for snprintf to get consistent behavior on platforms for
553     which the return value of snprintf does not conform to C99.
554  */
555 EVENT2_EXPORT_SYMBOL
556 int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
557 #ifdef __GNUC__
558 	__attribute__((format(printf, 3, 4)))
559 #endif
560 ;
561 /** Replacement for vsnprintf to get consistent behavior on platforms for
562     which the return value of snprintf does not conform to C99.
563  */
564 EVENT2_EXPORT_SYMBOL
565 int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
566 #ifdef __GNUC__
567 	__attribute__((format(printf, 3, 0)))
568 #endif
569 ;
570 
571 /** Replacement for inet_ntop for platforms which lack it. */
572 EVENT2_EXPORT_SYMBOL
573 const char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
574 /** Replacement for inet_pton for platforms which lack it. */
575 EVENT2_EXPORT_SYMBOL
576 int evutil_inet_pton(int af, const char *src, void *dst);
577 struct sockaddr;
578 
579 /** Parse an IPv4 or IPv6 address, with optional port, from a string.
580 
581     Recognized formats are:
582     - [IPv6Address]:port
583     - [IPv6Address]
584     - IPv6Address
585     - IPv4Address:port
586     - IPv4Address
587 
588     If no port is specified, the port in the output is set to 0.
589 
590     @param str The string to parse.
591     @param out A struct sockaddr to hold the result.  This should probably be
592        a struct sockaddr_storage.
593     @param outlen A pointer to the number of bytes that that 'out' can safely
594        hold.  Set to the number of bytes used in 'out' on success.
595     @return -1 if the address is not well-formed, if the port is out of range,
596        or if out is not large enough to hold the result.  Otherwise returns
597        0 on success.
598 */
599 EVENT2_EXPORT_SYMBOL
600 int evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
601 
602 /** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
603  * preceeds sa2, or greater than 0 if sa1 follows sa2.  If include_port is
604  * true, consider the port as well as the address.  Only implemented for
605  * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
606  * the same between Libevent versions. */
607 EVENT2_EXPORT_SYMBOL
608 int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
609     int include_port);
610 
611 /** As strcasecmp, but always compares the characters in locale-independent
612     ASCII.  That's useful if you're handling data in ASCII-based protocols.
613  */
614 EVENT2_EXPORT_SYMBOL
615 int evutil_ascii_strcasecmp(const char *str1, const char *str2);
616 /** As strncasecmp, but always compares the characters in locale-independent
617     ASCII.  That's useful if you're handling data in ASCII-based protocols.
618  */
619 EVENT2_EXPORT_SYMBOL
620 int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
621 
622 /* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
623  * if this system has no getaddrinfo(). */
624 #ifdef EVENT__HAVE_STRUCT_ADDRINFO
625 #define evutil_addrinfo addrinfo
626 #else
627 /** A definition of struct addrinfo for systems that lack it.
628 
629     (This is just an alias for struct addrinfo if the system defines
630     struct addrinfo.)
631 */
632 struct evutil_addrinfo {
633 	int     ai_flags;     /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
634 	int     ai_family;    /* PF_xxx */
635 	int     ai_socktype;  /* SOCK_xxx */
636 	int     ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
637 	size_t  ai_addrlen;   /* length of ai_addr */
638 	char   *ai_canonname; /* canonical name for nodename */
639 	struct sockaddr  *ai_addr; /* binary address */
640 	struct evutil_addrinfo  *ai_next; /* next structure in linked list */
641 };
642 #endif
643 /** @name evutil_getaddrinfo() error codes
644 
645     These values are possible error codes for evutil_getaddrinfo() and
646     related functions.
647 
648     @{
649 */
650 #if defined(EAI_ADDRFAMILY) && defined(EVENT__HAVE_GETADDRINFO)
651 #define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
652 #else
653 #define EVUTIL_EAI_ADDRFAMILY -901
654 #endif
655 #if defined(EAI_AGAIN) && defined(EVENT__HAVE_GETADDRINFO)
656 #define EVUTIL_EAI_AGAIN EAI_AGAIN
657 #else
658 #define EVUTIL_EAI_AGAIN -902
659 #endif
660 #if defined(EAI_BADFLAGS) && defined(EVENT__HAVE_GETADDRINFO)
661 #define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
662 #else
663 #define EVUTIL_EAI_BADFLAGS -903
664 #endif
665 #if defined(EAI_FAIL) && defined(EVENT__HAVE_GETADDRINFO)
666 #define EVUTIL_EAI_FAIL EAI_FAIL
667 #else
668 #define EVUTIL_EAI_FAIL -904
669 #endif
670 #if defined(EAI_FAMILY) && defined(EVENT__HAVE_GETADDRINFO)
671 #define EVUTIL_EAI_FAMILY EAI_FAMILY
672 #else
673 #define EVUTIL_EAI_FAMILY -905
674 #endif
675 #if defined(EAI_MEMORY) && defined(EVENT__HAVE_GETADDRINFO)
676 #define EVUTIL_EAI_MEMORY EAI_MEMORY
677 #else
678 #define EVUTIL_EAI_MEMORY -906
679 #endif
680 /* This test is a bit complicated, since some MS SDKs decide to
681  * remove NODATA or redefine it to be the same as NONAME, in a
682  * fun interpretation of RFC 2553 and RFC 3493. */
683 #if defined(EAI_NODATA) && defined(EVENT__HAVE_GETADDRINFO) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
684 #define EVUTIL_EAI_NODATA EAI_NODATA
685 #else
686 #define EVUTIL_EAI_NODATA -907
687 #endif
688 #if defined(EAI_NONAME) && defined(EVENT__HAVE_GETADDRINFO)
689 #define EVUTIL_EAI_NONAME EAI_NONAME
690 #else
691 #define EVUTIL_EAI_NONAME -908
692 #endif
693 #if defined(EAI_SERVICE) && defined(EVENT__HAVE_GETADDRINFO)
694 #define EVUTIL_EAI_SERVICE EAI_SERVICE
695 #else
696 #define EVUTIL_EAI_SERVICE -909
697 #endif
698 #if defined(EAI_SOCKTYPE) && defined(EVENT__HAVE_GETADDRINFO)
699 #define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
700 #else
701 #define EVUTIL_EAI_SOCKTYPE -910
702 #endif
703 #if defined(EAI_SYSTEM) && defined(EVENT__HAVE_GETADDRINFO)
704 #define EVUTIL_EAI_SYSTEM EAI_SYSTEM
705 #else
706 #define EVUTIL_EAI_SYSTEM -911
707 #endif
708 
709 #define EVUTIL_EAI_CANCEL -90001
710 
711 #if defined(AI_PASSIVE) && defined(EVENT__HAVE_GETADDRINFO)
712 #define EVUTIL_AI_PASSIVE AI_PASSIVE
713 #else
714 #define EVUTIL_AI_PASSIVE 0x1000
715 #endif
716 #if defined(AI_CANONNAME) && defined(EVENT__HAVE_GETADDRINFO)
717 #define EVUTIL_AI_CANONNAME AI_CANONNAME
718 #else
719 #define EVUTIL_AI_CANONNAME 0x2000
720 #endif
721 #if defined(AI_NUMERICHOST) && defined(EVENT__HAVE_GETADDRINFO)
722 #define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
723 #else
724 #define EVUTIL_AI_NUMERICHOST 0x4000
725 #endif
726 #if defined(AI_NUMERICSERV) && defined(EVENT__HAVE_GETADDRINFO)
727 #define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
728 #else
729 #define EVUTIL_AI_NUMERICSERV 0x8000
730 #endif
731 #if defined(AI_V4MAPPED) && defined(EVENT__HAVE_GETADDRINFO)
732 #define EVUTIL_AI_V4MAPPED AI_V4MAPPED
733 #else
734 #define EVUTIL_AI_V4MAPPED 0x10000
735 #endif
736 #if defined(AI_ALL) && defined(EVENT__HAVE_GETADDRINFO)
737 #define EVUTIL_AI_ALL AI_ALL
738 #else
739 #define EVUTIL_AI_ALL 0x20000
740 #endif
741 #if defined(AI_ADDRCONFIG) && defined(EVENT__HAVE_GETADDRINFO)
742 #define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
743 #else
744 #define EVUTIL_AI_ADDRCONFIG 0x40000
745 #endif
746 /**@}*/
747 
748 struct evutil_addrinfo;
749 /**
750  * This function clones getaddrinfo for systems that don't have it.  For full
751  * details, see RFC 3493, section 6.1.
752  *
753  * Limitations:
754  * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
755  *   gethostbyname, with their attendant issues.
756  * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
757  *
758  * For a nonblocking variant, see evdns_getaddrinfo.
759  */
760 EVENT2_EXPORT_SYMBOL
761 int evutil_getaddrinfo(const char *nodename, const char *servname,
762     const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
763 
764 /** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
765 EVENT2_EXPORT_SYMBOL
766 void evutil_freeaddrinfo(struct evutil_addrinfo *ai);
767 
768 EVENT2_EXPORT_SYMBOL
769 const char *evutil_gai_strerror(int err);
770 
771 /** Generate n bytes of secure pseudorandom data, and store them in buf.
772  *
773  * Current versions of Libevent use an ARC4-based random number generator,
774  * seeded using the platform's entropy source (/dev/urandom on Unix-like
775  * systems; CryptGenRandom on Windows).  This is not actually as secure as it
776  * should be: ARC4 is a pretty lousy cipher, and the current implementation
777  * provides only rudimentary prediction- and backtracking-resistance.  Don't
778  * use this for serious cryptographic applications.
779  */
780 EVENT2_EXPORT_SYMBOL
781 void evutil_secure_rng_get_bytes(void *buf, size_t n);
782 
783 /**
784  * Seed the secure random number generator if needed, and return 0 on
785  * success or -1 on failure.
786  *
787  * It is okay to call this function more than once; it will still return
788  * 0 if the RNG has been successfully seeded and -1 if it can't be
789  * seeded.
790  *
791  * Ordinarily you don't need to call this function from your own code;
792  * Libevent will seed the RNG itself the first time it needs good random
793  * numbers.  You only need to call it if (a) you want to double-check
794  * that one of the seeding methods did succeed, or (b) you plan to drop
795  * the capability to seed (by chrooting, or dropping capabilities, or
796  * whatever), and you want to make sure that seeding happens before your
797  * program loses the ability to do it.
798  */
799 EVENT2_EXPORT_SYMBOL
800 int evutil_secure_rng_init(void);
801 
802 /**
803  * Set a filename to use in place of /dev/urandom for seeding the secure
804  * PRNG. Return 0 on success, -1 on failure.
805  *
806  * Call this function BEFORE calling any other initialization or RNG
807  * functions.
808  *
809  * (This string will _NOT_ be copied internally. Do not free it while any
810  * user of the secure RNG might be running. Don't pass anything other than a
811  * real /dev/...random device file here, or you might lose security.)
812  *
813  * This API is unstable, and might change in a future libevent version.
814  */
815 EVENT2_EXPORT_SYMBOL
816 int evutil_secure_rng_set_urandom_device_file(char *fname);
817 
818 /** Seed the random number generator with extra random bytes.
819 
820     You should almost never need to call this function; it should be
821     sufficient to invoke evutil_secure_rng_init(), or let Libevent take
822     care of calling evutil_secure_rng_init() on its own.
823 
824     If you call this function as a _replacement_ for the regular
825     entropy sources, then you need to be sure that your input
826     contains a fairly large amount of strong entropy.  Doing so is
827     notoriously hard: most people who try get it wrong.  Watch out!
828 
829     @param dat a buffer full of a strong source of random numbers
830     @param datlen the number of bytes to read from datlen
831  */
832 EVENT2_EXPORT_SYMBOL
833 void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
834 
835 #ifdef __cplusplus
836 }
837 #endif
838 
839 #endif /* EVENT1_EVUTIL_H_INCLUDED_ */
840