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