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"
34 #define WIN32_LEAN_AND_MEAN
36 #undef WIN32_LEAN_AND_MEAN
41 /* For structs needed by GetAdaptersAddresses */
42 #define _WIN32_WINNT 0x0501
46 #include <sys/types.h>
47 #ifdef EVENT__HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
50 #ifdef EVENT__HAVE_UNISTD_H
53 #ifdef EVENT__HAVE_FCNTL_H
56 #ifdef EVENT__HAVE_STDLIB_H
63 #ifdef EVENT__HAVE_NETINET_IN_H
64 #include <netinet/in.h>
66 #ifdef EVENT__HAVE_NETINET_IN6_H
67 #include <netinet/in6.h>
69 #ifdef EVENT__HAVE_NETINET_TCP_H
70 #include <netinet/tcp.h>
72 #ifdef EVENT__HAVE_ARPA_INET_H
73 #include <arpa/inet.h>
77 #ifdef EVENT__HAVE_IFADDRS_H
81 #include "event2/util.h"
82 #include "util-internal.h"
83 #include "log-internal.h"
84 #include "mm-internal.h"
85 #include "evthread-internal.h"
87 #include "strlcpy-internal.h"
88 #include "ipv6-internal.h"
91 #define HT_NO_CACHE_HASH_VALUES
92 #include "ht-internal.h"
97 #define fstat _fstati64
100 #define stat _stati64
106 evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
111 fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
112 if (fd >= 0 || errno == EINVAL)
114 /* If we got an EINVAL, fall through and try without O_CLOEXEC */
116 fd = open(pathname, flags, (mode_t)mode);
120 #if defined(FD_CLOEXEC)
121 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
131 Read the contents of 'filename' into a newly allocated NUL-terminated
132 string. Set *content_out to hold this string, and *len_out to hold its
133 length (not including the appended NUL). If 'is_binary', open the file in
136 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
138 Used internally only; may go away in a future version.
141 evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
147 size_t read_so_far=0;
150 EVUTIL_ASSERT(content_out);
151 EVUTIL_ASSERT(len_out);
160 fd = evutil_open_closeonexec_(filename, mode, 0);
163 if (fstat(fd, &st) || st.st_size < 0 ||
164 st.st_size > EV_SSIZE_MAX-1 ) {
168 mem = mm_malloc((size_t)st.st_size + 1);
175 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
177 #define N_TO_READ(x) (x)
179 while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
181 if (read_so_far >= (size_t)st.st_size)
183 EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
190 mem[read_so_far] = 0;
192 *len_out = read_so_far;
198 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
201 return socketpair(family, type, protocol, fd);
203 return evutil_ersatz_socketpair_(family, type, protocol, fd);
208 evutil_ersatz_socketpair_(int family, int type, int protocol,
209 evutil_socket_t fd[2])
211 /* This code is originally from Tor. Used with permission. */
213 /* This socketpair does not work when localhost is down. So
214 * it's really not the same thing at all. But it's close enough
215 * for now, and really, when localhost is down sometimes, we
216 * have other problems too.
219 #define ERR(e) WSA##e
223 evutil_socket_t listener = -1;
224 evutil_socket_t connector = -1;
225 evutil_socket_t acceptor = -1;
226 struct sockaddr_in listen_addr;
227 struct sockaddr_in connect_addr;
229 int saved_errno = -1;
232 family_test = family != AF_INET;
234 family_test = family_test && (family != AF_UNIX);
236 if (protocol || family_test) {
237 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
242 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
246 listener = socket(AF_INET, type, 0);
249 memset(&listen_addr, 0, sizeof(listen_addr));
250 listen_addr.sin_family = AF_INET;
251 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
252 listen_addr.sin_port = 0; /* kernel chooses port. */
253 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
255 goto tidy_up_and_fail;
256 if (listen(listener, 1) == -1)
257 goto tidy_up_and_fail;
259 connector = socket(AF_INET, type, 0);
261 goto tidy_up_and_fail;
263 memset(&connect_addr, 0, sizeof(connect_addr));
265 /* We want to find out the port number to connect to. */
266 size = sizeof(connect_addr);
267 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
268 goto tidy_up_and_fail;
269 if (size != sizeof (connect_addr))
270 goto abort_tidy_up_and_fail;
271 if (connect(connector, (struct sockaddr *) &connect_addr,
272 sizeof(connect_addr)) == -1)
273 goto tidy_up_and_fail;
275 size = sizeof(listen_addr);
276 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
278 goto tidy_up_and_fail;
279 if (size != sizeof(listen_addr))
280 goto abort_tidy_up_and_fail;
281 /* Now check we are talking to ourself by matching port and host on the
283 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
284 goto tidy_up_and_fail;
285 if (size != sizeof (connect_addr)
286 || listen_addr.sin_family != connect_addr.sin_family
287 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
288 || listen_addr.sin_port != connect_addr.sin_port)
289 goto abort_tidy_up_and_fail;
290 evutil_closesocket(listener);
296 abort_tidy_up_and_fail:
297 saved_errno = ERR(ECONNABORTED);
300 saved_errno = EVUTIL_SOCKET_ERROR();
302 evutil_closesocket(listener);
304 evutil_closesocket(connector);
306 evutil_closesocket(acceptor);
308 EVUTIL_SET_SOCKET_ERROR(saved_errno);
314 evutil_make_socket_nonblocking(evutil_socket_t fd)
318 unsigned long nonblocking = 1;
319 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
320 event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
327 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
328 event_warn("fcntl(%d, F_GETFL)", fd);
331 if (!(flags & O_NONBLOCK)) {
332 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
333 event_warn("fcntl(%d, F_SETFL)", fd);
342 /* Faster version of evutil_make_socket_nonblocking for internal use.
344 * Requires that no F_SETFL flags were previously set on the fd.
347 evutil_fast_socket_nonblocking(evutil_socket_t fd)
350 return evutil_make_socket_nonblocking(fd);
352 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
353 event_warn("fcntl(%d, F_SETFL)", fd);
361 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
363 #if defined(SO_REUSEADDR) && !defined(_WIN32)
365 /* REUSEADDR on Unix means, "don't hang on to this address after the
366 * listener is closed." On Windows, though, it means "don't keep other
367 * processes from binding to this address while we're using it. */
368 return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
369 (ev_socklen_t)sizeof(one));
376 evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
378 #if defined __linux__ && defined(SO_REUSEPORT)
380 /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
381 * threads) can bind to the same port if they each set the option. */
382 return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
383 (ev_socklen_t)sizeof(one));
390 evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
392 #if defined(IPV6_V6ONLY)
394 return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
395 (ev_socklen_t)sizeof(one));
401 evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
403 #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
406 /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
407 * has arrived and ready to read */
408 return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
409 (ev_socklen_t)sizeof(one));
415 evutil_make_socket_closeonexec(evutil_socket_t fd)
417 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
419 if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
420 event_warn("fcntl(%d, F_GETFD)", fd);
423 if (!(flags & FD_CLOEXEC)) {
424 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
425 event_warn("fcntl(%d, F_SETFD)", fd);
433 /* Faster version of evutil_make_socket_closeonexec for internal use.
435 * Requires that no F_SETFD flags were previously set on the fd.
438 evutil_fast_socket_closeonexec(evutil_socket_t fd)
440 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
441 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
442 event_warn("fcntl(%d, F_SETFD)", fd);
450 evutil_closesocket(evutil_socket_t sock)
455 return closesocket(sock);
460 evutil_strtoll(const char *s, char **endptr, int base)
462 #ifdef EVENT__HAVE_STRTOLL
463 return (ev_int64_t)strtoll(s, endptr, base);
464 #elif EVENT__SIZEOF_LONG == 8
465 return (ev_int64_t)strtol(s, endptr, base);
466 #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
467 /* XXXX on old versions of MS APIs, we only support base
472 r = (ev_int64_t) _atoi64(s);
482 #elif defined(_WIN32)
483 return (ev_int64_t) _strtoi64(s, endptr, base);
484 #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
487 if (base != 10 && base != 16)
490 n = sscanf(s, "%lld", &r);
492 unsigned long long ru=0;
493 n = sscanf(s, "%llx", &ru);
494 if (ru > EV_INT64_MAX)
500 while (EVUTIL_ISSPACE_(*s))
505 while (EVUTIL_ISDIGIT_(*s))
508 while (EVUTIL_ISXDIGIT_(*s))
515 #error "I don't know how to parse 64-bit integers."
521 evutil_socket_geterror(evutil_socket_t sock)
523 int optval, optvallen=sizeof(optval);
524 int err = WSAGetLastError();
525 if (err == WSAEWOULDBLOCK && sock >= 0) {
526 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
536 /* XXX we should use an enum here. */
537 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
539 evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
544 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
547 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
552 if (connect(*fd_ptr, sa, socklen) < 0) {
553 int e = evutil_socket_geterror(*fd_ptr);
554 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
556 if (EVUTIL_ERR_CONNECT_REFUSED(e))
565 evutil_closesocket(*fd_ptr);
571 /* Check whether a socket on which we called connect() is done
572 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
573 error case, set the current socket errno to the error that happened during
574 the connect operation. */
576 evutil_socket_finished_connecting_(evutil_socket_t fd)
579 ev_socklen_t elen = sizeof(e);
581 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
585 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
587 EVUTIL_SET_SOCKET_ERROR(e);
594 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
595 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
596 EVUTIL_AI_ADDRCONFIG) != \
597 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
598 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
599 EVUTIL_AI_ADDRCONFIG)
600 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
603 /* We sometimes need to know whether we have an ipv4 address and whether we
604 have an ipv6 address. If 'have_checked_interfaces', then we've already done
605 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
606 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
607 set by evutil_check_interfaces. */
608 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
610 /* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
611 static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
612 { return addr>>24 == 127; }
614 /* True iff the IPv4 address 'addr', in host order, is link-local
615 * 169.254.0.0/16 (RFC3927) */
616 static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
617 { return ((addr & 0xffff0000U) == 0xa9fe0000U); }
619 /* True iff the IPv4 address 'addr', in host order, is a class D
620 * (multiclass) address. */
621 static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
622 { return ((addr>>24) & 0xf0) == 0xe0; }
625 evutil_v4addr_is_local_(const struct in_addr *in)
627 const ev_uint32_t addr = ntohl(in->s_addr);
628 return addr == INADDR_ANY ||
629 evutil_v4addr_is_localhost(addr) ||
630 evutil_v4addr_is_linklocal(addr) ||
631 evutil_v4addr_is_classd(addr);
634 evutil_v6addr_is_local_(const struct in6_addr *in)
636 static const char ZEROES[] =
637 "\x00\x00\x00\x00\x00\x00\x00\x00"
638 "\x00\x00\x00\x00\x00\x00\x00\x00";
640 const unsigned char *addr = (const unsigned char *)in->s6_addr;
641 return !memcmp(addr, ZEROES, 8) ||
642 ((addr[0] & 0xfe) == 0xfc) ||
643 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
644 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
649 evutil_found_ifaddr(const struct sockaddr *sa)
651 if (sa->sa_family == AF_INET) {
652 const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
653 if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
654 event_debug(("Detected an IPv4 interface"));
655 had_ipv4_address = 1;
657 } else if (sa->sa_family == AF_INET6) {
658 const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
659 if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
660 event_debug(("Detected an IPv6 interface"));
661 had_ipv6_address = 1;
667 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
668 ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
672 evutil_check_ifaddrs(void)
674 #if defined(EVENT__HAVE_GETIFADDRS)
675 /* Most free Unixy systems provide getifaddrs, which gives us a linked list
676 * of struct ifaddrs. */
677 struct ifaddrs *ifa = NULL;
678 const struct ifaddrs *i;
679 if (getifaddrs(&ifa) < 0) {
680 event_warn("Unable to call getifaddrs()");
684 for (i = ifa; i; i = i->ifa_next) {
687 evutil_found_ifaddr(i->ifa_addr);
692 #elif defined(_WIN32)
693 /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
694 "GetAdaptersInfo", but that's deprecated; let's just try
695 GetAdaptersAddresses and fall back to connect+getsockname.
697 HMODULE lib = evutil_load_windows_system_library_(TEXT("ihplapi.dll"));
698 GetAdaptersAddresses_fn_t fn;
700 IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
703 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
704 GAA_FLAG_SKIP_MULTICAST | \
705 GAA_FLAG_SKIP_DNS_SERVER)
710 if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
713 /* Guess how much space we need. */
715 addresses = mm_malloc(size);
718 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
719 if (res == ERROR_BUFFER_OVERFLOW) {
720 /* we didn't guess that we needed enough space; try again */
722 addresses = mm_malloc(size);
725 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
730 for (address = addresses; address; address = address->Next) {
731 IP_ADAPTER_UNICAST_ADDRESS *a;
732 for (a = address->FirstUnicastAddress; a; a = a->Next) {
733 /* Yes, it's a linked list inside a linked list */
734 struct sockaddr *sa = a->Address.lpSockaddr;
735 evutil_found_ifaddr(sa);
751 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
752 * the test seemed successful. */
754 evutil_check_interfaces(void)
756 evutil_socket_t fd = -1;
757 struct sockaddr_in sin, sin_out;
758 struct sockaddr_in6 sin6, sin6_out;
759 ev_socklen_t sin_out_len = sizeof(sin_out);
760 ev_socklen_t sin6_out_len = sizeof(sin6_out);
762 if (have_checked_interfaces)
765 /* From this point on we have done the ipv4/ipv6 interface check */
766 have_checked_interfaces = 1;
768 if (evutil_check_ifaddrs() == 0) {
769 /* Use a nice sane interface, if this system has one. */
773 /* Ugh. There was no nice sane interface. So to check whether we have
774 * an interface open for a given protocol, will try to make a UDP
775 * 'connection' to a remote host on the internet. We don't actually
776 * use it, so the address doesn't matter, but we want to pick one that
777 * keep us from using a host- or link-local interface. */
778 memset(&sin, 0, sizeof(sin));
779 sin.sin_family = AF_INET;
780 sin.sin_port = htons(53);
781 r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
784 memset(&sin6, 0, sizeof(sin6));
785 sin6.sin6_family = AF_INET6;
786 sin6.sin6_port = htons(53);
787 r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
790 memset(&sin_out, 0, sizeof(sin_out));
791 memset(&sin6_out, 0, sizeof(sin6_out));
793 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
794 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
795 connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
796 getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
797 /* We might have an IPv4 interface. */
798 evutil_found_ifaddr((struct sockaddr*) &sin_out);
801 evutil_closesocket(fd);
803 if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
804 connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
805 getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
806 /* We might have an IPv6 interface. */
807 evutil_found_ifaddr((struct sockaddr*) &sin6_out);
811 evutil_closesocket(fd);
816 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
817 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
818 * it, and we should trust what they said.
820 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
822 /* Helper: construct a new addrinfo containing the socket address in
823 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
824 * socktype and protocol info from hints. If they weren't set, then
825 * allocate both a TCP and a UDP addrinfo.
827 struct evutil_addrinfo *
828 evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
829 const struct evutil_addrinfo *hints)
831 struct evutil_addrinfo *res;
832 EVUTIL_ASSERT(hints);
834 if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
835 /* Indecisive user! Give them a UDP and a TCP. */
836 struct evutil_addrinfo *r1, *r2;
837 struct evutil_addrinfo tmp;
838 memcpy(&tmp, hints, sizeof(tmp));
839 tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
840 r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
843 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
844 r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
846 evutil_freeaddrinfo(r1);
853 /* We're going to allocate extra space to hold the sockaddr. */
854 res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
857 res->ai_addr = (struct sockaddr*)
858 (((char*)res) + sizeof(struct evutil_addrinfo));
859 memcpy(res->ai_addr, sa, socklen);
860 res->ai_addrlen = socklen;
861 res->ai_family = sa->sa_family; /* Same or not? XXX */
862 res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
863 res->ai_socktype = hints->ai_socktype;
864 res->ai_protocol = hints->ai_protocol;
869 /* Append the addrinfo 'append' to the end of 'first', and return the start of
870 * the list. Either element can be NULL, in which case we return the element
871 * that is not NULL. */
872 struct evutil_addrinfo *
873 evutil_addrinfo_append_(struct evutil_addrinfo *first,
874 struct evutil_addrinfo *append)
876 struct evutil_addrinfo *ai = first;
881 ai->ai_next = append;
887 parse_numeric_servname(const char *servname)
891 n = (int) strtol(servname, &endptr, 10);
892 if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
898 /** Parse a service name in 'servname', which can be a decimal port.
899 * Return the port number, or -1 on error.
902 evutil_parse_servname(const char *servname, const char *protocol,
903 const struct evutil_addrinfo *hints)
905 int n = parse_numeric_servname(servname);
908 #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
909 if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
910 struct servent *ent = getservbyname(servname, protocol);
912 return ntohs(ent->s_port);
919 /* Return a string corresponding to a protocol number that we can pass to
922 evutil_unparse_protoname(int proto)
936 #ifdef EVENT__HAVE_GETPROTOBYNUMBER
938 struct protoent *ent = getprotobynumber(proto);
948 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
950 /* If we can guess the protocol from the socktype, do so. */
951 if (!hints->ai_protocol && hints->ai_socktype) {
952 if (hints->ai_socktype == SOCK_DGRAM)
953 hints->ai_protocol = IPPROTO_UDP;
954 else if (hints->ai_socktype == SOCK_STREAM)
955 hints->ai_protocol = IPPROTO_TCP;
958 /* Set the socktype if it isn't set. */
959 if (!hints->ai_socktype && hints->ai_protocol) {
960 if (hints->ai_protocol == IPPROTO_UDP)
961 hints->ai_socktype = SOCK_DGRAM;
962 else if (hints->ai_protocol == IPPROTO_TCP)
963 hints->ai_socktype = SOCK_STREAM;
965 else if (hints->ai_protocol == IPPROTO_SCTP)
966 hints->ai_socktype = SOCK_STREAM;
971 #if AF_UNSPEC != PF_UNSPEC
972 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
975 /** Implements the part of looking up hosts by name that's common to both
976 * the blocking and nonblocking resolver:
977 * - Adjust 'hints' to have a reasonable socktype and protocol.
978 * - Look up the port based on 'servname', and store it in *portnum,
979 * - Handle the nodename==NULL case
980 * - Handle some invalid arguments cases.
981 * - Handle the cases where nodename is an IPv4 or IPv6 address.
983 * If we need the resolver to look up the hostname, we return
984 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
985 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
986 * set *res as getaddrinfo would.
989 evutil_getaddrinfo_common_(const char *nodename, const char *servname,
990 struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
995 if (nodename == NULL && servname == NULL)
996 return EVUTIL_EAI_NONAME;
998 /* We only understand 3 families */
999 if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
1000 hints->ai_family != PF_INET6)
1001 return EVUTIL_EAI_FAMILY;
1003 evutil_getaddrinfo_infer_protocols(hints);
1005 /* Look up the port number and protocol, if possible. */
1006 pname = evutil_unparse_protoname(hints->ai_protocol);
1008 /* XXXX We could look at the protocol we got back from
1009 * getservbyname, but it doesn't seem too useful. */
1010 port = evutil_parse_servname(servname, pname, hints);
1012 return EVUTIL_EAI_NONAME;
1016 /* If we have no node name, then we're supposed to bind to 'any' and
1017 * connect to localhost. */
1018 if (nodename == NULL) {
1019 struct evutil_addrinfo *res4=NULL, *res6=NULL;
1020 if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
1021 struct sockaddr_in6 sin6;
1022 memset(&sin6, 0, sizeof(sin6));
1023 sin6.sin6_family = AF_INET6;
1024 sin6.sin6_port = htons(port);
1025 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1028 /* connect to ::1 */
1029 sin6.sin6_addr.s6_addr[15] = 1;
1031 res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1032 sizeof(sin6), hints);
1034 return EVUTIL_EAI_MEMORY;
1037 if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
1038 struct sockaddr_in sin;
1039 memset(&sin, 0, sizeof(sin));
1040 sin.sin_family = AF_INET;
1041 sin.sin_port = htons(port);
1042 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1043 /* Bind to 0.0.0.0 */
1045 /* connect to 127.0.0.1 */
1046 sin.sin_addr.s_addr = htonl(0x7f000001);
1048 res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
1049 sizeof(sin), hints);
1052 evutil_freeaddrinfo(res6);
1053 return EVUTIL_EAI_MEMORY;
1056 *res = evutil_addrinfo_append_(res4, res6);
1060 /* If we can, we should try to parse the hostname without resolving
1063 if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
1064 struct sockaddr_in6 sin6;
1065 memset(&sin6, 0, sizeof(sin6));
1066 if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
1067 /* Got an ipv6 address. */
1068 sin6.sin6_family = AF_INET6;
1069 sin6.sin6_port = htons(port);
1070 *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1071 sizeof(sin6), hints);
1073 return EVUTIL_EAI_MEMORY;
1079 if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
1080 struct sockaddr_in sin;
1081 memset(&sin, 0, sizeof(sin));
1082 if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
1083 /* Got an ipv4 address. */
1084 sin.sin_family = AF_INET;
1085 sin.sin_port = htons(port);
1086 *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
1087 sizeof(sin), hints);
1089 return EVUTIL_EAI_MEMORY;
1095 /* If we have reached this point, we definitely need to do a DNS
1097 if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
1098 /* If we're not allowed to do one, then say so. */
1099 return EVUTIL_EAI_NONAME;
1102 return EVUTIL_EAI_NEED_RESOLVE;
1105 #ifdef EVENT__HAVE_GETADDRINFO
1106 #define USE_NATIVE_GETADDRINFO
1109 #ifdef USE_NATIVE_GETADDRINFO
1110 /* A mask of all the flags that we declare, so we can clear them before calling
1111 * the native getaddrinfo */
1112 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
1116 #ifndef AI_CANONNAME
1117 EVUTIL_AI_CANONNAME |
1119 #ifndef AI_NUMERICHOST
1120 EVUTIL_AI_NUMERICHOST |
1122 #ifndef AI_NUMERICSERV
1123 EVUTIL_AI_NUMERICSERV |
1125 #ifndef AI_ADDRCONFIG
1126 EVUTIL_AI_ADDRCONFIG |
1132 EVUTIL_AI_V4MAPPED |
1134 EVUTIL_AI_LIBEVENT_ALLOCATED;
1136 static const unsigned int ALL_NATIVE_AI_FLAGS =
1143 #ifdef AI_NUMERICHOST
1146 #ifdef AI_NUMERICSERV
1149 #ifdef AI_ADDRCONFIG
1161 #ifndef USE_NATIVE_GETADDRINFO
1162 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1165 static struct evutil_addrinfo *
1166 addrinfo_from_hostent(const struct hostent *ent,
1167 int port, const struct evutil_addrinfo *hints)
1170 struct sockaddr_in sin;
1171 struct sockaddr_in6 sin6;
1172 struct sockaddr *sa;
1174 struct evutil_addrinfo *res=NULL, *ai;
1177 if (ent->h_addrtype == PF_INET) {
1178 memset(&sin, 0, sizeof(sin));
1179 sin.sin_family = AF_INET;
1180 sin.sin_port = htons(port);
1181 sa = (struct sockaddr *)&sin;
1182 socklen = sizeof(struct sockaddr_in);
1183 addrp = &sin.sin_addr;
1184 if (ent->h_length != sizeof(sin.sin_addr)) {
1185 event_warnx("Weird h_length from gethostbyname");
1188 } else if (ent->h_addrtype == PF_INET6) {
1189 memset(&sin6, 0, sizeof(sin6));
1190 sin6.sin6_family = AF_INET6;
1191 sin6.sin6_port = htons(port);
1192 sa = (struct sockaddr *)&sin6;
1193 socklen = sizeof(struct sockaddr_in6);
1194 addrp = &sin6.sin6_addr;
1195 if (ent->h_length != sizeof(sin6.sin6_addr)) {
1196 event_warnx("Weird h_length from gethostbyname");
1202 for (i = 0; ent->h_addr_list[i]; ++i) {
1203 memcpy(addrp, ent->h_addr_list[i], ent->h_length);
1204 ai = evutil_new_addrinfo_(sa, socklen, hints);
1206 evutil_freeaddrinfo(res);
1209 res = evutil_addrinfo_append_(res, ai);
1212 if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1213 res->ai_canonname = mm_strdup(ent->h_name);
1214 if (res->ai_canonname == NULL) {
1215 evutil_freeaddrinfo(res);
1224 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1225 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1226 * that we'll only get addresses we could maybe connect to.
1229 evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
1231 if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1233 if (hints->ai_family != PF_UNSPEC)
1235 evutil_check_interfaces();
1236 if (had_ipv4_address && !had_ipv6_address) {
1237 hints->ai_family = PF_INET;
1238 } else if (!had_ipv4_address && had_ipv6_address) {
1239 hints->ai_family = PF_INET6;
1243 #ifdef USE_NATIVE_GETADDRINFO
1244 static int need_numeric_port_hack_=0;
1245 static int need_socktype_protocol_hack_=0;
1246 static int tested_for_getaddrinfo_hacks=0;
1248 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1249 giving a numeric port without giving an ai_socktype was verboten.
1250 We test for this so we can apply an appropriate workaround. If it
1251 turns out that the bug is present, then:
1253 - If nodename==NULL and servname is numeric, we build an answer
1254 ourselves using evutil_getaddrinfo_common_().
1256 - If nodename!=NULL and servname is numeric, then we set
1257 servname=NULL when calling getaddrinfo, and post-process the
1258 result to set the ports on it.
1260 We test for this bug at runtime, since otherwise we can't have the
1261 same binary run on multiple BSD versions.
1263 - Some versions of Solaris believe that it's nice to leave to protocol
1264 field set to 0. We test for this so we can apply an appropriate
1267 static struct evutil_addrinfo *ai_find_protocol(struct evutil_addrinfo *ai)
1270 if (ai->ai_protocol)
1277 test_for_getaddrinfo_hacks(void)
1280 struct evutil_addrinfo *ai=NULL, *ai2=NULL, *ai3=NULL;
1281 struct evutil_addrinfo hints;
1283 memset(&hints,0,sizeof(hints));
1284 hints.ai_family = PF_UNSPEC;
1286 #ifdef AI_NUMERICHOST
1289 #ifdef AI_NUMERICSERV
1293 r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1294 getaddrinfo("1.2.3.4", NULL, &hints, &ai3);
1295 hints.ai_socktype = SOCK_STREAM;
1296 r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1297 if (r2 == 0 && r != 0) {
1298 need_numeric_port_hack_=1;
1300 if (!ai_find_protocol(ai2) || !ai_find_protocol(ai3)) {
1301 need_socktype_protocol_hack_=1;
1310 tested_for_getaddrinfo_hacks=1;
1314 need_numeric_port_hack(void)
1316 if (!tested_for_getaddrinfo_hacks)
1317 test_for_getaddrinfo_hacks();
1318 return need_numeric_port_hack_;
1322 need_socktype_protocol_hack(void)
1324 if (!tested_for_getaddrinfo_hacks)
1325 test_for_getaddrinfo_hacks();
1326 return need_socktype_protocol_hack_;
1330 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1332 /* Now we run through the list and set the ports on all of the
1333 * results where ports would make sense. */
1334 for ( ; *ai; ai = &(*ai)->ai_next) {
1335 struct sockaddr *sa = (*ai)->ai_addr;
1336 if (sa && sa->sa_family == AF_INET) {
1337 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1338 sin->sin_port = htons(port);
1339 } else if (sa && sa->sa_family == AF_INET6) {
1340 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1341 sin6->sin6_port = htons(port);
1343 /* A numeric port makes no sense here; remove this one
1345 struct evutil_addrinfo *victim = *ai;
1346 *ai = victim->ai_next;
1347 victim->ai_next = NULL;
1348 freeaddrinfo(victim);
1354 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1356 struct evutil_addrinfo *ai_new;
1357 for (; ai; ai = ai->ai_next) {
1358 evutil_getaddrinfo_infer_protocols(ai);
1359 if (ai->ai_socktype || ai->ai_protocol)
1361 ai_new = mm_malloc(sizeof(*ai_new));
1364 memcpy(ai_new, ai, sizeof(*ai_new));
1365 ai->ai_socktype = SOCK_STREAM;
1366 ai->ai_protocol = IPPROTO_TCP;
1367 ai_new->ai_socktype = SOCK_DGRAM;
1368 ai_new->ai_protocol = IPPROTO_UDP;
1370 ai_new->ai_next = ai->ai_next;
1371 ai->ai_next = ai_new;
1378 evutil_getaddrinfo(const char *nodename, const char *servname,
1379 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1381 #ifdef USE_NATIVE_GETADDRINFO
1382 struct evutil_addrinfo hints;
1383 int portnum=-1, need_np_hack, err;
1386 memcpy(&hints, hints_in, sizeof(hints));
1388 memset(&hints, 0, sizeof(hints));
1389 hints.ai_family = PF_UNSPEC;
1392 #ifndef AI_ADDRCONFIG
1393 /* Not every system has AI_ADDRCONFIG, so fake it. */
1394 if (hints.ai_family == PF_UNSPEC &&
1395 (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1396 evutil_adjust_hints_for_addrconfig_(&hints);
1400 #ifndef AI_NUMERICSERV
1401 /* Not every system has AI_NUMERICSERV, so fake it. */
1402 if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1403 if (servname && parse_numeric_servname(servname)<0)
1404 return EVUTIL_EAI_NONAME;
1408 /* Enough operating systems handle enough common non-resolve
1409 * cases here weirdly enough that we are better off just
1410 * overriding them. For example:
1412 * - Windows doesn't like to infer the protocol from the
1413 * socket type, or fill in socket or protocol types much at
1414 * all. It also seems to do its own broken implicit
1415 * always-on version of AI_ADDRCONFIG that keeps it from
1416 * ever resolving even a literal IPv6 address when
1417 * ai_addrtype is PF_UNSPEC.
1422 err = evutil_getaddrinfo_common_(nodename,servname,&hints,
1425 err == EVUTIL_EAI_MEMORY ||
1426 err == EVUTIL_EAI_NONAME)
1428 /* If we make it here, the system getaddrinfo can
1429 * have a crack at it. */
1433 /* See documentation for need_numeric_port_hack above.*/
1434 need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1435 && ((portnum=parse_numeric_servname(servname)) >= 0);
1438 return evutil_getaddrinfo_common_(
1439 NULL,servname,&hints, res, &portnum);
1443 if (need_socktype_protocol_hack()) {
1444 evutil_getaddrinfo_infer_protocols(&hints);
1447 /* Make sure that we didn't actually steal any AI_FLAGS values that
1448 * the system is using. (This is a constant expression, and should ge
1451 * XXXX Turn this into a compile-time failure rather than a run-time
1454 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1456 /* Clear any flags that only libevent understands. */
1457 hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1459 err = getaddrinfo(nodename, servname, &hints, res);
1461 apply_numeric_port_hack(portnum, res);
1463 if (need_socktype_protocol_hack()) {
1464 if (apply_socktype_protocol_hack(*res) < 0) {
1465 evutil_freeaddrinfo(*res);
1467 return EVUTIL_EAI_MEMORY;
1473 struct hostent *ent = NULL;
1474 struct evutil_addrinfo hints;
1477 memcpy(&hints, hints_in, sizeof(hints));
1479 memset(&hints, 0, sizeof(hints));
1480 hints.ai_family = PF_UNSPEC;
1483 evutil_adjust_hints_for_addrconfig_(&hints);
1485 err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
1486 if (err != EVUTIL_EAI_NEED_RESOLVE) {
1487 /* We either succeeded or failed. No need to continue */
1492 /* Use any of the various gethostbyname_r variants as available. */
1494 #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1495 /* This one is what glibc provides. */
1497 struct hostent hostent;
1499 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1501 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1503 struct hostent hostent;
1504 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1506 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1507 struct hostent_data data;
1508 struct hostent hostent;
1509 memset(&data, 0, sizeof(data));
1510 err = gethostbyname_r(nodename, &hostent, &data);
1511 ent = err ? NULL : &hostent;
1513 /* fall back to gethostbyname. */
1514 /* XXXX This needs a lock everywhere but Windows. */
1515 ent = gethostbyname(nodename);
1517 err = WSAGetLastError();
1523 /* Now we have either ent or err set. */
1525 /* XXX is this right for windows ? */
1528 return EVUTIL_EAI_AGAIN;
1531 return EVUTIL_EAI_FAIL;
1532 case HOST_NOT_FOUND:
1533 return EVUTIL_EAI_NONAME;
1535 #if NO_DATA != NO_ADDRESS
1538 return EVUTIL_EAI_NODATA;
1542 if (ent->h_addrtype != hints.ai_family &&
1543 hints.ai_family != PF_UNSPEC) {
1544 /* This wasn't the type we were hoping for. Too bad
1545 * we never had a chance to ask gethostbyname for what
1547 return EVUTIL_EAI_NONAME;
1550 /* Make sure we got _some_ answers. */
1551 if (ent->h_length == 0)
1552 return EVUTIL_EAI_NODATA;
1554 /* If we got an address type we don't know how to make a
1555 sockaddr for, give up. */
1556 if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1557 return EVUTIL_EAI_FAMILY;
1559 *res = addrinfo_from_hostent(ent, port, &hints);
1561 return EVUTIL_EAI_MEMORY;
1569 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1571 #ifdef EVENT__HAVE_GETADDRINFO
1572 if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
1578 struct evutil_addrinfo *next = ai->ai_next;
1579 if (ai->ai_canonname)
1580 mm_free(ai->ai_canonname);
1586 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1587 static evdns_getaddrinfo_cancel_fn evdns_getaddrinfo_cancel_impl = NULL;
1590 evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
1592 if (!evdns_getaddrinfo_impl)
1593 evdns_getaddrinfo_impl = fn;
1596 evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn)
1598 if (!evdns_getaddrinfo_cancel_impl)
1599 evdns_getaddrinfo_cancel_impl = fn;
1602 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1603 * otherwise do a blocking resolve and pass the result to the callback in the
1604 * way that evdns_getaddrinfo would.
1606 struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
1607 struct evdns_base *dns_base,
1608 const char *nodename, const char *servname,
1609 const struct evutil_addrinfo *hints_in,
1610 void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1612 if (dns_base && evdns_getaddrinfo_impl) {
1613 return evdns_getaddrinfo_impl(
1614 dns_base, nodename, servname, hints_in, cb, arg);
1616 struct evutil_addrinfo *ai=NULL;
1618 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1624 void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data)
1626 if (evdns_getaddrinfo_cancel_impl && data) {
1627 evdns_getaddrinfo_cancel_impl(data);
1632 evutil_gai_strerror(int err)
1634 /* As a sneaky side-benefit, this case statement will get most
1635 * compilers to tell us if any of the error codes we defined
1636 * conflict with the platform's native error codes. */
1638 case EVUTIL_EAI_CANCEL:
1639 return "Request canceled";
1643 case EVUTIL_EAI_ADDRFAMILY:
1644 return "address family for nodename not supported";
1645 case EVUTIL_EAI_AGAIN:
1646 return "temporary failure in name resolution";
1647 case EVUTIL_EAI_BADFLAGS:
1648 return "invalid value for ai_flags";
1649 case EVUTIL_EAI_FAIL:
1650 return "non-recoverable failure in name resolution";
1651 case EVUTIL_EAI_FAMILY:
1652 return "ai_family not supported";
1653 case EVUTIL_EAI_MEMORY:
1654 return "memory allocation failure";
1655 case EVUTIL_EAI_NODATA:
1656 return "no address associated with nodename";
1657 case EVUTIL_EAI_NONAME:
1658 return "nodename nor servname provided, or not known";
1659 case EVUTIL_EAI_SERVICE:
1660 return "servname not supported for ai_socktype";
1661 case EVUTIL_EAI_SOCKTYPE:
1662 return "ai_socktype not supported";
1663 case EVUTIL_EAI_SYSTEM:
1664 return "system error";
1666 #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1667 return gai_strerrorA(err);
1668 #elif defined(USE_NATIVE_GETADDRINFO)
1669 return gai_strerror(err);
1671 return "Unknown error code";
1677 /* destructively remove a trailing line terminator from s */
1682 if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
1684 if (len > 0 && s[len - 1] == '\r')
1689 /* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1690 * is supposed to return a string which is good indefinitely without having
1691 * to be freed. To make this work without leaking memory, we cache the
1692 * string the first time FormatMessage is called on a particular error
1693 * code, and then return the cached string on subsequent calls with the
1694 * same code. The strings aren't freed until libevent_global_shutdown
1695 * (or never). We use a linked list to cache the errors, because we
1696 * only expect there to be a few dozen, and that should be fast enough.
1699 struct cached_sock_errs_entry {
1700 HT_ENTRY(cached_sock_errs_entry) node;
1702 char *msg; /* allocated with LocalAlloc; free with LocalFree */
1705 static inline unsigned
1706 hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
1708 /* Use Murmur3's 32-bit finalizer as an integer hash function */
1719 eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
1720 const struct cached_sock_errs_entry *b)
1722 return a->code == b->code;
1725 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1726 static void *windows_socket_errors_lock_ = NULL;
1729 static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
1730 windows_socket_errors = HT_INITIALIZER();
1732 HT_PROTOTYPE(cached_sock_errs_map,
1733 cached_sock_errs_entry,
1735 hash_cached_sock_errs,
1736 eq_cached_sock_errs);
1738 HT_GENERATE(cached_sock_errs_map,
1739 cached_sock_errs_entry,
1741 hash_cached_sock_errs,
1742 eq_cached_sock_errs,
1748 /** Equivalent to strerror, but for windows socket errors. */
1750 evutil_socket_error_to_string(int errcode)
1752 struct cached_sock_errs_entry *errs, *newerr, find;
1755 EVLOCK_LOCK(windows_socket_errors_lock_, 0);
1757 find.code = errcode;
1758 errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
1764 if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1765 FORMAT_MESSAGE_IGNORE_INSERTS |
1766 FORMAT_MESSAGE_ALLOCATE_BUFFER,
1767 NULL, errcode, 0, (char *)&msg, 0, NULL))
1768 chomp (msg); /* because message has trailing newline */
1771 /* use LocalAlloc because FormatMessage does */
1772 msg = LocalAlloc(LMEM_FIXED, len);
1774 msg = (char *)"LocalAlloc failed during Winsock error";
1777 evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
1780 newerr = (struct cached_sock_errs_entry *)
1781 mm_malloc(sizeof (struct cached_sock_errs_entry));
1785 msg = (char *)"malloc failed during Winsock error";
1789 newerr->code = errcode;
1791 HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
1794 EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
1799 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1801 evutil_global_setup_locks_(const int enable_locks)
1803 EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
1809 evutil_free_sock_err_globals(void)
1811 struct cached_sock_errs_entry **errs, *tofree;
1813 for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
1816 errs = HT_NEXT_RMV(cached_sock_errs_map,
1817 &windows_socket_errors,
1819 LocalFree(tofree->msg);
1823 HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
1825 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1826 if (windows_socket_errors_lock_ != NULL) {
1827 EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
1828 windows_socket_errors_lock_ = NULL;
1835 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1837 evutil_global_setup_locks_(const int enable_locks)
1844 evutil_free_sock_err_globals(void)
1851 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
1855 va_start(ap, format);
1856 r = evutil_vsnprintf(buf, buflen, format, ap);
1862 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
1867 #if defined(_MSC_VER) || defined(_WIN32)
1868 r = _vsnprintf(buf, buflen, format, ap);
1870 r = _vscprintf(format, ap);
1872 /* Make sure we always use the correct vsnprintf on IRIX */
1873 extern int _xpg5_vsnprintf(char * __restrict,
1874 __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
1875 const char * __restrict, /* va_list */ char *);
1877 r = _xpg5_vsnprintf(buf, buflen, format, ap);
1879 r = vsnprintf(buf, buflen, format, ap);
1881 buf[buflen-1] = '\0';
1885 #define USE_INTERNAL_NTOP
1886 #define USE_INTERNAL_PTON
1889 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
1891 #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1892 return inet_ntop(af, src, dst, len);
1894 if (af == AF_INET) {
1895 const struct in_addr *in = src;
1896 const ev_uint32_t a = ntohl(in->s_addr);
1898 r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
1899 (int)(ev_uint8_t)((a>>24)&0xff),
1900 (int)(ev_uint8_t)((a>>16)&0xff),
1901 (int)(ev_uint8_t)((a>>8 )&0xff),
1902 (int)(ev_uint8_t)((a )&0xff));
1903 if (r<0||(size_t)r>=len)
1908 } else if (af == AF_INET6) {
1909 const struct in6_addr *addr = src;
1911 int longestGapLen = 0, longestGapPos = -1, i,
1912 curGapPos = -1, curGapLen = 0;
1913 ev_uint16_t words[8];
1914 for (i = 0; i < 8; ++i) {
1916 (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1918 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1919 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1920 (words[5] == 0xffff))) {
1921 /* This is an IPv4 address. */
1922 if (words[5] == 0) {
1923 evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1924 addr->s6_addr[12], addr->s6_addr[13],
1925 addr->s6_addr[14], addr->s6_addr[15]);
1927 evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1928 addr->s6_addr[12], addr->s6_addr[13],
1929 addr->s6_addr[14], addr->s6_addr[15]);
1931 if (strlen(buf) > len)
1933 strlcpy(dst, buf, len);
1938 if (words[i] == 0) {
1941 while (i<8 && words[i] == 0) {
1944 if (curGapLen > longestGapLen) {
1945 longestGapPos = curGapPos;
1946 longestGapLen = curGapLen;
1952 if (longestGapLen<=1)
1956 for (i = 0; i < 8; ++i) {
1957 if (words[i] == 0 && longestGapPos == i) {
1961 while (i < 8 && words[i] == 0)
1963 --i; /* to compensate for loop increment. */
1966 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1973 if (strlen(buf) > len)
1975 strlcpy(dst, buf, len);
1985 evutil_inet_pton(int af, const char *src, void *dst)
1987 #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1988 return inet_pton(af, src, dst);
1990 if (af == AF_INET) {
1993 struct in_addr *addr = dst;
1994 if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
1996 if (a > 255) return 0;
1997 if (b > 255) return 0;
1998 if (c > 255) return 0;
1999 if (d > 255) return 0;
2000 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2003 } else if (af == AF_INET6) {
2004 struct in6_addr *out = dst;
2005 ev_uint16_t words[8];
2006 int gapPos = -1, i, setWords=0;
2007 const char *dot = strchr(src, '.');
2008 const char *eow; /* end of words. */
2012 eow = src+strlen(src);
2014 unsigned byte1,byte2,byte3,byte4;
2016 for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
2020 /* We use "scanf" because some platform inet_aton()s are too lax
2021 * about IPv4 addresses of the form "1.2.3" */
2022 if (sscanf(eow, "%u.%u.%u.%u%c",
2023 &byte1,&byte2,&byte3,&byte4,&more) != 4)
2032 words[6] = (byte1<<8) | byte2;
2033 words[7] = (byte3<<8) | byte4;
2041 if (EVUTIL_ISXDIGIT_(*src)) {
2043 long r = strtol(src, &next, 16);
2051 words[i++] = (ev_uint16_t)r;
2054 if (*src != ':' && src != eow)
2057 } else if (*src == ':' && i > 0 && gapPos==-1) {
2060 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
2069 (setWords == 8 && gapPos != -1) ||
2070 (setWords < 8 && gapPos == -1))
2074 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2075 int gapLen = 8 - setWords;
2076 /* assert(nToMove >= 0); */
2078 return -1; /* should be impossible */
2079 memmove(&words[gapPos+gapLen], &words[gapPos],
2080 sizeof(ev_uint16_t)*nToMove);
2081 memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
2083 for (i = 0; i < 8; ++i) {
2084 out->s6_addr[2*i ] = words[i] >> 8;
2085 out->s6_addr[2*i+1] = words[i] & 0xff;
2097 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
2101 const char *cp, *addr_part, *port_part;
2103 /* recognized formats are:
2111 cp = strchr(ip_as_string, ':');
2112 if (*ip_as_string == '[') {
2114 if (!(cp = strchr(ip_as_string, ']'))) {
2117 len = ( cp-(ip_as_string + 1) );
2118 if (len > sizeof(buf)-1) {
2121 memcpy(buf, ip_as_string+1, len);
2129 } else if (cp && strchr(cp+1, ':')) {
2131 addr_part = ip_as_string;
2135 if (cp - ip_as_string > (int)sizeof(buf)-1) {
2138 memcpy(buf, ip_as_string, cp-ip_as_string);
2139 buf[cp-ip_as_string] = '\0';
2143 addr_part = ip_as_string;
2148 if (port_part == NULL) {
2151 port = atoi(port_part);
2152 if (port <= 0 || port > 65535) {
2158 return -1; /* Should be impossible. */
2162 struct sockaddr_in6 sin6;
2163 memset(&sin6, 0, sizeof(sin6));
2164 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2165 sin6.sin6_len = sizeof(sin6);
2167 sin6.sin6_family = AF_INET6;
2168 sin6.sin6_port = htons(port);
2169 if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
2171 if ((int)sizeof(sin6) > *outlen)
2173 memset(out, 0, *outlen);
2174 memcpy(out, &sin6, sizeof(sin6));
2175 *outlen = sizeof(sin6);
2181 struct sockaddr_in sin;
2182 memset(&sin, 0, sizeof(sin));
2183 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2184 sin.sin_len = sizeof(sin);
2186 sin.sin_family = AF_INET;
2187 sin.sin_port = htons(port);
2188 if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
2190 if ((int)sizeof(sin) > *outlen)
2192 memset(out, 0, *outlen);
2193 memcpy(out, &sin, sizeof(sin));
2194 *outlen = sizeof(sin);
2200 evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
2203 const char *res=NULL;
2205 if (sa->sa_family == AF_INET) {
2206 const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
2207 res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
2208 port = ntohs(sin->sin_port);
2210 evutil_snprintf(out, outlen, "%s:%d", b, port);
2213 } else if (sa->sa_family == AF_INET6) {
2214 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
2215 res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
2216 port = ntohs(sin6->sin6_port);
2218 evutil_snprintf(out, outlen, "[%s]:%d", b, port);
2223 evutil_snprintf(out, outlen, "<addr with socktype %d>",
2224 (int)sa->sa_family);
2229 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
2233 if (0 != (r = (sa1->sa_family - sa2->sa_family)))
2236 if (sa1->sa_family == AF_INET) {
2237 const struct sockaddr_in *sin1, *sin2;
2238 sin1 = (const struct sockaddr_in *)sa1;
2239 sin2 = (const struct sockaddr_in *)sa2;
2240 if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
2242 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
2244 else if (include_port &&
2245 (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
2251 else if (sa1->sa_family == AF_INET6) {
2252 const struct sockaddr_in6 *sin1, *sin2;
2253 sin1 = (const struct sockaddr_in6 *)sa1;
2254 sin2 = (const struct sockaddr_in6 *)sa2;
2255 if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
2257 else if (include_port &&
2258 (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
2267 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
2268 * has 256 bits to look up whether a character is in some set or not. This
2269 * fails on non-ASCII platforms, but so does every other place where we
2270 * take a char and write it onto the network.
2272 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
2273 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2274 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
2275 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2276 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2277 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
2278 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2279 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2280 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
2281 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2282 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2283 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2284 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
2286 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
2287 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2288 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2289 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2290 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2291 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2292 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2293 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2294 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2295 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2296 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2297 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2298 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2299 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2300 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2301 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2302 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2304 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
2305 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2306 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2307 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2308 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2309 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2310 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2311 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2312 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2313 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2314 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2315 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2316 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2317 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2318 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2319 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2320 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2323 #define IMPL_CTYPE_FN(name) \
2324 int EVUTIL_##name##_(char c) { \
2326 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
2328 IMPL_CTYPE_FN(ISALPHA)
2329 IMPL_CTYPE_FN(ISALNUM)
2330 IMPL_CTYPE_FN(ISSPACE)
2331 IMPL_CTYPE_FN(ISDIGIT)
2332 IMPL_CTYPE_FN(ISXDIGIT)
2333 IMPL_CTYPE_FN(ISPRINT)
2334 IMPL_CTYPE_FN(ISLOWER)
2335 IMPL_CTYPE_FN(ISUPPER)
2337 char EVUTIL_TOLOWER_(char c)
2339 return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2341 char EVUTIL_TOUPPER_(char c)
2343 return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2346 evutil_ascii_strcasecmp(const char *s1, const char *s2)
2350 c1 = EVUTIL_TOLOWER_(*s1++);
2351 c2 = EVUTIL_TOLOWER_(*s2++);
2360 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2364 c1 = EVUTIL_TOLOWER_(*s1++);
2365 c2 = EVUTIL_TOLOWER_(*s2++);
2377 evutil_rtrim_lws_(char *str)
2384 if ((cp = strchr(str, '\0')) == NULL || (cp == str))
2389 while (*cp == ' ' || *cp == '\t') {
2398 evutil_issetugid(void)
2400 #ifdef EVENT__HAVE_ISSETUGID
2404 #ifdef EVENT__HAVE_GETEUID
2405 if (getuid() != geteuid())
2408 #ifdef EVENT__HAVE_GETEGID
2409 if (getgid() != getegid())
2417 evutil_getenv_(const char *varname)
2419 if (evutil_issetugid())
2422 return getenv(varname);
2426 evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
2430 evutil_gettimeofday(&tv, NULL);
2431 seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
2433 seed += (ev_uint32_t) _getpid();
2435 seed += (ev_uint32_t) getpid();
2443 evutil_weakrand_(struct evutil_weakrand_state *state)
2445 /* This RNG implementation is a linear congruential generator, with
2446 * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
2447 * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2449 * The linear congruential generator is not an industrial-strength
2450 * RNG! It's fast, but it can have higher-order patterns. Notably,
2451 * the low bits tend to have periodicity.
2453 state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
2454 return (ev_int32_t)(state->seed);
2458 evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
2460 ev_int32_t divisor, result;
2462 /* We can't just do weakrand() % top, since the low bits of the LCG
2463 * are less random than the high ones. (Specifically, since the LCG
2464 * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2465 * therefore the low m bits of the LCG will have period 2^m.) */
2466 divisor = EVUTIL_WEAKRAND_MAX / top;
2468 result = evutil_weakrand_(state) / divisor;
2469 } while (result >= top);
2474 * Volatile pointer to memset: we use this to keep the compiler from
2475 * eliminating our call to memset.
2477 void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
2480 evutil_memclear_(void *mem, size_t len)
2482 evutil_memset_volatile_(mem, 0, len);
2486 evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
2488 static const char LOOPBACK_S6[16] =
2489 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2490 if (addr->sa_family == AF_INET) {
2491 struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2492 return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2493 } else if (addr->sa_family == AF_INET6) {
2494 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2495 return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2501 evutil_hex_char_to_int_(char c)
2515 case 'A': case 'a': return 10;
2516 case 'B': case 'b': return 11;
2517 case 'C': case 'c': return 12;
2518 case 'D': case 'd': return 13;
2519 case 'E': case 'e': return 14;
2520 case 'F': case 'f': return 15;
2527 evutil_load_windows_system_library_(const TCHAR *library_name)
2529 TCHAR path[MAX_PATH];
2531 n = GetSystemDirectory(path, MAX_PATH);
2532 if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2534 _tcscat(path, TEXT("\\"));
2535 _tcscat(path, library_name);
2536 return LoadLibrary(path);
2540 /* Internal wrapper around 'socket' to provide Linux-style support for
2541 * syscall-saving methods where available.
2543 * In addition to regular socket behavior, you can use a bitwise or to set the
2544 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2545 * to make the socket nonblocking or close-on-exec with as few syscalls as
2549 evutil_socket_(int domain, int type, int protocol)
2552 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2553 r = socket(domain, type, protocol);
2556 else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
2559 #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2560 r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
2563 if (type & EVUTIL_SOCK_NONBLOCK) {
2564 if (evutil_fast_socket_nonblocking(r) < 0) {
2565 evutil_closesocket(r);
2569 if (type & EVUTIL_SOCK_CLOEXEC) {
2570 if (evutil_fast_socket_closeonexec(r) < 0) {
2571 evutil_closesocket(r);
2578 /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2579 * support for syscall-saving methods where available.
2581 * In addition to regular accept behavior, you can set one or more of flags
2582 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2583 * make the socket nonblocking or close-on-exec with as few syscalls as
2587 evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
2588 ev_socklen_t *addrlen, int flags)
2590 evutil_socket_t result;
2591 #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2592 result = accept4(sockfd, addr, addrlen, flags);
2593 if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
2594 /* A nonnegative result means that we succeeded, so return.
2595 * Failing with EINVAL means that an option wasn't supported,
2596 * and failing with ENOSYS means that the syscall wasn't
2597 * there: in those cases we want to fall back. Otherwise, we
2598 * got a real error, and we should return. */
2602 result = accept(sockfd, addr, addrlen);
2606 if (flags & EVUTIL_SOCK_CLOEXEC) {
2607 if (evutil_fast_socket_closeonexec(result) < 0) {
2608 evutil_closesocket(result);
2612 if (flags & EVUTIL_SOCK_NONBLOCK) {
2613 if (evutil_fast_socket_nonblocking(result) < 0) {
2614 evutil_closesocket(result);
2621 /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2622 * fd[1] get read from fd[0]. Make both fds nonblocking and close-on-exec.
2623 * Return 0 on success, -1 on failure.
2626 evutil_make_internal_pipe_(evutil_socket_t fd[2])
2629 Making the second socket nonblocking is a bit subtle, given that we
2630 ignore any EAGAIN returns when writing to it, and you don't usally
2631 do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2632 then there's no need to add any more data to the buffer, since
2633 the main thread is already either about to wake up and drain it,
2634 or woken up and in the process of draining it.
2637 #if defined(EVENT__HAVE_PIPE2)
2638 if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
2641 #if defined(EVENT__HAVE_PIPE)
2642 if (pipe(fd) == 0) {
2643 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2644 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2645 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2646 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2654 event_warn("%s: pipe", __func__);
2659 #define LOCAL_SOCKETPAIR_AF AF_INET
2661 #define LOCAL_SOCKETPAIR_AF AF_UNIX
2663 if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
2664 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2665 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2666 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2667 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2668 evutil_closesocket(fd[0]);
2669 evutil_closesocket(fd[1]);
2679 /* Wrapper around eventfd on systems that provide it. Unlike the system
2680 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2681 * flags. Returns -1 on error or if eventfd is not supported.
2684 evutil_eventfd_(unsigned initval, int flags)
2686 #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
2688 #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
2689 r = eventfd(initval, flags);
2690 if (r >= 0 || flags == 0)
2693 r = eventfd(initval, 0);
2696 if (flags & EVUTIL_EFD_CLOEXEC) {
2697 if (evutil_fast_socket_closeonexec(r) < 0) {
2698 evutil_closesocket(r);
2702 if (flags & EVUTIL_EFD_NONBLOCK) {
2703 if (evutil_fast_socket_nonblocking(r) < 0) {
2704 evutil_closesocket(r);
2715 evutil_free_globals_(void)
2717 evutil_free_secure_rng_globals_();
2718 evutil_free_sock_err_globals();