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 != AF_INET
236 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
240 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
244 listener = socket(AF_INET, type, 0);
247 memset(&listen_addr, 0, sizeof(listen_addr));
248 listen_addr.sin_family = AF_INET;
249 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
250 listen_addr.sin_port = 0; /* kernel chooses port. */
251 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
253 goto tidy_up_and_fail;
254 if (listen(listener, 1) == -1)
255 goto tidy_up_and_fail;
257 connector = socket(AF_INET, type, 0);
259 goto tidy_up_and_fail;
260 /* We want to find out the port number to connect to. */
261 size = sizeof(connect_addr);
262 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
263 goto tidy_up_and_fail;
264 if (size != sizeof (connect_addr))
265 goto abort_tidy_up_and_fail;
266 if (connect(connector, (struct sockaddr *) &connect_addr,
267 sizeof(connect_addr)) == -1)
268 goto tidy_up_and_fail;
270 size = sizeof(listen_addr);
271 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
273 goto tidy_up_and_fail;
274 if (size != sizeof(listen_addr))
275 goto abort_tidy_up_and_fail;
276 /* Now check we are talking to ourself by matching port and host on the
278 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
279 goto tidy_up_and_fail;
280 if (size != sizeof (connect_addr)
281 || listen_addr.sin_family != connect_addr.sin_family
282 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
283 || listen_addr.sin_port != connect_addr.sin_port)
284 goto abort_tidy_up_and_fail;
285 evutil_closesocket(listener);
291 abort_tidy_up_and_fail:
292 saved_errno = ERR(ECONNABORTED);
295 saved_errno = EVUTIL_SOCKET_ERROR();
297 evutil_closesocket(listener);
299 evutil_closesocket(connector);
301 evutil_closesocket(acceptor);
303 EVUTIL_SET_SOCKET_ERROR(saved_errno);
309 evutil_make_socket_nonblocking(evutil_socket_t fd)
313 u_long nonblocking = 1;
314 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
315 event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
322 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
323 event_warn("fcntl(%d, F_GETFL)", fd);
326 if (!(flags & O_NONBLOCK)) {
327 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
328 event_warn("fcntl(%d, F_SETFL)", fd);
337 /* Faster version of evutil_make_socket_nonblocking for internal use.
339 * Requires that no F_SETFL flags were previously set on the fd.
342 evutil_fast_socket_nonblocking(evutil_socket_t fd)
345 return evutil_make_socket_nonblocking(fd);
347 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
348 event_warn("fcntl(%d, F_SETFL)", fd);
356 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
360 /* REUSEADDR on Unix means, "don't hang on to this address after the
361 * listener is closed." On Windows, though, it means "don't keep other
362 * processes from binding to this address while we're using it. */
363 return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
364 (ev_socklen_t)sizeof(one));
371 evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
373 #if defined __linux__ && defined(SO_REUSEPORT)
375 /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
376 * threads) can bind to the same port if they each set the option. */
377 return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
378 (ev_socklen_t)sizeof(one));
385 evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
387 #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
390 /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
391 * has arrived and ready to read */
392 return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
393 (ev_socklen_t)sizeof(one));
399 evutil_make_socket_closeonexec(evutil_socket_t fd)
401 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
403 if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
404 event_warn("fcntl(%d, F_GETFD)", fd);
407 if (!(flags & FD_CLOEXEC)) {
408 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
409 event_warn("fcntl(%d, F_SETFD)", fd);
417 /* Faster version of evutil_make_socket_closeonexec for internal use.
419 * Requires that no F_SETFD flags were previously set on the fd.
422 evutil_fast_socket_closeonexec(evutil_socket_t fd)
424 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
425 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
426 event_warn("fcntl(%d, F_SETFD)", fd);
434 evutil_closesocket(evutil_socket_t sock)
439 return closesocket(sock);
444 evutil_strtoll(const char *s, char **endptr, int base)
446 #ifdef EVENT__HAVE_STRTOLL
447 return (ev_int64_t)strtoll(s, endptr, base);
448 #elif EVENT__SIZEOF_LONG == 8
449 return (ev_int64_t)strtol(s, endptr, base);
450 #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
451 /* XXXX on old versions of MS APIs, we only support base
456 r = (ev_int64_t) _atoi64(s);
466 #elif defined(_WIN32)
467 return (ev_int64_t) _strtoi64(s, endptr, base);
468 #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
471 if (base != 10 && base != 16)
474 n = sscanf(s, "%lld", &r);
476 unsigned long long ru=0;
477 n = sscanf(s, "%llx", &ru);
478 if (ru > EV_INT64_MAX)
484 while (EVUTIL_ISSPACE_(*s))
489 while (EVUTIL_ISDIGIT_(*s))
492 while (EVUTIL_ISXDIGIT_(*s))
499 #error "I don't know how to parse 64-bit integers."
505 evutil_socket_geterror(evutil_socket_t sock)
507 int optval, optvallen=sizeof(optval);
508 int err = WSAGetLastError();
509 if (err == WSAEWOULDBLOCK && sock >= 0) {
510 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
520 /* XXX we should use an enum here. */
521 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
523 evutil_socket_connect_(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
528 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
531 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
536 if (connect(*fd_ptr, sa, socklen) < 0) {
537 int e = evutil_socket_geterror(*fd_ptr);
538 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
540 if (EVUTIL_ERR_CONNECT_REFUSED(e))
549 evutil_closesocket(*fd_ptr);
555 /* Check whether a socket on which we called connect() is done
556 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
557 error case, set the current socket errno to the error that happened during
558 the connect operation. */
560 evutil_socket_finished_connecting_(evutil_socket_t fd)
563 ev_socklen_t elen = sizeof(e);
565 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
569 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
571 EVUTIL_SET_SOCKET_ERROR(e);
578 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
579 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
580 EVUTIL_AI_ADDRCONFIG) != \
581 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
582 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
583 EVUTIL_AI_ADDRCONFIG)
584 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
587 /* We sometimes need to know whether we have an ipv4 address and whether we
588 have an ipv6 address. If 'have_checked_interfaces', then we've already done
589 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
590 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
591 set by evutil_check_interfaces. */
592 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
594 /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
596 #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
598 /* Macro: True iff the IPv4 address 'addr', in host order, is a class D
599 * (multiclass) address.
601 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
604 evutil_found_ifaddr(const struct sockaddr *sa)
606 const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
607 "\x00\x00\x00\x00\x00\x00\x00\x00";
609 if (sa->sa_family == AF_INET) {
610 const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
611 ev_uint32_t addr = ntohl(sin->sin_addr.s_addr);
613 EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
614 EVUTIL_V4ADDR_IS_CLASSD(addr)) {
615 /* Not actually a usable external address. */
617 event_debug(("Detected an IPv4 interface"));
618 had_ipv4_address = 1;
620 } else if (sa->sa_family == AF_INET6) {
621 const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
622 const unsigned char *addr =
623 (unsigned char*)sin6->sin6_addr.s6_addr;
624 if (!memcmp(addr, ZEROES, 8) ||
625 ((addr[0] & 0xfe) == 0xfc) ||
626 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
627 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
629 /* This is a reserved, ipv4compat, ipv4map, loopback,
630 * link-local, multicast, or unspecified address. */
632 event_debug(("Detected an IPv6 interface"));
633 had_ipv6_address = 1;
639 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
640 ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
644 evutil_check_ifaddrs(void)
646 #if defined(EVENT__HAVE_GETIFADDRS)
647 /* Most free Unixy systems provide getifaddrs, which gives us a linked list
648 * of struct ifaddrs. */
649 struct ifaddrs *ifa = NULL;
650 const struct ifaddrs *i;
651 if (getifaddrs(&ifa) < 0) {
652 event_warn("Unable to call getifaddrs()");
656 for (i = ifa; i; i = i->ifa_next) {
659 evutil_found_ifaddr(i->ifa_addr);
664 #elif defined(_WIN32)
665 /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
666 "GetAdaptersInfo", but that's deprecated; let's just try
667 GetAdaptersAddresses and fall back to connect+getsockname.
669 HMODULE lib = evutil_load_windows_system_library_(TEXT("ihplapi.dll"));
670 GetAdaptersAddresses_fn_t fn;
672 IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
675 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
676 GAA_FLAG_SKIP_MULTICAST | \
677 GAA_FLAG_SKIP_DNS_SERVER)
682 if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
685 /* Guess how much space we need. */
687 addresses = mm_malloc(size);
690 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
691 if (res == ERROR_BUFFER_OVERFLOW) {
692 /* we didn't guess that we needed enough space; try again */
694 addresses = mm_malloc(size);
697 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
702 for (address = addresses; address; address = address->Next) {
703 IP_ADAPTER_UNICAST_ADDRESS *a;
704 for (a = address->FirstUnicastAddress; a; a = a->Next) {
705 /* Yes, it's a linked list inside a linked list */
706 struct sockaddr *sa = a->Address.lpSockaddr;
707 evutil_found_ifaddr(sa);
723 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
724 * the test seemed successful. */
726 evutil_check_interfaces(int force_recheck)
728 evutil_socket_t fd = -1;
729 struct sockaddr_in sin, sin_out;
730 struct sockaddr_in6 sin6, sin6_out;
731 ev_socklen_t sin_out_len = sizeof(sin_out);
732 ev_socklen_t sin6_out_len = sizeof(sin6_out);
734 if (have_checked_interfaces && !force_recheck)
737 if (evutil_check_ifaddrs() == 0) {
738 /* Use a nice sane interface, if this system has one. */
742 /* Ugh. There was no nice sane interface. So to check whether we have
743 * an interface open for a given protocol, will try to make a UDP
744 * 'connection' to a remote host on the internet. We don't actually
745 * use it, so the address doesn't matter, but we want to pick one that
746 * keep us from using a host- or link-local interface. */
747 memset(&sin, 0, sizeof(sin));
748 sin.sin_family = AF_INET;
749 sin.sin_port = htons(53);
750 r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
753 memset(&sin6, 0, sizeof(sin6));
754 sin6.sin6_family = AF_INET6;
755 sin6.sin6_port = htons(53);
756 r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
759 memset(&sin_out, 0, sizeof(sin_out));
760 memset(&sin6_out, 0, sizeof(sin6_out));
762 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
763 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
764 connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
765 getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
766 /* We might have an IPv4 interface. */
767 evutil_found_ifaddr((struct sockaddr*) &sin_out);
770 evutil_closesocket(fd);
772 if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
773 connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
774 getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
775 /* We might have an IPv6 interface. */
776 evutil_found_ifaddr((struct sockaddr*) &sin6_out);
780 evutil_closesocket(fd);
785 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
786 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
787 * it, and we should trust what they said.
789 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
791 /* Helper: construct a new addrinfo containing the socket address in
792 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
793 * socktype and protocol info from hints. If they weren't set, then
794 * allocate both a TCP and a UDP addrinfo.
796 struct evutil_addrinfo *
797 evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
798 const struct evutil_addrinfo *hints)
800 struct evutil_addrinfo *res;
801 EVUTIL_ASSERT(hints);
803 if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
804 /* Indecisive user! Give them a UDP and a TCP. */
805 struct evutil_addrinfo *r1, *r2;
806 struct evutil_addrinfo tmp;
807 memcpy(&tmp, hints, sizeof(tmp));
808 tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
809 r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
812 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
813 r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
815 evutil_freeaddrinfo(r1);
822 /* We're going to allocate extra space to hold the sockaddr. */
823 res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
826 res->ai_addr = (struct sockaddr*)
827 (((char*)res) + sizeof(struct evutil_addrinfo));
828 memcpy(res->ai_addr, sa, socklen);
829 res->ai_addrlen = socklen;
830 res->ai_family = sa->sa_family; /* Same or not? XXX */
831 res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
832 res->ai_socktype = hints->ai_socktype;
833 res->ai_protocol = hints->ai_protocol;
838 /* Append the addrinfo 'append' to the end of 'first', and return the start of
839 * the list. Either element can be NULL, in which case we return the element
840 * that is not NULL. */
841 struct evutil_addrinfo *
842 evutil_addrinfo_append_(struct evutil_addrinfo *first,
843 struct evutil_addrinfo *append)
845 struct evutil_addrinfo *ai = first;
850 ai->ai_next = append;
856 parse_numeric_servname(const char *servname)
860 n = (int) strtol(servname, &endptr, 10);
861 if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
867 /** Parse a service name in 'servname', which can be a decimal port.
868 * Return the port number, or -1 on error.
871 evutil_parse_servname(const char *servname, const char *protocol,
872 const struct evutil_addrinfo *hints)
874 int n = parse_numeric_servname(servname);
877 #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
878 if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
879 struct servent *ent = getservbyname(servname, protocol);
881 return ntohs(ent->s_port);
888 /* Return a string corresponding to a protocol number that we can pass to
891 evutil_unparse_protoname(int proto)
905 #ifdef EVENT__HAVE_GETPROTOBYNUMBER
907 struct protoent *ent = getprotobynumber(proto);
917 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
919 /* If we can guess the protocol from the socktype, do so. */
920 if (!hints->ai_protocol && hints->ai_socktype) {
921 if (hints->ai_socktype == SOCK_DGRAM)
922 hints->ai_protocol = IPPROTO_UDP;
923 else if (hints->ai_socktype == SOCK_STREAM)
924 hints->ai_protocol = IPPROTO_TCP;
927 /* Set the socktype if it isn't set. */
928 if (!hints->ai_socktype && hints->ai_protocol) {
929 if (hints->ai_protocol == IPPROTO_UDP)
930 hints->ai_socktype = SOCK_DGRAM;
931 else if (hints->ai_protocol == IPPROTO_TCP)
932 hints->ai_socktype = SOCK_STREAM;
934 else if (hints->ai_protocol == IPPROTO_SCTP)
935 hints->ai_socktype = SOCK_STREAM;
940 #if AF_UNSPEC != PF_UNSPEC
941 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
944 /** Implements the part of looking up hosts by name that's common to both
945 * the blocking and nonblocking resolver:
946 * - Adjust 'hints' to have a reasonable socktype and protocol.
947 * - Look up the port based on 'servname', and store it in *portnum,
948 * - Handle the nodename==NULL case
949 * - Handle some invalid arguments cases.
950 * - Handle the cases where nodename is an IPv4 or IPv6 address.
952 * If we need the resolver to look up the hostname, we return
953 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
954 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
955 * set *res as getaddrinfo would.
958 evutil_getaddrinfo_common_(const char *nodename, const char *servname,
959 struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
964 if (nodename == NULL && servname == NULL)
965 return EVUTIL_EAI_NONAME;
967 /* We only understand 3 families */
968 if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
969 hints->ai_family != PF_INET6)
970 return EVUTIL_EAI_FAMILY;
972 evutil_getaddrinfo_infer_protocols(hints);
974 /* Look up the port number and protocol, if possible. */
975 pname = evutil_unparse_protoname(hints->ai_protocol);
977 /* XXXX We could look at the protocol we got back from
978 * getservbyname, but it doesn't seem too useful. */
979 port = evutil_parse_servname(servname, pname, hints);
981 return EVUTIL_EAI_NONAME;
985 /* If we have no node name, then we're supposed to bind to 'any' and
986 * connect to localhost. */
987 if (nodename == NULL) {
988 struct evutil_addrinfo *res4=NULL, *res6=NULL;
989 if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
990 struct sockaddr_in6 sin6;
991 memset(&sin6, 0, sizeof(sin6));
992 sin6.sin6_family = AF_INET6;
993 sin6.sin6_port = htons(port);
994 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
998 sin6.sin6_addr.s6_addr[15] = 1;
1000 res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1001 sizeof(sin6), hints);
1003 return EVUTIL_EAI_MEMORY;
1006 if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
1007 struct sockaddr_in sin;
1008 memset(&sin, 0, sizeof(sin));
1009 sin.sin_family = AF_INET;
1010 sin.sin_port = htons(port);
1011 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1012 /* Bind to 0.0.0.0 */
1014 /* connect to 127.0.0.1 */
1015 sin.sin_addr.s_addr = htonl(0x7f000001);
1017 res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
1018 sizeof(sin), hints);
1021 evutil_freeaddrinfo(res6);
1022 return EVUTIL_EAI_MEMORY;
1025 *res = evutil_addrinfo_append_(res4, res6);
1029 /* If we can, we should try to parse the hostname without resolving
1032 if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
1033 struct sockaddr_in6 sin6;
1034 memset(&sin6, 0, sizeof(sin6));
1035 if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
1036 /* Got an ipv6 address. */
1037 sin6.sin6_family = AF_INET6;
1038 sin6.sin6_port = htons(port);
1039 *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1040 sizeof(sin6), hints);
1042 return EVUTIL_EAI_MEMORY;
1048 if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
1049 struct sockaddr_in sin;
1050 memset(&sin, 0, sizeof(sin));
1051 if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
1052 /* Got an ipv6 address. */
1053 sin.sin_family = AF_INET;
1054 sin.sin_port = htons(port);
1055 *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
1056 sizeof(sin), hints);
1058 return EVUTIL_EAI_MEMORY;
1064 /* If we have reached this point, we definitely need to do a DNS
1066 if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
1067 /* If we're not allowed to do one, then say so. */
1068 return EVUTIL_EAI_NONAME;
1071 return EVUTIL_EAI_NEED_RESOLVE;
1074 #ifdef EVENT__HAVE_GETADDRINFO
1075 #define USE_NATIVE_GETADDRINFO
1078 #ifdef USE_NATIVE_GETADDRINFO
1079 /* A mask of all the flags that we declare, so we can clear them before calling
1080 * the native getaddrinfo */
1081 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
1085 #ifndef AI_CANONNAME
1086 EVUTIL_AI_CANONNAME |
1088 #ifndef AI_NUMERICHOST
1089 EVUTIL_AI_NUMERICHOST |
1091 #ifndef AI_NUMERICSERV
1092 EVUTIL_AI_NUMERICSERV |
1094 #ifndef AI_ADDRCONFIG
1095 EVUTIL_AI_ADDRCONFIG |
1101 EVUTIL_AI_V4MAPPED |
1103 EVUTIL_AI_LIBEVENT_ALLOCATED;
1105 static const unsigned int ALL_NATIVE_AI_FLAGS =
1112 #ifdef AI_NUMERICHOST
1115 #ifdef AI_NUMERICSERV
1118 #ifdef AI_ADDRCONFIG
1130 #ifndef USE_NATIVE_GETADDRINFO
1131 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1134 static struct evutil_addrinfo *
1135 addrinfo_from_hostent(const struct hostent *ent,
1136 int port, const struct evutil_addrinfo *hints)
1139 struct sockaddr_in sin;
1140 struct sockaddr_in6 sin6;
1141 struct sockaddr *sa;
1143 struct evutil_addrinfo *res=NULL, *ai;
1146 if (ent->h_addrtype == PF_INET) {
1147 memset(&sin, 0, sizeof(sin));
1148 sin.sin_family = AF_INET;
1149 sin.sin_port = htons(port);
1150 sa = (struct sockaddr *)&sin;
1151 socklen = sizeof(struct sockaddr_in);
1152 addrp = &sin.sin_addr;
1153 if (ent->h_length != sizeof(sin.sin_addr)) {
1154 event_warnx("Weird h_length from gethostbyname");
1157 } else if (ent->h_addrtype == PF_INET6) {
1158 memset(&sin6, 0, sizeof(sin6));
1159 sin6.sin6_family = AF_INET6;
1160 sin6.sin6_port = htons(port);
1161 sa = (struct sockaddr *)&sin6;
1162 socklen = sizeof(struct sockaddr_in);
1163 addrp = &sin6.sin6_addr;
1164 if (ent->h_length != sizeof(sin6.sin6_addr)) {
1165 event_warnx("Weird h_length from gethostbyname");
1171 for (i = 0; ent->h_addr_list[i]; ++i) {
1172 memcpy(addrp, ent->h_addr_list[i], ent->h_length);
1173 ai = evutil_new_addrinfo_(sa, socklen, hints);
1175 evutil_freeaddrinfo(res);
1178 res = evutil_addrinfo_append_(res, ai);
1181 if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1182 res->ai_canonname = mm_strdup(ent->h_name);
1183 if (res->ai_canonname == NULL) {
1184 evutil_freeaddrinfo(res);
1193 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1194 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1195 * that we'll only get addresses we could maybe connect to.
1198 evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
1200 if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1202 if (hints->ai_family != PF_UNSPEC)
1204 if (!have_checked_interfaces)
1205 evutil_check_interfaces(0);
1206 if (had_ipv4_address && !had_ipv6_address) {
1207 hints->ai_family = PF_INET;
1208 } else if (!had_ipv4_address && had_ipv6_address) {
1209 hints->ai_family = PF_INET6;
1213 #ifdef USE_NATIVE_GETADDRINFO
1214 static int need_numeric_port_hack_=0;
1215 static int need_socktype_protocol_hack_=0;
1216 static int tested_for_getaddrinfo_hacks=0;
1218 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1219 giving a numeric port without giving an ai_socktype was verboten.
1220 We test for this so we can apply an appropriate workaround. If it
1221 turns out that the bug is present, then:
1223 - If nodename==NULL and servname is numeric, we build an answer
1224 ourselves using evutil_getaddrinfo_common_().
1226 - If nodename!=NULL and servname is numeric, then we set
1227 servname=NULL when calling getaddrinfo, and post-process the
1228 result to set the ports on it.
1230 We test for this bug at runtime, since otherwise we can't have the
1231 same binary run on multiple BSD versions.
1233 - Some versions of Solaris believe that it's nice to leave to protocol
1234 field set to 0. We test for this so we can apply an appropriate
1238 test_for_getaddrinfo_hacks(void)
1241 struct evutil_addrinfo *ai=NULL, *ai2=NULL;
1242 struct evutil_addrinfo hints;
1244 memset(&hints,0,sizeof(hints));
1245 hints.ai_family = PF_UNSPEC;
1247 #ifdef AI_NUMERICHOST
1250 #ifdef AI_NUMERICSERV
1254 r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1255 hints.ai_socktype = SOCK_STREAM;
1256 r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1257 if (r2 == 0 && r != 0) {
1258 need_numeric_port_hack_=1;
1260 if (ai2 && ai2->ai_protocol == 0) {
1261 need_socktype_protocol_hack_=1;
1268 tested_for_getaddrinfo_hacks=1;
1272 need_numeric_port_hack(void)
1274 if (!tested_for_getaddrinfo_hacks)
1275 test_for_getaddrinfo_hacks();
1276 return need_numeric_port_hack_;
1280 need_socktype_protocol_hack(void)
1282 if (!tested_for_getaddrinfo_hacks)
1283 test_for_getaddrinfo_hacks();
1284 return need_socktype_protocol_hack_;
1288 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1290 /* Now we run through the list and set the ports on all of the
1291 * results where ports would make sense. */
1292 for ( ; *ai; ai = &(*ai)->ai_next) {
1293 struct sockaddr *sa = (*ai)->ai_addr;
1294 if (sa && sa->sa_family == AF_INET) {
1295 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1296 sin->sin_port = htons(port);
1297 } else if (sa && sa->sa_family == AF_INET6) {
1298 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1299 sin6->sin6_port = htons(port);
1301 /* A numeric port makes no sense here; remove this one
1303 struct evutil_addrinfo *victim = *ai;
1304 *ai = victim->ai_next;
1305 victim->ai_next = NULL;
1306 freeaddrinfo(victim);
1312 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1314 struct evutil_addrinfo *ai_new;
1315 for (; ai; ai = ai->ai_next) {
1316 evutil_getaddrinfo_infer_protocols(ai);
1317 if (ai->ai_socktype || ai->ai_protocol)
1319 ai_new = mm_malloc(sizeof(*ai_new));
1322 memcpy(ai_new, ai, sizeof(*ai_new));
1323 ai->ai_socktype = SOCK_STREAM;
1324 ai->ai_protocol = IPPROTO_TCP;
1325 ai_new->ai_socktype = SOCK_DGRAM;
1326 ai_new->ai_protocol = IPPROTO_UDP;
1328 ai_new->ai_next = ai->ai_next;
1329 ai->ai_next = ai_new;
1336 evutil_getaddrinfo(const char *nodename, const char *servname,
1337 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1339 #ifdef USE_NATIVE_GETADDRINFO
1340 struct evutil_addrinfo hints;
1341 int portnum=-1, need_np_hack, err;
1344 memcpy(&hints, hints_in, sizeof(hints));
1346 memset(&hints, 0, sizeof(hints));
1347 hints.ai_family = PF_UNSPEC;
1350 #ifndef AI_ADDRCONFIG
1351 /* Not every system has AI_ADDRCONFIG, so fake it. */
1352 if (hints.ai_family == PF_UNSPEC &&
1353 (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1354 evutil_adjust_hints_for_addrconfig_(&hints);
1358 #ifndef AI_NUMERICSERV
1359 /* Not every system has AI_NUMERICSERV, so fake it. */
1360 if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1361 if (servname && parse_numeric_servname(servname)<0)
1362 return EVUTIL_EAI_NONAME;
1366 /* Enough operating systems handle enough common non-resolve
1367 * cases here weirdly enough that we are better off just
1368 * overriding them. For example:
1370 * - Windows doesn't like to infer the protocol from the
1371 * socket type, or fill in socket or protocol types much at
1372 * all. It also seems to do its own broken implicit
1373 * always-on version of AI_ADDRCONFIG that keeps it from
1374 * ever resolving even a literal IPv6 address when
1375 * ai_addrtype is PF_UNSPEC.
1380 err = evutil_getaddrinfo_common_(nodename,servname,&hints,
1383 err == EVUTIL_EAI_MEMORY ||
1384 err == EVUTIL_EAI_NONAME)
1386 /* If we make it here, the system getaddrinfo can
1387 * have a crack at it. */
1391 /* See documentation for need_numeric_port_hack above.*/
1392 need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1393 && ((portnum=parse_numeric_servname(servname)) >= 0);
1396 return evutil_getaddrinfo_common_(
1397 NULL,servname,&hints, res, &portnum);
1401 if (need_socktype_protocol_hack()) {
1402 evutil_getaddrinfo_infer_protocols(&hints);
1405 /* Make sure that we didn't actually steal any AI_FLAGS values that
1406 * the system is using. (This is a constant expression, and should ge
1409 * XXXX Turn this into a compile-time failure rather than a run-time
1412 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1414 /* Clear any flags that only libevent understands. */
1415 hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1417 err = getaddrinfo(nodename, servname, &hints, res);
1419 apply_numeric_port_hack(portnum, res);
1421 if (need_socktype_protocol_hack()) {
1422 if (apply_socktype_protocol_hack(*res) < 0) {
1423 evutil_freeaddrinfo(*res);
1425 return EVUTIL_EAI_MEMORY;
1431 struct hostent *ent = NULL;
1432 struct evutil_addrinfo hints;
1435 memcpy(&hints, hints_in, sizeof(hints));
1437 memset(&hints, 0, sizeof(hints));
1438 hints.ai_family = PF_UNSPEC;
1441 evutil_adjust_hints_for_addrconfig_(&hints);
1443 err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
1444 if (err != EVUTIL_EAI_NEED_RESOLVE) {
1445 /* We either succeeded or failed. No need to continue */
1450 /* Use any of the various gethostbyname_r variants as available. */
1452 #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1453 /* This one is what glibc provides. */
1455 struct hostent hostent;
1457 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1459 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1461 struct hostent hostent;
1462 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1464 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1465 struct hostent_data data;
1466 struct hostent hostent;
1467 memset(&data, 0, sizeof(data));
1468 err = gethostbyname_r(nodename, &hostent, &data);
1469 ent = err ? NULL : &hostent;
1471 /* fall back to gethostbyname. */
1472 /* XXXX This needs a lock everywhere but Windows. */
1473 ent = gethostbyname(nodename);
1475 err = WSAGetLastError();
1481 /* Now we have either ent or err set. */
1483 /* XXX is this right for windows ? */
1486 return EVUTIL_EAI_AGAIN;
1489 return EVUTIL_EAI_FAIL;
1490 case HOST_NOT_FOUND:
1491 return EVUTIL_EAI_NONAME;
1493 #if NO_DATA != NO_ADDRESS
1496 return EVUTIL_EAI_NODATA;
1500 if (ent->h_addrtype != hints.ai_family &&
1501 hints.ai_family != PF_UNSPEC) {
1502 /* This wasn't the type we were hoping for. Too bad
1503 * we never had a chance to ask gethostbyname for what
1505 return EVUTIL_EAI_NONAME;
1508 /* Make sure we got _some_ answers. */
1509 if (ent->h_length == 0)
1510 return EVUTIL_EAI_NODATA;
1512 /* If we got an address type we don't know how to make a
1513 sockaddr for, give up. */
1514 if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1515 return EVUTIL_EAI_FAMILY;
1517 *res = addrinfo_from_hostent(ent, port, &hints);
1519 return EVUTIL_EAI_MEMORY;
1527 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1529 #ifdef EVENT__HAVE_GETADDRINFO
1530 if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
1536 struct evutil_addrinfo *next = ai->ai_next;
1537 if (ai->ai_canonname)
1538 mm_free(ai->ai_canonname);
1544 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1547 evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
1549 if (!evdns_getaddrinfo_impl)
1550 evdns_getaddrinfo_impl = fn;
1553 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1554 * otherwise do a blocking resolve and pass the result to the callback in the
1555 * way that evdns_getaddrinfo would.
1558 evutil_getaddrinfo_async_(struct evdns_base *dns_base,
1559 const char *nodename, const char *servname,
1560 const struct evutil_addrinfo *hints_in,
1561 void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1563 if (dns_base && evdns_getaddrinfo_impl) {
1564 evdns_getaddrinfo_impl(
1565 dns_base, nodename, servname, hints_in, cb, arg);
1567 struct evutil_addrinfo *ai=NULL;
1569 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1576 evutil_gai_strerror(int err)
1578 /* As a sneaky side-benefit, this case statement will get most
1579 * compilers to tell us if any of the error codes we defined
1580 * conflict with the platform's native error codes. */
1582 case EVUTIL_EAI_CANCEL:
1583 return "Request canceled";
1587 case EVUTIL_EAI_ADDRFAMILY:
1588 return "address family for nodename not supported";
1589 case EVUTIL_EAI_AGAIN:
1590 return "temporary failure in name resolution";
1591 case EVUTIL_EAI_BADFLAGS:
1592 return "invalid value for ai_flags";
1593 case EVUTIL_EAI_FAIL:
1594 return "non-recoverable failure in name resolution";
1595 case EVUTIL_EAI_FAMILY:
1596 return "ai_family not supported";
1597 case EVUTIL_EAI_MEMORY:
1598 return "memory allocation failure";
1599 case EVUTIL_EAI_NODATA:
1600 return "no address associated with nodename";
1601 case EVUTIL_EAI_NONAME:
1602 return "nodename nor servname provided, or not known";
1603 case EVUTIL_EAI_SERVICE:
1604 return "servname not supported for ai_socktype";
1605 case EVUTIL_EAI_SOCKTYPE:
1606 return "ai_socktype not supported";
1607 case EVUTIL_EAI_SYSTEM:
1608 return "system error";
1610 #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1611 return gai_strerrorA(err);
1612 #elif defined(USE_NATIVE_GETADDRINFO)
1613 return gai_strerror(err);
1615 return "Unknown error code";
1621 /* destructively remove a trailing line terminator from s */
1626 if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
1628 if (len > 0 && s[len - 1] == '\r')
1633 /* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1634 * is supposed to return a string which is good indefinitely without having
1635 * to be freed. To make this work without leaking memory, we cache the
1636 * string the first time FormatMessage is called on a particular error
1637 * code, and then return the cached string on subsequent calls with the
1638 * same code. The strings aren't freed until libevent_global_shutdown
1639 * (or never). We use a linked list to cache the errors, because we
1640 * only expect there to be a few dozen, and that should be fast enough.
1643 struct cached_sock_errs_entry {
1644 HT_ENTRY(cached_sock_errs_entry) node;
1646 char *msg; /* allocated with LocalAlloc; free with LocalFree */
1649 static inline unsigned
1650 hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
1652 /* Use Murmur3's 32-bit finalizer as an integer hash function */
1663 eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
1664 const struct cached_sock_errs_entry *b)
1666 return a->code == b->code;
1669 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1670 static void *windows_socket_errors_lock_ = NULL;
1673 static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
1674 windows_socket_errors = HT_INITIALIZER();
1676 HT_PROTOTYPE(cached_sock_errs_map,
1677 cached_sock_errs_entry,
1679 hash_cached_sock_errs,
1680 eq_cached_sock_errs);
1682 HT_GENERATE(cached_sock_errs_map,
1683 cached_sock_errs_entry,
1685 hash_cached_sock_errs,
1686 eq_cached_sock_errs,
1692 /** Equivalent to strerror, but for windows socket errors. */
1694 evutil_socket_error_to_string(int errcode)
1696 struct cached_sock_errs_entry *errs, *newerr, find;
1699 EVLOCK_LOCK(windows_socket_errors_lock_, 0);
1701 find.code = errcode;
1702 errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
1708 if (0 != FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1709 FORMAT_MESSAGE_IGNORE_INSERTS |
1710 FORMAT_MESSAGE_ALLOCATE_BUFFER,
1711 NULL, errcode, 0, (LPTSTR)&msg, 0, NULL))
1712 chomp (msg); /* because message has trailing newline */
1715 /* use LocalAlloc because FormatMessage does */
1716 msg = LocalAlloc(LMEM_FIXED, len);
1718 msg = (char *)"LocalAlloc failed during Winsock error";
1721 evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
1724 newerr = (struct cached_sock_errs_entry *)
1725 mm_malloc(sizeof (struct cached_sock_errs_entry));
1729 msg = (char *)"malloc failed during Winsock error";
1733 newerr->code = errcode;
1735 HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
1738 EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
1743 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1745 evutil_global_setup_locks_(const int enable_locks)
1747 EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
1753 evutil_free_sock_err_globals(void)
1755 struct cached_sock_errs_entry **errs, *tofree;
1757 for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
1760 errs = HT_NEXT_RMV(cached_sock_errs_map,
1761 &windows_socket_errors,
1763 LocalFree(tofree->msg);
1767 HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
1769 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1770 if (windows_socket_errors_lock_ != NULL) {
1771 EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
1772 windows_socket_errors_lock_ = NULL;
1779 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1781 evutil_global_setup_locks_(const int enable_locks)
1788 evutil_free_sock_err_globals(void)
1795 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
1799 va_start(ap, format);
1800 r = evutil_vsnprintf(buf, buflen, format, ap);
1806 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
1811 #if defined(_MSC_VER) || defined(_WIN32)
1812 r = _vsnprintf(buf, buflen, format, ap);
1814 r = _vscprintf(format, ap);
1816 /* Make sure we always use the correct vsnprintf on IRIX */
1817 extern int _xpg5_vsnprintf(char * __restrict,
1818 __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
1819 const char * __restrict, /* va_list */ char *);
1821 r = _xpg5_vsnprintf(buf, buflen, format, ap);
1823 r = vsnprintf(buf, buflen, format, ap);
1825 buf[buflen-1] = '\0';
1829 #define USE_INTERNAL_NTOP
1830 #define USE_INTERNAL_PTON
1833 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
1835 #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1836 return inet_ntop(af, src, dst, len);
1838 if (af == AF_INET) {
1839 const struct in_addr *in = src;
1840 const ev_uint32_t a = ntohl(in->s_addr);
1842 r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
1843 (int)(ev_uint8_t)((a>>24)&0xff),
1844 (int)(ev_uint8_t)((a>>16)&0xff),
1845 (int)(ev_uint8_t)((a>>8 )&0xff),
1846 (int)(ev_uint8_t)((a )&0xff));
1847 if (r<0||(size_t)r>=len)
1852 } else if (af == AF_INET6) {
1853 const struct in6_addr *addr = src;
1855 int longestGapLen = 0, longestGapPos = -1, i,
1856 curGapPos = -1, curGapLen = 0;
1857 ev_uint16_t words[8];
1858 for (i = 0; i < 8; ++i) {
1860 (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1862 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1863 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1864 (words[5] == 0xffff))) {
1865 /* This is an IPv4 address. */
1866 if (words[5] == 0) {
1867 evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1868 addr->s6_addr[12], addr->s6_addr[13],
1869 addr->s6_addr[14], addr->s6_addr[15]);
1871 evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1872 addr->s6_addr[12], addr->s6_addr[13],
1873 addr->s6_addr[14], addr->s6_addr[15]);
1875 if (strlen(buf) > len)
1877 strlcpy(dst, buf, len);
1882 if (words[i] == 0) {
1885 while (i<8 && words[i] == 0) {
1888 if (curGapLen > longestGapLen) {
1889 longestGapPos = curGapPos;
1890 longestGapLen = curGapLen;
1896 if (longestGapLen<=1)
1900 for (i = 0; i < 8; ++i) {
1901 if (words[i] == 0 && longestGapPos == i) {
1905 while (i < 8 && words[i] == 0)
1907 --i; /* to compensate for loop increment. */
1910 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1917 if (strlen(buf) > len)
1919 strlcpy(dst, buf, len);
1929 evutil_inet_pton(int af, const char *src, void *dst)
1931 #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1932 return inet_pton(af, src, dst);
1934 if (af == AF_INET) {
1937 struct in_addr *addr = dst;
1938 if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
1940 if (a > 255) return 0;
1941 if (b > 255) return 0;
1942 if (c > 255) return 0;
1943 if (d > 255) return 0;
1944 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1947 } else if (af == AF_INET6) {
1948 struct in6_addr *out = dst;
1949 ev_uint16_t words[8];
1950 int gapPos = -1, i, setWords=0;
1951 const char *dot = strchr(src, '.');
1952 const char *eow; /* end of words. */
1956 eow = src+strlen(src);
1958 unsigned byte1,byte2,byte3,byte4;
1960 for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
1964 /* We use "scanf" because some platform inet_aton()s are too lax
1965 * about IPv4 addresses of the form "1.2.3" */
1966 if (sscanf(eow, "%u.%u.%u.%u%c",
1967 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1976 words[6] = (byte1<<8) | byte2;
1977 words[7] = (byte3<<8) | byte4;
1985 if (EVUTIL_ISXDIGIT_(*src)) {
1987 long r = strtol(src, &next, 16);
1995 words[i++] = (ev_uint16_t)r;
1998 if (*src != ':' && src != eow)
2001 } else if (*src == ':' && i > 0 && gapPos==-1) {
2004 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
2013 (setWords == 8 && gapPos != -1) ||
2014 (setWords < 8 && gapPos == -1))
2018 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2019 int gapLen = 8 - setWords;
2020 /* assert(nToMove >= 0); */
2022 return -1; /* should be impossible */
2023 memmove(&words[gapPos+gapLen], &words[gapPos],
2024 sizeof(ev_uint16_t)*nToMove);
2025 memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
2027 for (i = 0; i < 8; ++i) {
2028 out->s6_addr[2*i ] = words[i] >> 8;
2029 out->s6_addr[2*i+1] = words[i] & 0xff;
2041 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
2045 const char *cp, *addr_part, *port_part;
2047 /* recognized formats are:
2055 cp = strchr(ip_as_string, ':');
2056 if (*ip_as_string == '[') {
2058 if (!(cp = strchr(ip_as_string, ']'))) {
2061 len = (int) ( cp-(ip_as_string + 1) );
2062 if (len > (int)sizeof(buf)-1) {
2065 memcpy(buf, ip_as_string+1, len);
2073 } else if (cp && strchr(cp+1, ':')) {
2075 addr_part = ip_as_string;
2079 if (cp - ip_as_string > (int)sizeof(buf)-1) {
2082 memcpy(buf, ip_as_string, cp-ip_as_string);
2083 buf[cp-ip_as_string] = '\0';
2087 addr_part = ip_as_string;
2092 if (port_part == NULL) {
2095 port = atoi(port_part);
2096 if (port <= 0 || port > 65535) {
2102 return -1; /* Should be impossible. */
2106 struct sockaddr_in6 sin6;
2107 memset(&sin6, 0, sizeof(sin6));
2108 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2109 sin6.sin6_len = sizeof(sin6);
2111 sin6.sin6_family = AF_INET6;
2112 sin6.sin6_port = htons(port);
2113 if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
2115 if ((int)sizeof(sin6) > *outlen)
2117 memset(out, 0, *outlen);
2118 memcpy(out, &sin6, sizeof(sin6));
2119 *outlen = sizeof(sin6);
2125 struct sockaddr_in sin;
2126 memset(&sin, 0, sizeof(sin));
2127 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2128 sin.sin_len = sizeof(sin);
2130 sin.sin_family = AF_INET;
2131 sin.sin_port = htons(port);
2132 if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
2134 if ((int)sizeof(sin) > *outlen)
2136 memset(out, 0, *outlen);
2137 memcpy(out, &sin, sizeof(sin));
2138 *outlen = sizeof(sin);
2144 evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
2147 const char *res=NULL;
2149 if (sa->sa_family == AF_INET) {
2150 const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
2151 res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
2152 port = ntohs(sin->sin_port);
2154 evutil_snprintf(out, outlen, "%s:%d", b, port);
2157 } else if (sa->sa_family == AF_INET6) {
2158 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
2159 res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
2160 port = ntohs(sin6->sin6_port);
2162 evutil_snprintf(out, outlen, "[%s]:%d", b, port);
2167 evutil_snprintf(out, outlen, "<addr with socktype %d>",
2168 (int)sa->sa_family);
2173 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
2177 if (0 != (r = (sa1->sa_family - sa2->sa_family)))
2180 if (sa1->sa_family == AF_INET) {
2181 const struct sockaddr_in *sin1, *sin2;
2182 sin1 = (const struct sockaddr_in *)sa1;
2183 sin2 = (const struct sockaddr_in *)sa2;
2184 if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
2186 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
2188 else if (include_port &&
2189 (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
2195 else if (sa1->sa_family == AF_INET6) {
2196 const struct sockaddr_in6 *sin1, *sin2;
2197 sin1 = (const struct sockaddr_in6 *)sa1;
2198 sin2 = (const struct sockaddr_in6 *)sa2;
2199 if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
2201 else if (include_port &&
2202 (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
2211 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
2212 * has 256 bits to look up whether a character is in some set or not. This
2213 * fails on non-ASCII platforms, but so does every other place where we
2214 * take a char and write it onto the network.
2216 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
2217 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2218 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
2219 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2220 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2221 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
2222 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2223 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2224 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
2225 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2226 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2227 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2228 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
2230 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
2231 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2232 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2233 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2234 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2235 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2236 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2237 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2238 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2239 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2240 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2241 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2242 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2243 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2244 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2245 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2246 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2248 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
2249 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2250 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2251 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2252 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2253 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2254 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2255 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2256 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2257 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2258 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2259 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2260 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2261 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2262 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2263 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2264 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2267 #define IMPL_CTYPE_FN(name) \
2268 int EVUTIL_##name##_(char c) { \
2270 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
2272 IMPL_CTYPE_FN(ISALPHA)
2273 IMPL_CTYPE_FN(ISALNUM)
2274 IMPL_CTYPE_FN(ISSPACE)
2275 IMPL_CTYPE_FN(ISDIGIT)
2276 IMPL_CTYPE_FN(ISXDIGIT)
2277 IMPL_CTYPE_FN(ISPRINT)
2278 IMPL_CTYPE_FN(ISLOWER)
2279 IMPL_CTYPE_FN(ISUPPER)
2281 char EVUTIL_TOLOWER_(char c)
2283 return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2285 char EVUTIL_TOUPPER_(char c)
2287 return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2290 evutil_ascii_strcasecmp(const char *s1, const char *s2)
2294 c1 = EVUTIL_TOLOWER_(*s1++);
2295 c2 = EVUTIL_TOLOWER_(*s2++);
2304 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2308 c1 = EVUTIL_TOLOWER_(*s1++);
2309 c2 = EVUTIL_TOLOWER_(*s2++);
2321 evutil_rtrim_lws_(char *str)
2328 if ((cp = strchr(str, '\0')) == NULL || (cp == str))
2333 while (*cp == ' ' || *cp == '\t') {
2342 evutil_issetugid(void)
2344 #ifdef EVENT__HAVE_ISSETUGID
2348 #ifdef EVENT__HAVE_GETEUID
2349 if (getuid() != geteuid())
2352 #ifdef EVENT__HAVE_GETEGID
2353 if (getgid() != getegid())
2361 evutil_getenv_(const char *varname)
2363 if (evutil_issetugid())
2366 return getenv(varname);
2370 evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
2374 evutil_gettimeofday(&tv, NULL);
2375 seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
2377 seed += (ev_uint32_t) _getpid();
2379 seed += (ev_uint32_t) getpid();
2387 evutil_weakrand_(struct evutil_weakrand_state *state)
2389 /* This RNG implementation is a linear congruential generator, with
2390 * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
2391 * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2393 * The linear congruential generator is not an industrial-strength
2394 * RNG! It's fast, but it can have higher-order patterns. Notably,
2395 * the low bits tend to have periodicity.
2397 state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
2398 return (ev_int32_t)(state->seed);
2402 evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
2404 ev_int32_t divisor, result;
2406 /* We can't just do weakrand() % top, since the low bits of the LCG
2407 * are less random than the high ones. (Specifically, since the LCG
2408 * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2409 * therefore the low m bits of the LCG will have period 2^m.) */
2410 divisor = EVUTIL_WEAKRAND_MAX / top;
2412 result = evutil_weakrand_(state) / divisor;
2413 } while (result >= top);
2418 * Volatile pointer to memset: we use this to keep the compiler from
2419 * eliminating our call to memset.
2421 void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
2424 evutil_memclear_(void *mem, size_t len)
2426 evutil_memset_volatile_(mem, 0, len);
2430 evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
2432 static const char LOOPBACK_S6[16] =
2433 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2434 if (addr->sa_family == AF_INET) {
2435 struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2436 return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2437 } else if (addr->sa_family == AF_INET6) {
2438 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2439 return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2445 evutil_hex_char_to_int_(char c)
2459 case 'A': case 'a': return 10;
2460 case 'B': case 'b': return 11;
2461 case 'C': case 'c': return 12;
2462 case 'D': case 'd': return 13;
2463 case 'E': case 'e': return 14;
2464 case 'F': case 'f': return 15;
2471 evutil_load_windows_system_library_(const TCHAR *library_name)
2473 TCHAR path[MAX_PATH];
2475 n = GetSystemDirectory(path, MAX_PATH);
2476 if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2478 _tcscat(path, TEXT("\\"));
2479 _tcscat(path, library_name);
2480 return LoadLibrary(path);
2484 /* Internal wrapper around 'socket' to provide Linux-style support for
2485 * syscall-saving methods where available.
2487 * In addition to regular socket behavior, you can use a bitwise or to set the
2488 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2489 * to make the socket nonblocking or close-on-exec with as few syscalls as
2493 evutil_socket_(int domain, int type, int protocol)
2496 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2497 r = socket(domain, type, protocol);
2500 else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
2503 #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2504 r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
2507 if (type & EVUTIL_SOCK_NONBLOCK) {
2508 if (evutil_fast_socket_nonblocking(r) < 0) {
2509 evutil_closesocket(r);
2513 if (type & EVUTIL_SOCK_CLOEXEC) {
2514 if (evutil_fast_socket_closeonexec(r) < 0) {
2515 evutil_closesocket(r);
2522 /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2523 * support for syscall-saving methods where available.
2525 * In addition to regular accept behavior, you can set one or more of flags
2526 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2527 * make the socket nonblocking or close-on-exec with as few syscalls as
2531 evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
2532 ev_socklen_t *addrlen, int flags)
2534 evutil_socket_t result;
2535 #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2536 result = accept4(sockfd, addr, addrlen, flags);
2537 if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
2538 /* A nonnegative result means that we succeeded, so return.
2539 * Failing with EINVAL means that an option wasn't supported,
2540 * and failing with ENOSYS means that the syscall wasn't
2541 * there: in those cases we want to fall back. Otherwise, we
2542 * got a real error, and we should return. */
2546 result = accept(sockfd, addr, addrlen);
2550 if (flags & EVUTIL_SOCK_CLOEXEC) {
2551 if (evutil_fast_socket_closeonexec(result) < 0) {
2552 evutil_closesocket(result);
2556 if (flags & EVUTIL_SOCK_NONBLOCK) {
2557 if (evutil_fast_socket_nonblocking(result) < 0) {
2558 evutil_closesocket(result);
2565 /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2566 * fd[0] get read from fd[1]. Make both fds nonblocking and close-on-exec.
2567 * Return 0 on success, -1 on failure.
2570 evutil_make_internal_pipe_(evutil_socket_t fd[2])
2573 Making the second socket nonblocking is a bit subtle, given that we
2574 ignore any EAGAIN returns when writing to it, and you don't usally
2575 do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2576 then there's no need to add any more data to the buffer, since
2577 the main thread is already either about to wake up and drain it,
2578 or woken up and in the process of draining it.
2581 #if defined(EVENT__HAVE_PIPE2)
2582 if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
2585 #if defined(EVENT__HAVE_PIPE)
2586 if (pipe(fd) == 0) {
2587 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2588 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2589 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2590 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2598 event_warn("%s: pipe", __func__);
2603 #define LOCAL_SOCKETPAIR_AF AF_INET
2605 #define LOCAL_SOCKETPAIR_AF AF_UNIX
2607 if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
2608 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2609 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2610 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2611 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2612 evutil_closesocket(fd[0]);
2613 evutil_closesocket(fd[1]);
2623 /* Wrapper around eventfd on systems that provide it. Unlike the system
2624 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2625 * flags. Returns -1 on error or if eventfd is not supported.
2628 evutil_eventfd_(unsigned initval, int flags)
2630 #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
2632 #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
2633 r = eventfd(initval, flags);
2634 if (r >= 0 || flags == 0)
2637 r = eventfd(initval, 0);
2640 if (flags & EVUTIL_EFD_CLOEXEC) {
2641 if (evutil_fast_socket_closeonexec(r) < 0) {
2642 evutil_closesocket(r);
2646 if (flags & EVUTIL_EFD_NONBLOCK) {
2647 if (evutil_fast_socket_nonblocking(r) < 0) {
2648 evutil_closesocket(r);
2659 evutil_free_globals_(void)
2661 evutil_free_secure_rng_globals_();
2662 evutil_free_sock_err_globals();