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