2 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "event2/event-config.h"
28 #include "evconfig-private.h"
33 #define WIN32_LEAN_AND_MEAN
35 #undef WIN32_LEAN_AND_MEAN
40 /* For structs needed by GetAdaptersAddresses */
41 #define _WIN32_WINNT 0x0501
45 #include <sys/types.h>
46 #ifdef EVENT__HAVE_SYS_SOCKET_H
47 #include <sys/socket.h>
49 #ifdef EVENT__HAVE_UNISTD_H
52 #ifdef EVENT__HAVE_FCNTL_H
55 #ifdef EVENT__HAVE_STDLIB_H
62 #ifdef EVENT__HAVE_NETINET_IN_H
63 #include <netinet/in.h>
65 #ifdef EVENT__HAVE_NETINET_IN6_H
66 #include <netinet/in6.h>
68 #ifdef EVENT__HAVE_NETINET_TCP_H
69 #include <netinet/tcp.h>
71 #ifdef EVENT__HAVE_ARPA_INET_H
72 #include <arpa/inet.h>
76 #ifdef EVENT__HAVE_IFADDRS_H
80 #include "event2/util.h"
81 #include "util-internal.h"
82 #include "log-internal.h"
83 #include "mm-internal.h"
84 #include "evthread-internal.h"
86 #include "strlcpy-internal.h"
87 #include "ipv6-internal.h"
90 #define HT_NO_CACHE_HASH_VALUES
91 #include "ht-internal.h"
96 #define fstat _fstati64
105 evutil_open_closeonexec_(const char *pathname
, int flags
, unsigned mode
)
110 fd
= open(pathname
, flags
|O_CLOEXEC
, (mode_t
)mode
);
111 if (fd
>= 0 || errno
== EINVAL
)
113 /* If we got an EINVAL, fall through and try without O_CLOEXEC */
115 fd
= open(pathname
, flags
, (mode_t
)mode
);
119 #if defined(FD_CLOEXEC)
120 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
) < 0) {
130 Read the contents of 'filename' into a newly allocated NUL-terminated
131 string. Set *content_out to hold this string, and *len_out to hold its
132 length (not including the appended NUL). If 'is_binary', open the file in
135 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
137 Used internally only; may go away in a future version.
140 evutil_read_file_(const char *filename
, char **content_out
, size_t *len_out
,
146 size_t read_so_far
=0;
149 EVUTIL_ASSERT(content_out
);
150 EVUTIL_ASSERT(len_out
);
159 fd
= evutil_open_closeonexec_(filename
, mode
, 0);
162 if (fstat(fd
, &st
) || st
.st_size
< 0 ||
163 st
.st_size
> EV_SSIZE_MAX
-1 ) {
167 mem
= mm_malloc((size_t)st
.st_size
+ 1);
174 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
176 #define N_TO_READ(x) (x)
178 while ((r
= read(fd
, mem
+read_so_far
, N_TO_READ(st
.st_size
- read_so_far
))) > 0) {
180 if (read_so_far
>= (size_t)st
.st_size
)
182 EVUTIL_ASSERT(read_so_far
< (size_t)st
.st_size
);
189 mem
[read_so_far
] = 0;
191 *len_out
= read_so_far
;
197 evutil_socketpair(int family
, int type
, int protocol
, evutil_socket_t fd
[2])
200 return socketpair(family
, type
, protocol
, fd
);
202 return evutil_ersatz_socketpair_(family
, type
, protocol
, fd
);
207 evutil_ersatz_socketpair_(int family
, int type
, int protocol
,
208 evutil_socket_t fd
[2])
210 /* This code is originally from Tor. Used with permission. */
212 /* This socketpair does not work when localhost is down. So
213 * it's really not the same thing at all. But it's close enough
214 * for now, and really, when localhost is down sometimes, we
215 * have other problems too.
218 #define ERR(e) WSA##e
222 evutil_socket_t listener
= -1;
223 evutil_socket_t connector
= -1;
224 evutil_socket_t acceptor
= -1;
225 struct sockaddr_in listen_addr
;
226 struct sockaddr_in connect_addr
;
228 int saved_errno
= -1;
231 family_test
= family
!= AF_INET
;
233 family_test
= family_test
&& (family
!= AF_UNIX
);
235 if (protocol
|| family_test
) {
236 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT
));
241 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL
));
245 listener
= socket(AF_INET
, type
, 0);
248 memset(&listen_addr
, 0, sizeof(listen_addr
));
249 listen_addr
.sin_family
= AF_INET
;
250 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
251 listen_addr
.sin_port
= 0; /* kernel chooses port. */
252 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
254 goto tidy_up_and_fail
;
255 if (listen(listener
, 1) == -1)
256 goto tidy_up_and_fail
;
258 connector
= socket(AF_INET
, type
, 0);
260 goto tidy_up_and_fail
;
262 memset(&connect_addr
, 0, sizeof(connect_addr
));
264 /* We want to find out the port number to connect to. */
265 size
= sizeof(connect_addr
);
266 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
267 goto tidy_up_and_fail
;
268 if (size
!= sizeof (connect_addr
))
269 goto abort_tidy_up_and_fail
;
270 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
271 sizeof(connect_addr
)) == -1)
272 goto tidy_up_and_fail
;
274 size
= sizeof(listen_addr
);
275 acceptor
= accept(listener
, (struct sockaddr
*) &listen_addr
, &size
);
277 goto tidy_up_and_fail
;
278 if (size
!= sizeof(listen_addr
))
279 goto abort_tidy_up_and_fail
;
280 /* Now check we are talking to ourself by matching port and host on the
282 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
283 goto tidy_up_and_fail
;
284 if (size
!= sizeof (connect_addr
)
285 || listen_addr
.sin_family
!= connect_addr
.sin_family
286 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
287 || listen_addr
.sin_port
!= connect_addr
.sin_port
)
288 goto abort_tidy_up_and_fail
;
289 evutil_closesocket(listener
);
295 abort_tidy_up_and_fail
:
296 saved_errno
= ERR(ECONNABORTED
);
299 saved_errno
= EVUTIL_SOCKET_ERROR();
301 evutil_closesocket(listener
);
303 evutil_closesocket(connector
);
305 evutil_closesocket(acceptor
);
307 EVUTIL_SET_SOCKET_ERROR(saved_errno
);
313 evutil_make_socket_nonblocking(evutil_socket_t fd
)
317 unsigned long nonblocking
= 1;
318 if (ioctlsocket(fd
, FIONBIO
, &nonblocking
) == SOCKET_ERROR
) {
319 event_sock_warn(fd
, "fcntl(%d, F_GETFL)", (int)fd
);
326 if ((flags
= fcntl(fd
, F_GETFL
, NULL
)) < 0) {
327 event_warn("fcntl(%d, F_GETFL)", fd
);
330 if (!(flags
& O_NONBLOCK
)) {
331 if (fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
) == -1) {
332 event_warn("fcntl(%d, F_SETFL)", fd
);
341 /* Faster version of evutil_make_socket_nonblocking for internal use.
343 * Requires that no F_SETFL flags were previously set on the fd.
346 evutil_fast_socket_nonblocking(evutil_socket_t fd
)
349 return evutil_make_socket_nonblocking(fd
);
351 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) == -1) {
352 event_warn("fcntl(%d, F_SETFL)", fd
);
360 evutil_make_listen_socket_reuseable(evutil_socket_t sock
)
362 #if defined(SO_REUSEADDR) && !defined(_WIN32)
364 /* REUSEADDR on Unix means, "don't hang on to this address after the
365 * listener is closed." On Windows, though, it means "don't keep other
366 * processes from binding to this address while we're using it. */
367 return setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
,
368 (ev_socklen_t
)sizeof(one
));
375 evutil_make_listen_socket_reuseable_port(evutil_socket_t sock
)
377 #if defined __linux__ && defined(SO_REUSEPORT)
379 /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
380 * threads) can bind to the same port if they each set the option. */
381 return setsockopt(sock
, SOL_SOCKET
, SO_REUSEPORT
, (void*) &one
,
382 (ev_socklen_t
)sizeof(one
));
389 evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock
)
391 #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
394 /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
395 * has arrived and ready to read */
396 return setsockopt(sock
, IPPROTO_TCP
, TCP_DEFER_ACCEPT
, &one
,
397 (ev_socklen_t
)sizeof(one
));
403 evutil_make_socket_closeonexec(evutil_socket_t fd
)
405 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
407 if ((flags
= fcntl(fd
, F_GETFD
, NULL
)) < 0) {
408 event_warn("fcntl(%d, F_GETFD)", fd
);
411 if (!(flags
& FD_CLOEXEC
)) {
412 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) == -1) {
413 event_warn("fcntl(%d, F_SETFD)", fd
);
421 /* Faster version of evutil_make_socket_closeonexec for internal use.
423 * Requires that no F_SETFD flags were previously set on the fd.
426 evutil_fast_socket_closeonexec(evutil_socket_t fd
)
428 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
429 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
) == -1) {
430 event_warn("fcntl(%d, F_SETFD)", fd
);
438 evutil_closesocket(evutil_socket_t sock
)
443 return closesocket(sock
);
448 evutil_strtoll(const char *s
, char **endptr
, int base
)
450 #ifdef EVENT__HAVE_STRTOLL
451 return (ev_int64_t
)strtoll(s
, endptr
, base
);
452 #elif EVENT__SIZEOF_LONG == 8
453 return (ev_int64_t
)strtol(s
, endptr
, base
);
454 #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
455 /* XXXX on old versions of MS APIs, we only support base
460 r
= (ev_int64_t
) _atoi64(s
);
470 #elif defined(_WIN32)
471 return (ev_int64_t
) _strtoi64(s
, endptr
, base
);
472 #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
475 if (base
!= 10 && base
!= 16)
478 n
= sscanf(s
, "%lld", &r
);
480 unsigned long long ru
=0;
481 n
= sscanf(s
, "%llx", &ru
);
482 if (ru
> EV_INT64_MAX
)
488 while (EVUTIL_ISSPACE_(*s
))
493 while (EVUTIL_ISDIGIT_(*s
))
496 while (EVUTIL_ISXDIGIT_(*s
))
503 #error "I don't know how to parse 64-bit integers."
509 evutil_socket_geterror(evutil_socket_t sock
)
511 int optval
, optvallen
=sizeof(optval
);
512 int err
= WSAGetLastError();
513 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
514 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
,
524 /* XXX we should use an enum here. */
525 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
527 evutil_socket_connect_(evutil_socket_t
*fd_ptr
, const struct sockaddr
*sa
, int socklen
)
532 if ((*fd_ptr
= socket(sa
->sa_family
, SOCK_STREAM
, 0)) < 0)
535 if (evutil_make_socket_nonblocking(*fd_ptr
) < 0) {
540 if (connect(*fd_ptr
, sa
, socklen
) < 0) {
541 int e
= evutil_socket_geterror(*fd_ptr
);
542 if (EVUTIL_ERR_CONNECT_RETRIABLE(e
))
544 if (EVUTIL_ERR_CONNECT_REFUSED(e
))
553 evutil_closesocket(*fd_ptr
);
559 /* Check whether a socket on which we called connect() is done
560 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
561 error case, set the current socket errno to the error that happened during
562 the connect operation. */
564 evutil_socket_finished_connecting_(evutil_socket_t fd
)
567 ev_socklen_t elen
= sizeof(e
);
569 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &elen
) < 0)
573 if (EVUTIL_ERR_CONNECT_RETRIABLE(e
))
575 EVUTIL_SET_SOCKET_ERROR(e
);
582 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
583 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
584 EVUTIL_AI_ADDRCONFIG) != \
585 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
586 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
587 EVUTIL_AI_ADDRCONFIG)
588 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
591 /* We sometimes need to know whether we have an ipv4 address and whether we
592 have an ipv6 address. If 'have_checked_interfaces', then we've already done
593 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
594 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
595 set by evutil_check_interfaces. */
596 static int have_checked_interfaces
, had_ipv4_address
, had_ipv6_address
;
598 /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
600 #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
602 /* Macro: True iff the IPv4 address 'addr', in host order, is a class D
603 * (multiclass) address.
605 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
608 evutil_found_ifaddr(const struct sockaddr
*sa
)
610 const char ZEROES
[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
611 "\x00\x00\x00\x00\x00\x00\x00\x00";
613 if (sa
->sa_family
== AF_INET
) {
614 const struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
615 ev_uint32_t addr
= ntohl(sin
->sin_addr
.s_addr
);
617 EVUTIL_V4ADDR_IS_LOCALHOST(addr
) ||
618 EVUTIL_V4ADDR_IS_CLASSD(addr
)) {
619 /* Not actually a usable external address. */
621 event_debug(("Detected an IPv4 interface"));
622 had_ipv4_address
= 1;
624 } else if (sa
->sa_family
== AF_INET6
) {
625 const struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
626 const unsigned char *addr
=
627 (unsigned char*)sin6
->sin6_addr
.s6_addr
;
628 if (!memcmp(addr
, ZEROES
, 8) ||
629 ((addr
[0] & 0xfe) == 0xfc) ||
630 (addr
[0] == 0xfe && (addr
[1] & 0xc0) == 0x80) ||
631 (addr
[0] == 0xfe && (addr
[1] & 0xc0) == 0xc0) ||
633 /* This is a reserved, ipv4compat, ipv4map, loopback,
634 * link-local, multicast, or unspecified address. */
636 event_debug(("Detected an IPv6 interface"));
637 had_ipv6_address
= 1;
643 typedef ULONG (WINAPI
*GetAdaptersAddresses_fn_t
)(
644 ULONG
, ULONG
, PVOID
, PIP_ADAPTER_ADDRESSES
, PULONG
);
648 evutil_check_ifaddrs(void)
650 #if defined(EVENT__HAVE_GETIFADDRS)
651 /* Most free Unixy systems provide getifaddrs, which gives us a linked list
652 * of struct ifaddrs. */
653 struct ifaddrs
*ifa
= NULL
;
654 const struct ifaddrs
*i
;
655 if (getifaddrs(&ifa
) < 0) {
656 event_warn("Unable to call getifaddrs()");
660 for (i
= ifa
; i
; i
= i
->ifa_next
) {
663 evutil_found_ifaddr(i
->ifa_addr
);
668 #elif defined(_WIN32)
669 /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
670 "GetAdaptersInfo", but that's deprecated; let's just try
671 GetAdaptersAddresses and fall back to connect+getsockname.
673 HMODULE lib
= evutil_load_windows_system_library_(TEXT("ihplapi.dll"));
674 GetAdaptersAddresses_fn_t fn
;
676 IP_ADAPTER_ADDRESSES
*addresses
= NULL
, *address
;
679 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
680 GAA_FLAG_SKIP_MULTICAST | \
681 GAA_FLAG_SKIP_DNS_SERVER)
686 if (!(fn
= (GetAdaptersAddresses_fn_t
) GetProcAddress(lib
, "GetAdaptersAddresses")))
689 /* Guess how much space we need. */
691 addresses
= mm_malloc(size
);
694 res
= fn(AF_UNSPEC
, FLAGS
, NULL
, addresses
, &size
);
695 if (res
== ERROR_BUFFER_OVERFLOW
) {
696 /* we didn't guess that we needed enough space; try again */
698 addresses
= mm_malloc(size
);
701 res
= fn(AF_UNSPEC
, FLAGS
, NULL
, addresses
, &size
);
706 for (address
= addresses
; address
; address
= address
->Next
) {
707 IP_ADAPTER_UNICAST_ADDRESS
*a
;
708 for (a
= address
->FirstUnicastAddress
; a
; a
= a
->Next
) {
709 /* Yes, it's a linked list inside a linked list */
710 struct sockaddr
*sa
= a
->Address
.lpSockaddr
;
711 evutil_found_ifaddr(sa
);
727 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
728 * the test seemed successful. */
730 evutil_check_interfaces(int force_recheck
)
732 evutil_socket_t fd
= -1;
733 struct sockaddr_in sin
, sin_out
;
734 struct sockaddr_in6 sin6
, sin6_out
;
735 ev_socklen_t sin_out_len
= sizeof(sin_out
);
736 ev_socklen_t sin6_out_len
= sizeof(sin6_out
);
738 if (have_checked_interfaces
&& !force_recheck
)
741 if (evutil_check_ifaddrs() == 0) {
742 /* Use a nice sane interface, if this system has one. */
746 /* Ugh. There was no nice sane interface. So to check whether we have
747 * an interface open for a given protocol, will try to make a UDP
748 * 'connection' to a remote host on the internet. We don't actually
749 * use it, so the address doesn't matter, but we want to pick one that
750 * keep us from using a host- or link-local interface. */
751 memset(&sin
, 0, sizeof(sin
));
752 sin
.sin_family
= AF_INET
;
753 sin
.sin_port
= htons(53);
754 r
= evutil_inet_pton(AF_INET
, "18.244.0.188", &sin
.sin_addr
);
757 memset(&sin6
, 0, sizeof(sin6
));
758 sin6
.sin6_family
= AF_INET6
;
759 sin6
.sin6_port
= htons(53);
760 r
= evutil_inet_pton(AF_INET6
, "2001:4860:b002::68", &sin6
.sin6_addr
);
763 memset(&sin_out
, 0, sizeof(sin_out
));
764 memset(&sin6_out
, 0, sizeof(sin6_out
));
766 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
767 if ((fd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
)) >= 0 &&
768 connect(fd
, (struct sockaddr
*)&sin
, sizeof(sin
)) == 0 &&
769 getsockname(fd
, (struct sockaddr
*)&sin_out
, &sin_out_len
) == 0) {
770 /* We might have an IPv4 interface. */
771 evutil_found_ifaddr((struct sockaddr
*) &sin_out
);
774 evutil_closesocket(fd
);
776 if ((fd
= socket(AF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
)) >= 0 &&
777 connect(fd
, (struct sockaddr
*)&sin6
, sizeof(sin6
)) == 0 &&
778 getsockname(fd
, (struct sockaddr
*)&sin6_out
, &sin6_out_len
) == 0) {
779 /* We might have an IPv6 interface. */
780 evutil_found_ifaddr((struct sockaddr
*) &sin6_out
);
784 evutil_closesocket(fd
);
789 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
790 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
791 * it, and we should trust what they said.
793 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
795 /* Helper: construct a new addrinfo containing the socket address in
796 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
797 * socktype and protocol info from hints. If they weren't set, then
798 * allocate both a TCP and a UDP addrinfo.
800 struct evutil_addrinfo
*
801 evutil_new_addrinfo_(struct sockaddr
*sa
, ev_socklen_t socklen
,
802 const struct evutil_addrinfo
*hints
)
804 struct evutil_addrinfo
*res
;
805 EVUTIL_ASSERT(hints
);
807 if (hints
->ai_socktype
== 0 && hints
->ai_protocol
== 0) {
808 /* Indecisive user! Give them a UDP and a TCP. */
809 struct evutil_addrinfo
*r1
, *r2
;
810 struct evutil_addrinfo tmp
;
811 memcpy(&tmp
, hints
, sizeof(tmp
));
812 tmp
.ai_socktype
= SOCK_STREAM
; tmp
.ai_protocol
= IPPROTO_TCP
;
813 r1
= evutil_new_addrinfo_(sa
, socklen
, &tmp
);
816 tmp
.ai_socktype
= SOCK_DGRAM
; tmp
.ai_protocol
= IPPROTO_UDP
;
817 r2
= evutil_new_addrinfo_(sa
, socklen
, &tmp
);
819 evutil_freeaddrinfo(r1
);
826 /* We're going to allocate extra space to hold the sockaddr. */
827 res
= mm_calloc(1,sizeof(struct evutil_addrinfo
)+socklen
);
830 res
->ai_addr
= (struct sockaddr
*)
831 (((char*)res
) + sizeof(struct evutil_addrinfo
));
832 memcpy(res
->ai_addr
, sa
, socklen
);
833 res
->ai_addrlen
= socklen
;
834 res
->ai_family
= sa
->sa_family
; /* Same or not? XXX */
835 res
->ai_flags
= EVUTIL_AI_LIBEVENT_ALLOCATED
;
836 res
->ai_socktype
= hints
->ai_socktype
;
837 res
->ai_protocol
= hints
->ai_protocol
;
842 /* Append the addrinfo 'append' to the end of 'first', and return the start of
843 * the list. Either element can be NULL, in which case we return the element
844 * that is not NULL. */
845 struct evutil_addrinfo
*
846 evutil_addrinfo_append_(struct evutil_addrinfo
*first
,
847 struct evutil_addrinfo
*append
)
849 struct evutil_addrinfo
*ai
= first
;
854 ai
->ai_next
= append
;
860 parse_numeric_servname(const char *servname
)
864 n
= (int) strtol(servname
, &endptr
, 10);
865 if (n
>=0 && n
<= 65535 && servname
[0] && endptr
&& !endptr
[0])
871 /** Parse a service name in 'servname', which can be a decimal port.
872 * Return the port number, or -1 on error.
875 evutil_parse_servname(const char *servname
, const char *protocol
,
876 const struct evutil_addrinfo
*hints
)
878 int n
= parse_numeric_servname(servname
);
881 #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
882 if (!(hints
->ai_flags
& EVUTIL_AI_NUMERICSERV
)) {
883 struct servent
*ent
= getservbyname(servname
, protocol
);
885 return ntohs(ent
->s_port
);
892 /* Return a string corresponding to a protocol number that we can pass to
895 evutil_unparse_protoname(int proto
)
909 #ifdef EVENT__HAVE_GETPROTOBYNUMBER
911 struct protoent
*ent
= getprotobynumber(proto
);
921 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo
*hints
)
923 /* If we can guess the protocol from the socktype, do so. */
924 if (!hints
->ai_protocol
&& hints
->ai_socktype
) {
925 if (hints
->ai_socktype
== SOCK_DGRAM
)
926 hints
->ai_protocol
= IPPROTO_UDP
;
927 else if (hints
->ai_socktype
== SOCK_STREAM
)
928 hints
->ai_protocol
= IPPROTO_TCP
;
931 /* Set the socktype if it isn't set. */
932 if (!hints
->ai_socktype
&& hints
->ai_protocol
) {
933 if (hints
->ai_protocol
== IPPROTO_UDP
)
934 hints
->ai_socktype
= SOCK_DGRAM
;
935 else if (hints
->ai_protocol
== IPPROTO_TCP
)
936 hints
->ai_socktype
= SOCK_STREAM
;
938 else if (hints
->ai_protocol
== IPPROTO_SCTP
)
939 hints
->ai_socktype
= SOCK_STREAM
;
944 #if AF_UNSPEC != PF_UNSPEC
945 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
948 /** Implements the part of looking up hosts by name that's common to both
949 * the blocking and nonblocking resolver:
950 * - Adjust 'hints' to have a reasonable socktype and protocol.
951 * - Look up the port based on 'servname', and store it in *portnum,
952 * - Handle the nodename==NULL case
953 * - Handle some invalid arguments cases.
954 * - Handle the cases where nodename is an IPv4 or IPv6 address.
956 * If we need the resolver to look up the hostname, we return
957 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
958 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
959 * set *res as getaddrinfo would.
962 evutil_getaddrinfo_common_(const char *nodename
, const char *servname
,
963 struct evutil_addrinfo
*hints
, struct evutil_addrinfo
**res
, int *portnum
)
968 if (nodename
== NULL
&& servname
== NULL
)
969 return EVUTIL_EAI_NONAME
;
971 /* We only understand 3 families */
972 if (hints
->ai_family
!= PF_UNSPEC
&& hints
->ai_family
!= PF_INET
&&
973 hints
->ai_family
!= PF_INET6
)
974 return EVUTIL_EAI_FAMILY
;
976 evutil_getaddrinfo_infer_protocols(hints
);
978 /* Look up the port number and protocol, if possible. */
979 pname
= evutil_unparse_protoname(hints
->ai_protocol
);
981 /* XXXX We could look at the protocol we got back from
982 * getservbyname, but it doesn't seem too useful. */
983 port
= evutil_parse_servname(servname
, pname
, hints
);
985 return EVUTIL_EAI_NONAME
;
989 /* If we have no node name, then we're supposed to bind to 'any' and
990 * connect to localhost. */
991 if (nodename
== NULL
) {
992 struct evutil_addrinfo
*res4
=NULL
, *res6
=NULL
;
993 if (hints
->ai_family
!= PF_INET
) { /* INET6 or UNSPEC. */
994 struct sockaddr_in6 sin6
;
995 memset(&sin6
, 0, sizeof(sin6
));
996 sin6
.sin6_family
= AF_INET6
;
997 sin6
.sin6_port
= htons(port
);
998 if (hints
->ai_flags
& EVUTIL_AI_PASSIVE
) {
1001 /* connect to ::1 */
1002 sin6
.sin6_addr
.s6_addr
[15] = 1;
1004 res6
= evutil_new_addrinfo_((struct sockaddr
*)&sin6
,
1005 sizeof(sin6
), hints
);
1007 return EVUTIL_EAI_MEMORY
;
1010 if (hints
->ai_family
!= PF_INET6
) { /* INET or UNSPEC */
1011 struct sockaddr_in sin
;
1012 memset(&sin
, 0, sizeof(sin
));
1013 sin
.sin_family
= AF_INET
;
1014 sin
.sin_port
= htons(port
);
1015 if (hints
->ai_flags
& EVUTIL_AI_PASSIVE
) {
1016 /* Bind to 0.0.0.0 */
1018 /* connect to 127.0.0.1 */
1019 sin
.sin_addr
.s_addr
= htonl(0x7f000001);
1021 res4
= evutil_new_addrinfo_((struct sockaddr
*)&sin
,
1022 sizeof(sin
), hints
);
1025 evutil_freeaddrinfo(res6
);
1026 return EVUTIL_EAI_MEMORY
;
1029 *res
= evutil_addrinfo_append_(res4
, res6
);
1033 /* If we can, we should try to parse the hostname without resolving
1036 if (hints
->ai_family
== PF_INET6
|| hints
->ai_family
== PF_UNSPEC
) {
1037 struct sockaddr_in6 sin6
;
1038 memset(&sin6
, 0, sizeof(sin6
));
1039 if (1==evutil_inet_pton(AF_INET6
, nodename
, &sin6
.sin6_addr
)) {
1040 /* Got an ipv6 address. */
1041 sin6
.sin6_family
= AF_INET6
;
1042 sin6
.sin6_port
= htons(port
);
1043 *res
= evutil_new_addrinfo_((struct sockaddr
*)&sin6
,
1044 sizeof(sin6
), hints
);
1046 return EVUTIL_EAI_MEMORY
;
1052 if (hints
->ai_family
== PF_INET
|| hints
->ai_family
== PF_UNSPEC
) {
1053 struct sockaddr_in sin
;
1054 memset(&sin
, 0, sizeof(sin
));
1055 if (1==evutil_inet_pton(AF_INET
, nodename
, &sin
.sin_addr
)) {
1056 /* Got an ipv6 address. */
1057 sin
.sin_family
= AF_INET
;
1058 sin
.sin_port
= htons(port
);
1059 *res
= evutil_new_addrinfo_((struct sockaddr
*)&sin
,
1060 sizeof(sin
), hints
);
1062 return EVUTIL_EAI_MEMORY
;
1068 /* If we have reached this point, we definitely need to do a DNS
1070 if ((hints
->ai_flags
& EVUTIL_AI_NUMERICHOST
)) {
1071 /* If we're not allowed to do one, then say so. */
1072 return EVUTIL_EAI_NONAME
;
1075 return EVUTIL_EAI_NEED_RESOLVE
;
1078 #ifdef EVENT__HAVE_GETADDRINFO
1079 #define USE_NATIVE_GETADDRINFO
1082 #ifdef USE_NATIVE_GETADDRINFO
1083 /* A mask of all the flags that we declare, so we can clear them before calling
1084 * the native getaddrinfo */
1085 static const unsigned int ALL_NONNATIVE_AI_FLAGS
=
1089 #ifndef AI_CANONNAME
1090 EVUTIL_AI_CANONNAME
|
1092 #ifndef AI_NUMERICHOST
1093 EVUTIL_AI_NUMERICHOST
|
1095 #ifndef AI_NUMERICSERV
1096 EVUTIL_AI_NUMERICSERV
|
1098 #ifndef AI_ADDRCONFIG
1099 EVUTIL_AI_ADDRCONFIG
|
1105 EVUTIL_AI_V4MAPPED
|
1107 EVUTIL_AI_LIBEVENT_ALLOCATED
;
1109 static const unsigned int ALL_NATIVE_AI_FLAGS
=
1116 #ifdef AI_NUMERICHOST
1119 #ifdef AI_NUMERICSERV
1122 #ifdef AI_ADDRCONFIG
1134 #ifndef USE_NATIVE_GETADDRINFO
1135 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1138 static struct evutil_addrinfo
*
1139 addrinfo_from_hostent(const struct hostent
*ent
,
1140 int port
, const struct evutil_addrinfo
*hints
)
1143 struct sockaddr_in sin
;
1144 struct sockaddr_in6 sin6
;
1145 struct sockaddr
*sa
;
1147 struct evutil_addrinfo
*res
=NULL
, *ai
;
1150 if (ent
->h_addrtype
== PF_INET
) {
1151 memset(&sin
, 0, sizeof(sin
));
1152 sin
.sin_family
= AF_INET
;
1153 sin
.sin_port
= htons(port
);
1154 sa
= (struct sockaddr
*)&sin
;
1155 socklen
= sizeof(struct sockaddr_in
);
1156 addrp
= &sin
.sin_addr
;
1157 if (ent
->h_length
!= sizeof(sin
.sin_addr
)) {
1158 event_warnx("Weird h_length from gethostbyname");
1161 } else if (ent
->h_addrtype
== PF_INET6
) {
1162 memset(&sin6
, 0, sizeof(sin6
));
1163 sin6
.sin6_family
= AF_INET6
;
1164 sin6
.sin6_port
= htons(port
);
1165 sa
= (struct sockaddr
*)&sin6
;
1166 socklen
= sizeof(struct sockaddr_in6
);
1167 addrp
= &sin6
.sin6_addr
;
1168 if (ent
->h_length
!= sizeof(sin6
.sin6_addr
)) {
1169 event_warnx("Weird h_length from gethostbyname");
1175 for (i
= 0; ent
->h_addr_list
[i
]; ++i
) {
1176 memcpy(addrp
, ent
->h_addr_list
[i
], ent
->h_length
);
1177 ai
= evutil_new_addrinfo_(sa
, socklen
, hints
);
1179 evutil_freeaddrinfo(res
);
1182 res
= evutil_addrinfo_append_(res
, ai
);
1185 if (res
&& ((hints
->ai_flags
& EVUTIL_AI_CANONNAME
) && ent
->h_name
)) {
1186 res
->ai_canonname
= mm_strdup(ent
->h_name
);
1187 if (res
->ai_canonname
== NULL
) {
1188 evutil_freeaddrinfo(res
);
1197 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1198 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1199 * that we'll only get addresses we could maybe connect to.
1202 evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo
*hints
)
1204 if (!(hints
->ai_flags
& EVUTIL_AI_ADDRCONFIG
))
1206 if (hints
->ai_family
!= PF_UNSPEC
)
1208 if (!have_checked_interfaces
)
1209 evutil_check_interfaces(0);
1210 if (had_ipv4_address
&& !had_ipv6_address
) {
1211 hints
->ai_family
= PF_INET
;
1212 } else if (!had_ipv4_address
&& had_ipv6_address
) {
1213 hints
->ai_family
= PF_INET6
;
1217 #ifdef USE_NATIVE_GETADDRINFO
1218 static int need_numeric_port_hack_
=0;
1219 static int need_socktype_protocol_hack_
=0;
1220 static int tested_for_getaddrinfo_hacks
=0;
1222 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1223 giving a numeric port without giving an ai_socktype was verboten.
1224 We test for this so we can apply an appropriate workaround. If it
1225 turns out that the bug is present, then:
1227 - If nodename==NULL and servname is numeric, we build an answer
1228 ourselves using evutil_getaddrinfo_common_().
1230 - If nodename!=NULL and servname is numeric, then we set
1231 servname=NULL when calling getaddrinfo, and post-process the
1232 result to set the ports on it.
1234 We test for this bug at runtime, since otherwise we can't have the
1235 same binary run on multiple BSD versions.
1237 - Some versions of Solaris believe that it's nice to leave to protocol
1238 field set to 0. We test for this so we can apply an appropriate
1242 test_for_getaddrinfo_hacks(void)
1245 struct evutil_addrinfo
*ai
=NULL
, *ai2
=NULL
;
1246 struct evutil_addrinfo hints
;
1248 memset(&hints
,0,sizeof(hints
));
1249 hints
.ai_family
= PF_UNSPEC
;
1251 #ifdef AI_NUMERICHOST
1254 #ifdef AI_NUMERICSERV
1258 r
= getaddrinfo("1.2.3.4", "80", &hints
, &ai
);
1259 hints
.ai_socktype
= SOCK_STREAM
;
1260 r2
= getaddrinfo("1.2.3.4", "80", &hints
, &ai2
);
1261 if (r2
== 0 && r
!= 0) {
1262 need_numeric_port_hack_
=1;
1264 if (ai2
&& ai2
->ai_protocol
== 0) {
1265 need_socktype_protocol_hack_
=1;
1272 tested_for_getaddrinfo_hacks
=1;
1276 need_numeric_port_hack(void)
1278 if (!tested_for_getaddrinfo_hacks
)
1279 test_for_getaddrinfo_hacks();
1280 return need_numeric_port_hack_
;
1284 need_socktype_protocol_hack(void)
1286 if (!tested_for_getaddrinfo_hacks
)
1287 test_for_getaddrinfo_hacks();
1288 return need_socktype_protocol_hack_
;
1292 apply_numeric_port_hack(int port
, struct evutil_addrinfo
**ai
)
1294 /* Now we run through the list and set the ports on all of the
1295 * results where ports would make sense. */
1296 for ( ; *ai
; ai
= &(*ai
)->ai_next
) {
1297 struct sockaddr
*sa
= (*ai
)->ai_addr
;
1298 if (sa
&& sa
->sa_family
== AF_INET
) {
1299 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
1300 sin
->sin_port
= htons(port
);
1301 } else if (sa
&& sa
->sa_family
== AF_INET6
) {
1302 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
1303 sin6
->sin6_port
= htons(port
);
1305 /* A numeric port makes no sense here; remove this one
1307 struct evutil_addrinfo
*victim
= *ai
;
1308 *ai
= victim
->ai_next
;
1309 victim
->ai_next
= NULL
;
1310 freeaddrinfo(victim
);
1316 apply_socktype_protocol_hack(struct evutil_addrinfo
*ai
)
1318 struct evutil_addrinfo
*ai_new
;
1319 for (; ai
; ai
= ai
->ai_next
) {
1320 evutil_getaddrinfo_infer_protocols(ai
);
1321 if (ai
->ai_socktype
|| ai
->ai_protocol
)
1323 ai_new
= mm_malloc(sizeof(*ai_new
));
1326 memcpy(ai_new
, ai
, sizeof(*ai_new
));
1327 ai
->ai_socktype
= SOCK_STREAM
;
1328 ai
->ai_protocol
= IPPROTO_TCP
;
1329 ai_new
->ai_socktype
= SOCK_DGRAM
;
1330 ai_new
->ai_protocol
= IPPROTO_UDP
;
1332 ai_new
->ai_next
= ai
->ai_next
;
1333 ai
->ai_next
= ai_new
;
1340 evutil_getaddrinfo(const char *nodename
, const char *servname
,
1341 const struct evutil_addrinfo
*hints_in
, struct evutil_addrinfo
**res
)
1343 #ifdef USE_NATIVE_GETADDRINFO
1344 struct evutil_addrinfo hints
;
1345 int portnum
=-1, need_np_hack
, err
;
1348 memcpy(&hints
, hints_in
, sizeof(hints
));
1350 memset(&hints
, 0, sizeof(hints
));
1351 hints
.ai_family
= PF_UNSPEC
;
1354 #ifndef AI_ADDRCONFIG
1355 /* Not every system has AI_ADDRCONFIG, so fake it. */
1356 if (hints
.ai_family
== PF_UNSPEC
&&
1357 (hints
.ai_flags
& EVUTIL_AI_ADDRCONFIG
)) {
1358 evutil_adjust_hints_for_addrconfig_(&hints
);
1362 #ifndef AI_NUMERICSERV
1363 /* Not every system has AI_NUMERICSERV, so fake it. */
1364 if (hints
.ai_flags
& EVUTIL_AI_NUMERICSERV
) {
1365 if (servname
&& parse_numeric_servname(servname
)<0)
1366 return EVUTIL_EAI_NONAME
;
1370 /* Enough operating systems handle enough common non-resolve
1371 * cases here weirdly enough that we are better off just
1372 * overriding them. For example:
1374 * - Windows doesn't like to infer the protocol from the
1375 * socket type, or fill in socket or protocol types much at
1376 * all. It also seems to do its own broken implicit
1377 * always-on version of AI_ADDRCONFIG that keeps it from
1378 * ever resolving even a literal IPv6 address when
1379 * ai_addrtype is PF_UNSPEC.
1384 err
= evutil_getaddrinfo_common_(nodename
,servname
,&hints
,
1387 err
== EVUTIL_EAI_MEMORY
||
1388 err
== EVUTIL_EAI_NONAME
)
1390 /* If we make it here, the system getaddrinfo can
1391 * have a crack at it. */
1395 /* See documentation for need_numeric_port_hack above.*/
1396 need_np_hack
= need_numeric_port_hack() && servname
&& !hints
.ai_socktype
1397 && ((portnum
=parse_numeric_servname(servname
)) >= 0);
1400 return evutil_getaddrinfo_common_(
1401 NULL
,servname
,&hints
, res
, &portnum
);
1405 if (need_socktype_protocol_hack()) {
1406 evutil_getaddrinfo_infer_protocols(&hints
);
1409 /* Make sure that we didn't actually steal any AI_FLAGS values that
1410 * the system is using. (This is a constant expression, and should ge
1413 * XXXX Turn this into a compile-time failure rather than a run-time
1416 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS
& ALL_NATIVE_AI_FLAGS
) == 0);
1418 /* Clear any flags that only libevent understands. */
1419 hints
.ai_flags
&= ~ALL_NONNATIVE_AI_FLAGS
;
1421 err
= getaddrinfo(nodename
, servname
, &hints
, res
);
1423 apply_numeric_port_hack(portnum
, res
);
1425 if (need_socktype_protocol_hack()) {
1426 if (apply_socktype_protocol_hack(*res
) < 0) {
1427 evutil_freeaddrinfo(*res
);
1429 return EVUTIL_EAI_MEMORY
;
1435 struct hostent
*ent
= NULL
;
1436 struct evutil_addrinfo hints
;
1439 memcpy(&hints
, hints_in
, sizeof(hints
));
1441 memset(&hints
, 0, sizeof(hints
));
1442 hints
.ai_family
= PF_UNSPEC
;
1445 evutil_adjust_hints_for_addrconfig_(&hints
);
1447 err
= evutil_getaddrinfo_common_(nodename
, servname
, &hints
, res
, &port
);
1448 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
1449 /* We either succeeded or failed. No need to continue */
1454 /* Use any of the various gethostbyname_r variants as available. */
1456 #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1457 /* This one is what glibc provides. */
1459 struct hostent hostent
;
1461 r
= gethostbyname_r(nodename
, &hostent
, buf
, sizeof(buf
), &ent
,
1463 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1465 struct hostent hostent
;
1466 ent
= gethostbyname_r(nodename
, &hostent
, buf
, sizeof(buf
),
1468 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1469 struct hostent_data data
;
1470 struct hostent hostent
;
1471 memset(&data
, 0, sizeof(data
));
1472 err
= gethostbyname_r(nodename
, &hostent
, &data
);
1473 ent
= err
? NULL
: &hostent
;
1475 /* fall back to gethostbyname. */
1476 /* XXXX This needs a lock everywhere but Windows. */
1477 ent
= gethostbyname(nodename
);
1479 err
= WSAGetLastError();
1485 /* Now we have either ent or err set. */
1487 /* XXX is this right for windows ? */
1490 return EVUTIL_EAI_AGAIN
;
1493 return EVUTIL_EAI_FAIL
;
1494 case HOST_NOT_FOUND
:
1495 return EVUTIL_EAI_NONAME
;
1497 #if NO_DATA != NO_ADDRESS
1500 return EVUTIL_EAI_NODATA
;
1504 if (ent
->h_addrtype
!= hints
.ai_family
&&
1505 hints
.ai_family
!= PF_UNSPEC
) {
1506 /* This wasn't the type we were hoping for. Too bad
1507 * we never had a chance to ask gethostbyname for what
1509 return EVUTIL_EAI_NONAME
;
1512 /* Make sure we got _some_ answers. */
1513 if (ent
->h_length
== 0)
1514 return EVUTIL_EAI_NODATA
;
1516 /* If we got an address type we don't know how to make a
1517 sockaddr for, give up. */
1518 if (ent
->h_addrtype
!= PF_INET
&& ent
->h_addrtype
!= PF_INET6
)
1519 return EVUTIL_EAI_FAMILY
;
1521 *res
= addrinfo_from_hostent(ent
, port
, &hints
);
1523 return EVUTIL_EAI_MEMORY
;
1531 evutil_freeaddrinfo(struct evutil_addrinfo
*ai
)
1533 #ifdef EVENT__HAVE_GETADDRINFO
1534 if (!(ai
->ai_flags
& EVUTIL_AI_LIBEVENT_ALLOCATED
)) {
1540 struct evutil_addrinfo
*next
= ai
->ai_next
;
1541 if (ai
->ai_canonname
)
1542 mm_free(ai
->ai_canonname
);
1548 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl
= NULL
;
1551 evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn
)
1553 if (!evdns_getaddrinfo_impl
)
1554 evdns_getaddrinfo_impl
= fn
;
1557 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1558 * otherwise do a blocking resolve and pass the result to the callback in the
1559 * way that evdns_getaddrinfo would.
1562 evutil_getaddrinfo_async_(struct evdns_base
*dns_base
,
1563 const char *nodename
, const char *servname
,
1564 const struct evutil_addrinfo
*hints_in
,
1565 void (*cb
)(int, struct evutil_addrinfo
*, void *), void *arg
)
1567 if (dns_base
&& evdns_getaddrinfo_impl
) {
1568 evdns_getaddrinfo_impl(
1569 dns_base
, nodename
, servname
, hints_in
, cb
, arg
);
1571 struct evutil_addrinfo
*ai
=NULL
;
1573 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &ai
);
1580 evutil_gai_strerror(int err
)
1582 /* As a sneaky side-benefit, this case statement will get most
1583 * compilers to tell us if any of the error codes we defined
1584 * conflict with the platform's native error codes. */
1586 case EVUTIL_EAI_CANCEL
:
1587 return "Request canceled";
1591 case EVUTIL_EAI_ADDRFAMILY
:
1592 return "address family for nodename not supported";
1593 case EVUTIL_EAI_AGAIN
:
1594 return "temporary failure in name resolution";
1595 case EVUTIL_EAI_BADFLAGS
:
1596 return "invalid value for ai_flags";
1597 case EVUTIL_EAI_FAIL
:
1598 return "non-recoverable failure in name resolution";
1599 case EVUTIL_EAI_FAMILY
:
1600 return "ai_family not supported";
1601 case EVUTIL_EAI_MEMORY
:
1602 return "memory allocation failure";
1603 case EVUTIL_EAI_NODATA
:
1604 return "no address associated with nodename";
1605 case EVUTIL_EAI_NONAME
:
1606 return "nodename nor servname provided, or not known";
1607 case EVUTIL_EAI_SERVICE
:
1608 return "servname not supported for ai_socktype";
1609 case EVUTIL_EAI_SOCKTYPE
:
1610 return "ai_socktype not supported";
1611 case EVUTIL_EAI_SYSTEM
:
1612 return "system error";
1614 #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1615 return gai_strerrorA(err
);
1616 #elif defined(USE_NATIVE_GETADDRINFO)
1617 return gai_strerror(err
);
1619 return "Unknown error code";
1625 /* destructively remove a trailing line terminator from s */
1630 if (s
&& (len
= strlen (s
)) > 0 && s
[len
- 1] == '\n') {
1632 if (len
> 0 && s
[len
- 1] == '\r')
1637 /* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1638 * is supposed to return a string which is good indefinitely without having
1639 * to be freed. To make this work without leaking memory, we cache the
1640 * string the first time FormatMessage is called on a particular error
1641 * code, and then return the cached string on subsequent calls with the
1642 * same code. The strings aren't freed until libevent_global_shutdown
1643 * (or never). We use a linked list to cache the errors, because we
1644 * only expect there to be a few dozen, and that should be fast enough.
1647 struct cached_sock_errs_entry
{
1648 HT_ENTRY(cached_sock_errs_entry
) node
;
1650 char *msg
; /* allocated with LocalAlloc; free with LocalFree */
1653 static inline unsigned
1654 hash_cached_sock_errs(const struct cached_sock_errs_entry
*e
)
1656 /* Use Murmur3's 32-bit finalizer as an integer hash function */
1667 eq_cached_sock_errs(const struct cached_sock_errs_entry
*a
,
1668 const struct cached_sock_errs_entry
*b
)
1670 return a
->code
== b
->code
;
1673 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1674 static void *windows_socket_errors_lock_
= NULL
;
1677 static HT_HEAD(cached_sock_errs_map
, cached_sock_errs_entry
)
1678 windows_socket_errors
= HT_INITIALIZER();
1680 HT_PROTOTYPE(cached_sock_errs_map
,
1681 cached_sock_errs_entry
,
1683 hash_cached_sock_errs
,
1684 eq_cached_sock_errs
);
1686 HT_GENERATE(cached_sock_errs_map
,
1687 cached_sock_errs_entry
,
1689 hash_cached_sock_errs
,
1690 eq_cached_sock_errs
,
1696 /** Equivalent to strerror, but for windows socket errors. */
1698 evutil_socket_error_to_string(int errcode
)
1700 struct cached_sock_errs_entry
*errs
, *newerr
, find
;
1703 EVLOCK_LOCK(windows_socket_errors_lock_
, 0);
1705 find
.code
= errcode
;
1706 errs
= HT_FIND(cached_sock_errs_map
, &windows_socket_errors
, &find
);
1712 if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM
|
1713 FORMAT_MESSAGE_IGNORE_INSERTS
|
1714 FORMAT_MESSAGE_ALLOCATE_BUFFER
,
1715 NULL
, errcode
, 0, (char *)&msg
, 0, NULL
))
1716 chomp (msg
); /* because message has trailing newline */
1719 /* use LocalAlloc because FormatMessage does */
1720 msg
= LocalAlloc(LMEM_FIXED
, len
);
1722 msg
= (char *)"LocalAlloc failed during Winsock error";
1725 evutil_snprintf(msg
, len
, "winsock error 0x%08x", errcode
);
1728 newerr
= (struct cached_sock_errs_entry
*)
1729 mm_malloc(sizeof (struct cached_sock_errs_entry
));
1733 msg
= (char *)"malloc failed during Winsock error";
1737 newerr
->code
= errcode
;
1739 HT_INSERT(cached_sock_errs_map
, &windows_socket_errors
, newerr
);
1742 EVLOCK_UNLOCK(windows_socket_errors_lock_
, 0);
1747 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1749 evutil_global_setup_locks_(const int enable_locks
)
1751 EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_
, 0);
1757 evutil_free_sock_err_globals(void)
1759 struct cached_sock_errs_entry
**errs
, *tofree
;
1761 for (errs
= HT_START(cached_sock_errs_map
, &windows_socket_errors
)
1764 errs
= HT_NEXT_RMV(cached_sock_errs_map
,
1765 &windows_socket_errors
,
1767 LocalFree(tofree
->msg
);
1771 HT_CLEAR(cached_sock_errs_map
, &windows_socket_errors
);
1773 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1774 if (windows_socket_errors_lock_
!= NULL
) {
1775 EVTHREAD_FREE_LOCK(windows_socket_errors_lock_
, 0);
1776 windows_socket_errors_lock_
= NULL
;
1783 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1785 evutil_global_setup_locks_(const int enable_locks
)
1792 evutil_free_sock_err_globals(void)
1799 evutil_snprintf(char *buf
, size_t buflen
, const char *format
, ...)
1803 va_start(ap
, format
);
1804 r
= evutil_vsnprintf(buf
, buflen
, format
, ap
);
1810 evutil_vsnprintf(char *buf
, size_t buflen
, const char *format
, va_list ap
)
1815 #if defined(_MSC_VER) || defined(_WIN32)
1816 r
= _vsnprintf(buf
, buflen
, format
, ap
);
1818 r
= _vscprintf(format
, ap
);
1820 /* Make sure we always use the correct vsnprintf on IRIX */
1821 extern int _xpg5_vsnprintf(char * __restrict
,
1822 __SGI_LIBC_NAMESPACE_QUALIFIER
size_t,
1823 const char * __restrict
, /* va_list */ char *);
1825 r
= _xpg5_vsnprintf(buf
, buflen
, format
, ap
);
1827 r
= vsnprintf(buf
, buflen
, format
, ap
);
1829 buf
[buflen
-1] = '\0';
1833 #define USE_INTERNAL_NTOP
1834 #define USE_INTERNAL_PTON
1837 evutil_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1839 #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1840 return inet_ntop(af
, src
, dst
, len
);
1842 if (af
== AF_INET
) {
1843 const struct in_addr
*in
= src
;
1844 const ev_uint32_t a
= ntohl(in
->s_addr
);
1846 r
= evutil_snprintf(dst
, len
, "%d.%d.%d.%d",
1847 (int)(ev_uint8_t
)((a
>>24)&0xff),
1848 (int)(ev_uint8_t
)((a
>>16)&0xff),
1849 (int)(ev_uint8_t
)((a
>>8 )&0xff),
1850 (int)(ev_uint8_t
)((a
)&0xff));
1851 if (r
<0||(size_t)r
>=len
)
1856 } else if (af
== AF_INET6
) {
1857 const struct in6_addr
*addr
= src
;
1859 int longestGapLen
= 0, longestGapPos
= -1, i
,
1860 curGapPos
= -1, curGapLen
= 0;
1861 ev_uint16_t words
[8];
1862 for (i
= 0; i
< 8; ++i
) {
1864 (((ev_uint16_t
)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1866 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1867 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1868 (words
[5] == 0xffff))) {
1869 /* This is an IPv4 address. */
1870 if (words
[5] == 0) {
1871 evutil_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1872 addr
->s6_addr
[12], addr
->s6_addr
[13],
1873 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1875 evutil_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1876 addr
->s6_addr
[12], addr
->s6_addr
[13],
1877 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1879 if (strlen(buf
) > len
)
1881 strlcpy(dst
, buf
, len
);
1886 if (words
[i
] == 0) {
1889 while (i
<8 && words
[i
] == 0) {
1892 if (curGapLen
> longestGapLen
) {
1893 longestGapPos
= curGapPos
;
1894 longestGapLen
= curGapLen
;
1900 if (longestGapLen
<=1)
1904 for (i
= 0; i
< 8; ++i
) {
1905 if (words
[i
] == 0 && longestGapPos
== i
) {
1909 while (i
< 8 && words
[i
] == 0)
1911 --i
; /* to compensate for loop increment. */
1914 sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1921 if (strlen(buf
) > len
)
1923 strlcpy(dst
, buf
, len
);
1933 evutil_inet_pton(int af
, const char *src
, void *dst
)
1935 #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1936 return inet_pton(af
, src
, dst
);
1938 if (af
== AF_INET
) {
1941 struct in_addr
*addr
= dst
;
1942 if (sscanf(src
, "%u.%u.%u.%u%c", &a
,&b
,&c
,&d
,&more
) != 4)
1944 if (a
> 255) return 0;
1945 if (b
> 255) return 0;
1946 if (c
> 255) return 0;
1947 if (d
> 255) return 0;
1948 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1951 } else if (af
== AF_INET6
) {
1952 struct in6_addr
*out
= dst
;
1953 ev_uint16_t words
[8];
1954 int gapPos
= -1, i
, setWords
=0;
1955 const char *dot
= strchr(src
, '.');
1956 const char *eow
; /* end of words. */
1960 eow
= src
+strlen(src
);
1962 unsigned byte1
,byte2
,byte3
,byte4
;
1964 for (eow
= dot
-1; eow
>= src
&& EVUTIL_ISDIGIT_(*eow
); --eow
)
1968 /* We use "scanf" because some platform inet_aton()s are too lax
1969 * about IPv4 addresses of the form "1.2.3" */
1970 if (sscanf(eow
, "%u.%u.%u.%u%c",
1971 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1980 words
[6] = (byte1
<<8) | byte2
;
1981 words
[7] = (byte3
<<8) | byte4
;
1989 if (EVUTIL_ISXDIGIT_(*src
)) {
1991 long r
= strtol(src
, &next
, 16);
1999 words
[i
++] = (ev_uint16_t
)r
;
2002 if (*src
!= ':' && src
!= eow
)
2005 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
2008 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
2017 (setWords
== 8 && gapPos
!= -1) ||
2018 (setWords
< 8 && gapPos
== -1))
2022 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
2023 int gapLen
= 8 - setWords
;
2024 /* assert(nToMove >= 0); */
2026 return -1; /* should be impossible */
2027 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
2028 sizeof(ev_uint16_t
)*nToMove
);
2029 memset(&words
[gapPos
], 0, sizeof(ev_uint16_t
)*gapLen
);
2031 for (i
= 0; i
< 8; ++i
) {
2032 out
->s6_addr
[2*i
] = words
[i
] >> 8;
2033 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
2045 evutil_parse_sockaddr_port(const char *ip_as_string
, struct sockaddr
*out
, int *outlen
)
2049 const char *cp
, *addr_part
, *port_part
;
2051 /* recognized formats are:
2059 cp
= strchr(ip_as_string
, ':');
2060 if (*ip_as_string
== '[') {
2062 if (!(cp
= strchr(ip_as_string
, ']'))) {
2065 len
= (int) ( cp
-(ip_as_string
+ 1) );
2066 if (len
> (int)sizeof(buf
)-1) {
2069 memcpy(buf
, ip_as_string
+1, len
);
2077 } else if (cp
&& strchr(cp
+1, ':')) {
2079 addr_part
= ip_as_string
;
2083 if (cp
- ip_as_string
> (int)sizeof(buf
)-1) {
2086 memcpy(buf
, ip_as_string
, cp
-ip_as_string
);
2087 buf
[cp
-ip_as_string
] = '\0';
2091 addr_part
= ip_as_string
;
2096 if (port_part
== NULL
) {
2099 port
= atoi(port_part
);
2100 if (port
<= 0 || port
> 65535) {
2106 return -1; /* Should be impossible. */
2110 struct sockaddr_in6 sin6
;
2111 memset(&sin6
, 0, sizeof(sin6
));
2112 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2113 sin6
.sin6_len
= sizeof(sin6
);
2115 sin6
.sin6_family
= AF_INET6
;
2116 sin6
.sin6_port
= htons(port
);
2117 if (1 != evutil_inet_pton(AF_INET6
, addr_part
, &sin6
.sin6_addr
))
2119 if ((int)sizeof(sin6
) > *outlen
)
2121 memset(out
, 0, *outlen
);
2122 memcpy(out
, &sin6
, sizeof(sin6
));
2123 *outlen
= sizeof(sin6
);
2129 struct sockaddr_in sin
;
2130 memset(&sin
, 0, sizeof(sin
));
2131 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2132 sin
.sin_len
= sizeof(sin
);
2134 sin
.sin_family
= AF_INET
;
2135 sin
.sin_port
= htons(port
);
2136 if (1 != evutil_inet_pton(AF_INET
, addr_part
, &sin
.sin_addr
))
2138 if ((int)sizeof(sin
) > *outlen
)
2140 memset(out
, 0, *outlen
);
2141 memcpy(out
, &sin
, sizeof(sin
));
2142 *outlen
= sizeof(sin
);
2148 evutil_format_sockaddr_port_(const struct sockaddr
*sa
, char *out
, size_t outlen
)
2151 const char *res
=NULL
;
2153 if (sa
->sa_family
== AF_INET
) {
2154 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)sa
;
2155 res
= evutil_inet_ntop(AF_INET
, &sin
->sin_addr
,b
,sizeof(b
));
2156 port
= ntohs(sin
->sin_port
);
2158 evutil_snprintf(out
, outlen
, "%s:%d", b
, port
);
2161 } else if (sa
->sa_family
== AF_INET6
) {
2162 const struct sockaddr_in6
*sin6
= (const struct sockaddr_in6
*)sa
;
2163 res
= evutil_inet_ntop(AF_INET6
, &sin6
->sin6_addr
,b
,sizeof(b
));
2164 port
= ntohs(sin6
->sin6_port
);
2166 evutil_snprintf(out
, outlen
, "[%s]:%d", b
, port
);
2171 evutil_snprintf(out
, outlen
, "<addr with socktype %d>",
2172 (int)sa
->sa_family
);
2177 evutil_sockaddr_cmp(const struct sockaddr
*sa1
, const struct sockaddr
*sa2
,
2181 if (0 != (r
= (sa1
->sa_family
- sa2
->sa_family
)))
2184 if (sa1
->sa_family
== AF_INET
) {
2185 const struct sockaddr_in
*sin1
, *sin2
;
2186 sin1
= (const struct sockaddr_in
*)sa1
;
2187 sin2
= (const struct sockaddr_in
*)sa2
;
2188 if (sin1
->sin_addr
.s_addr
< sin2
->sin_addr
.s_addr
)
2190 else if (sin1
->sin_addr
.s_addr
> sin2
->sin_addr
.s_addr
)
2192 else if (include_port
&&
2193 (r
= ((int)sin1
->sin_port
- (int)sin2
->sin_port
)))
2199 else if (sa1
->sa_family
== AF_INET6
) {
2200 const struct sockaddr_in6
*sin1
, *sin2
;
2201 sin1
= (const struct sockaddr_in6
*)sa1
;
2202 sin2
= (const struct sockaddr_in6
*)sa2
;
2203 if ((r
= memcmp(sin1
->sin6_addr
.s6_addr
, sin2
->sin6_addr
.s6_addr
, 16)))
2205 else if (include_port
&&
2206 (r
= ((int)sin1
->sin6_port
- (int)sin2
->sin6_port
)))
2215 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
2216 * has 256 bits to look up whether a character is in some set or not. This
2217 * fails on non-ASCII platforms, but so does every other place where we
2218 * take a char and write it onto the network.
2220 static const ev_uint32_t EVUTIL_ISALPHA_TABLE
[8] =
2221 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2222 static const ev_uint32_t EVUTIL_ISALNUM_TABLE
[8] =
2223 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2224 static const ev_uint32_t EVUTIL_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2225 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE
[8] =
2226 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2227 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2228 static const ev_uint32_t EVUTIL_ISPRINT_TABLE
[8] =
2229 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2230 static const ev_uint32_t EVUTIL_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2231 static const ev_uint32_t EVUTIL_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2232 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
2234 static const unsigned char EVUTIL_TOUPPER_TABLE
[256] = {
2235 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2236 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2237 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2238 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2239 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2240 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2241 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2242 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2243 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2244 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2245 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2246 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2247 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2248 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2249 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2250 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2252 static const unsigned char EVUTIL_TOLOWER_TABLE
[256] = {
2253 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2254 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2255 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2256 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2257 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2258 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2259 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2260 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2261 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2262 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2263 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2264 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2265 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2266 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2267 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2268 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2271 #define IMPL_CTYPE_FN(name) \
2272 int EVUTIL_##name##_(char c) { \
2274 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
2276 IMPL_CTYPE_FN(ISALPHA
)
2277 IMPL_CTYPE_FN(ISALNUM
)
2278 IMPL_CTYPE_FN(ISSPACE
)
2279 IMPL_CTYPE_FN(ISDIGIT
)
2280 IMPL_CTYPE_FN(ISXDIGIT
)
2281 IMPL_CTYPE_FN(ISPRINT
)
2282 IMPL_CTYPE_FN(ISLOWER
)
2283 IMPL_CTYPE_FN(ISUPPER
)
2285 char EVUTIL_TOLOWER_(char c
)
2287 return ((char)EVUTIL_TOLOWER_TABLE
[(ev_uint8_t
)c
]);
2289 char EVUTIL_TOUPPER_(char c
)
2291 return ((char)EVUTIL_TOUPPER_TABLE
[(ev_uint8_t
)c
]);
2294 evutil_ascii_strcasecmp(const char *s1
, const char *s2
)
2298 c1
= EVUTIL_TOLOWER_(*s1
++);
2299 c2
= EVUTIL_TOLOWER_(*s2
++);
2308 int evutil_ascii_strncasecmp(const char *s1
, const char *s2
, size_t n
)
2312 c1
= EVUTIL_TOLOWER_(*s1
++);
2313 c2
= EVUTIL_TOLOWER_(*s2
++);
2325 evutil_rtrim_lws_(char *str
)
2332 if ((cp
= strchr(str
, '\0')) == NULL
|| (cp
== str
))
2337 while (*cp
== ' ' || *cp
== '\t') {
2346 evutil_issetugid(void)
2348 #ifdef EVENT__HAVE_ISSETUGID
2352 #ifdef EVENT__HAVE_GETEUID
2353 if (getuid() != geteuid())
2356 #ifdef EVENT__HAVE_GETEGID
2357 if (getgid() != getegid())
2365 evutil_getenv_(const char *varname
)
2367 if (evutil_issetugid())
2370 return getenv(varname
);
2374 evutil_weakrand_seed_(struct evutil_weakrand_state
*state
, ev_uint32_t seed
)
2378 evutil_gettimeofday(&tv
, NULL
);
2379 seed
= (ev_uint32_t
)tv
.tv_sec
+ (ev_uint32_t
)tv
.tv_usec
;
2381 seed
+= (ev_uint32_t
) _getpid();
2383 seed
+= (ev_uint32_t
) getpid();
2391 evutil_weakrand_(struct evutil_weakrand_state
*state
)
2393 /* This RNG implementation is a linear congruential generator, with
2394 * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
2395 * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2397 * The linear congruential generator is not an industrial-strength
2398 * RNG! It's fast, but it can have higher-order patterns. Notably,
2399 * the low bits tend to have periodicity.
2401 state
->seed
= ((state
->seed
) * 1103515245 + 12345) & 0x7fffffff;
2402 return (ev_int32_t
)(state
->seed
);
2406 evutil_weakrand_range_(struct evutil_weakrand_state
*state
, ev_int32_t top
)
2408 ev_int32_t divisor
, result
;
2410 /* We can't just do weakrand() % top, since the low bits of the LCG
2411 * are less random than the high ones. (Specifically, since the LCG
2412 * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2413 * therefore the low m bits of the LCG will have period 2^m.) */
2414 divisor
= EVUTIL_WEAKRAND_MAX
/ top
;
2416 result
= evutil_weakrand_(state
) / divisor
;
2417 } while (result
>= top
);
2422 * Volatile pointer to memset: we use this to keep the compiler from
2423 * eliminating our call to memset.
2425 void * (*volatile evutil_memset_volatile_
)(void *, int, size_t) = memset
;
2428 evutil_memclear_(void *mem
, size_t len
)
2430 evutil_memset_volatile_(mem
, 0, len
);
2434 evutil_sockaddr_is_loopback_(const struct sockaddr
*addr
)
2436 static const char LOOPBACK_S6
[16] =
2437 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2438 if (addr
->sa_family
== AF_INET
) {
2439 struct sockaddr_in
*sin
= (struct sockaddr_in
*)addr
;
2440 return (ntohl(sin
->sin_addr
.s_addr
) & 0xff000000) == 0x7f000000;
2441 } else if (addr
->sa_family
== AF_INET6
) {
2442 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)addr
;
2443 return !memcmp(sin6
->sin6_addr
.s6_addr
, LOOPBACK_S6
, 16);
2449 evutil_hex_char_to_int_(char c
)
2463 case 'A': case 'a': return 10;
2464 case 'B': case 'b': return 11;
2465 case 'C': case 'c': return 12;
2466 case 'D': case 'd': return 13;
2467 case 'E': case 'e': return 14;
2468 case 'F': case 'f': return 15;
2475 evutil_load_windows_system_library_(const TCHAR
*library_name
)
2477 TCHAR path
[MAX_PATH
];
2479 n
= GetSystemDirectory(path
, MAX_PATH
);
2480 if (n
== 0 || n
+ _tcslen(library_name
) + 2 >= MAX_PATH
)
2482 _tcscat(path
, TEXT("\\"));
2483 _tcscat(path
, library_name
);
2484 return LoadLibrary(path
);
2488 /* Internal wrapper around 'socket' to provide Linux-style support for
2489 * syscall-saving methods where available.
2491 * In addition to regular socket behavior, you can use a bitwise or to set the
2492 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2493 * to make the socket nonblocking or close-on-exec with as few syscalls as
2497 evutil_socket_(int domain
, int type
, int protocol
)
2500 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2501 r
= socket(domain
, type
, protocol
);
2504 else if ((type
& (SOCK_NONBLOCK
|SOCK_CLOEXEC
)) == 0)
2507 #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2508 r
= socket(domain
, type
& SOCKET_TYPE_MASK
, protocol
);
2511 if (type
& EVUTIL_SOCK_NONBLOCK
) {
2512 if (evutil_fast_socket_nonblocking(r
) < 0) {
2513 evutil_closesocket(r
);
2517 if (type
& EVUTIL_SOCK_CLOEXEC
) {
2518 if (evutil_fast_socket_closeonexec(r
) < 0) {
2519 evutil_closesocket(r
);
2526 /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2527 * support for syscall-saving methods where available.
2529 * In addition to regular accept behavior, you can set one or more of flags
2530 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2531 * make the socket nonblocking or close-on-exec with as few syscalls as
2535 evutil_accept4_(evutil_socket_t sockfd
, struct sockaddr
*addr
,
2536 ev_socklen_t
*addrlen
, int flags
)
2538 evutil_socket_t result
;
2539 #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2540 result
= accept4(sockfd
, addr
, addrlen
, flags
);
2541 if (result
>= 0 || (errno
!= EINVAL
&& errno
!= ENOSYS
)) {
2542 /* A nonnegative result means that we succeeded, so return.
2543 * Failing with EINVAL means that an option wasn't supported,
2544 * and failing with ENOSYS means that the syscall wasn't
2545 * there: in those cases we want to fall back. Otherwise, we
2546 * got a real error, and we should return. */
2550 result
= accept(sockfd
, addr
, addrlen
);
2554 if (flags
& EVUTIL_SOCK_CLOEXEC
) {
2555 if (evutil_fast_socket_closeonexec(result
) < 0) {
2556 evutil_closesocket(result
);
2560 if (flags
& EVUTIL_SOCK_NONBLOCK
) {
2561 if (evutil_fast_socket_nonblocking(result
) < 0) {
2562 evutil_closesocket(result
);
2569 /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2570 * fd[0] get read from fd[1]. Make both fds nonblocking and close-on-exec.
2571 * Return 0 on success, -1 on failure.
2574 evutil_make_internal_pipe_(evutil_socket_t fd
[2])
2577 Making the second socket nonblocking is a bit subtle, given that we
2578 ignore any EAGAIN returns when writing to it, and you don't usally
2579 do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2580 then there's no need to add any more data to the buffer, since
2581 the main thread is already either about to wake up and drain it,
2582 or woken up and in the process of draining it.
2585 #if defined(EVENT__HAVE_PIPE2)
2586 if (pipe2(fd
, O_NONBLOCK
|O_CLOEXEC
) == 0)
2589 #if defined(EVENT__HAVE_PIPE)
2590 if (pipe(fd
) == 0) {
2591 if (evutil_fast_socket_nonblocking(fd
[0]) < 0 ||
2592 evutil_fast_socket_nonblocking(fd
[1]) < 0 ||
2593 evutil_fast_socket_closeonexec(fd
[0]) < 0 ||
2594 evutil_fast_socket_closeonexec(fd
[1]) < 0) {
2602 event_warn("%s: pipe", __func__
);
2607 #define LOCAL_SOCKETPAIR_AF AF_INET
2609 #define LOCAL_SOCKETPAIR_AF AF_UNIX
2611 if (evutil_socketpair(LOCAL_SOCKETPAIR_AF
, SOCK_STREAM
, 0, fd
) == 0) {
2612 if (evutil_fast_socket_nonblocking(fd
[0]) < 0 ||
2613 evutil_fast_socket_nonblocking(fd
[1]) < 0 ||
2614 evutil_fast_socket_closeonexec(fd
[0]) < 0 ||
2615 evutil_fast_socket_closeonexec(fd
[1]) < 0) {
2616 evutil_closesocket(fd
[0]);
2617 evutil_closesocket(fd
[1]);
2627 /* Wrapper around eventfd on systems that provide it. Unlike the system
2628 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2629 * flags. Returns -1 on error or if eventfd is not supported.
2632 evutil_eventfd_(unsigned initval
, int flags
)
2634 #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
2636 #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
2637 r
= eventfd(initval
, flags
);
2638 if (r
>= 0 || flags
== 0)
2641 r
= eventfd(initval
, 0);
2644 if (flags
& EVUTIL_EFD_CLOEXEC
) {
2645 if (evutil_fast_socket_closeonexec(r
) < 0) {
2646 evutil_closesocket(r
);
2650 if (flags
& EVUTIL_EFD_NONBLOCK
) {
2651 if (evutil_fast_socket_nonblocking(r
) < 0) {
2652 evutil_closesocket(r
);
2663 evutil_free_globals_(void)
2665 evutil_free_secure_rng_globals_();
2666 evutil_free_sock_err_globals();