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 #ifdef EVENT__HAVE_AFUNIX_H
37 #define WIN32_LEAN_AND_MEAN
39 #undef WIN32_LEAN_AND_MEAN
44 /* For structs needed by GetAdaptersAddresses */
45 #define _WIN32_WINNT 0x0501
50 #include <sys/types.h>
51 #ifdef EVENT__HAVE_SYS_SOCKET_H
52 #include <sys/socket.h>
54 #ifdef EVENT__HAVE_UNISTD_H
57 #ifdef EVENT__HAVE_FCNTL_H
60 #ifdef EVENT__HAVE_STDLIB_H
67 #ifdef EVENT__HAVE_NETINET_IN_H
68 #include <netinet/in.h>
70 #ifdef EVENT__HAVE_NETINET_IN6_H
71 #include <netinet/in6.h>
73 #ifdef EVENT__HAVE_NETINET_TCP_H
74 #include <netinet/tcp.h>
76 #ifdef EVENT__HAVE_ARPA_INET_H
77 #include <arpa/inet.h>
84 #ifdef EVENT__HAVE_IFADDRS_H
88 #include "event2/util.h"
89 #include "util-internal.h"
90 #include "log-internal.h"
91 #include "mm-internal.h"
92 #include "evthread-internal.h"
94 #include "strlcpy-internal.h"
95 #include "ipv6-internal.h"
98 #define HT_NO_CACHE_HASH_VALUES
99 #include "ht-internal.h"
104 #define fstat _fstati64
107 #define stat _stati64
113 #define O_RDONLY _O_RDONLY
116 #ifdef EVENT__HAVE_AFUNIX_H
117 int have_working_afunix_ = -1;
121 evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
126 fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
127 if (fd >= 0 || errno == EINVAL)
129 /* If we got an EINVAL, fall through and try without O_CLOEXEC */
131 fd = open(pathname, flags, (mode_t)mode);
135 #if defined(FD_CLOEXEC)
136 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
146 Read the contents of 'filename' into a newly allocated NUL-terminated
147 string. Set *content_out to hold this string, and *len_out to hold its
148 length (not including the appended NUL). If 'is_binary', open the file in
151 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
153 Used internally only; may go away in a future version.
156 evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
162 size_t read_so_far=0;
165 EVUTIL_ASSERT(content_out);
166 EVUTIL_ASSERT(len_out);
175 fd = evutil_open_closeonexec_(filename, mode, 0);
178 if (fstat(fd, &st) || st.st_size < 0 ||
179 st.st_size > EV_SSIZE_MAX-1 ) {
183 mem = mm_malloc((size_t)st.st_size + 1);
190 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
192 #define N_TO_READ(x) (x)
194 while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
196 if (read_so_far >= (size_t)st.st_size)
198 EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
205 mem[read_so_far] = 0;
207 *len_out = read_so_far;
215 create_tmpfile(char tmpfile[MAX_PATH])
217 char short_path[MAX_PATH] = {0};
218 char long_path[MAX_PATH] = {0};
219 char prefix[4] = {0};
220 // GetTempFileNameA() uses up to the first three characters of the prefix
221 // and windows filesystems are case-insensitive
222 const char *base32set = "abcdefghijklmnopqrstuvwxyz012345";
225 evutil_secure_rng_get_bytes(&rnd, sizeof(rnd));
226 prefix[0] = base32set[(rnd ) & 31];
227 prefix[1] = base32set[(rnd >> 5) & 31];
228 prefix[2] = base32set[(rnd >> 10) & 31];
231 GetTempPathA(MAX_PATH, short_path);
232 GetLongPathNameA(short_path, long_path, MAX_PATH);
233 if (!GetTempFileNameA(long_path, prefix, 0, tmpfile)) {
234 event_warnx("GetTempFileName failed: %d", EVUTIL_SOCKET_ERROR());
240 #ifdef EVENT__HAVE_AFUNIX_H
241 /* Test whether Unix domain socket works.
242 * Return 1 if it works, otherwise 0 */
244 evutil_check_working_afunix_()
246 /* Windows 10 began to support Unix domain socket. Let's just try
247 * socket(AF_UNIX, , ) and fall back to socket(AF_INET, , ).
248 * https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/
250 evutil_socket_t sd = -1;
251 if (have_working_afunix_ < 0) {
252 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
253 have_working_afunix_ = 0;
255 have_working_afunix_ = 1;
256 evutil_closesocket(sd);
259 return have_working_afunix_;
262 /* XXX Copy from evutil_ersatz_socketpair_() */
264 evutil_win_socketpair_afunix(int family, int type, int protocol,
265 evutil_socket_t fd[2])
267 #define ERR(e) WSA##e
268 evutil_socket_t listener = -1;
269 evutil_socket_t connector = -1;
270 evutil_socket_t acceptor = -1;
272 struct sockaddr_un listen_addr;
273 struct sockaddr_un connect_addr;
274 char tmp_file[MAX_PATH] = {0};
277 int saved_errno = -1;
280 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
284 listener = socket(family, type, 0);
287 memset(&listen_addr, 0, sizeof(listen_addr));
289 if (create_tmpfile(tmp_file)) {
290 goto tidy_up_and_fail;
292 DeleteFileA(tmp_file);
293 listen_addr.sun_family = AF_UNIX;
294 if (strlcpy(listen_addr.sun_path, tmp_file, UNIX_PATH_MAX) >=
296 event_warnx("Temp file name is too long");
297 goto tidy_up_and_fail;
300 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
302 goto tidy_up_and_fail;
303 if (listen(listener, 1) == -1)
304 goto tidy_up_and_fail;
306 connector = socket(family, type, 0);
308 goto tidy_up_and_fail;
310 memset(&connect_addr, 0, sizeof(connect_addr));
312 /* We want to find out the port number to connect to. */
313 size = sizeof(connect_addr);
314 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
315 goto tidy_up_and_fail;
317 if (connect(connector, (struct sockaddr *) &connect_addr,
318 sizeof(connect_addr)) == -1)
319 goto tidy_up_and_fail;
321 size = sizeof(listen_addr);
322 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
324 goto tidy_up_and_fail;
325 if (size != sizeof(listen_addr))
326 goto abort_tidy_up_and_fail;
327 /* Now check we are talking to ourself by matching port and host on the
329 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
330 goto tidy_up_and_fail;
332 if (size != sizeof(connect_addr) ||
333 listen_addr.sun_family != connect_addr.sun_family ||
334 evutil_ascii_strcasecmp(listen_addr.sun_path, connect_addr.sun_path))
335 goto abort_tidy_up_and_fail;
337 evutil_closesocket(listener);
343 abort_tidy_up_and_fail:
344 saved_errno = ERR(ECONNABORTED);
347 saved_errno = EVUTIL_SOCKET_ERROR();
349 evutil_closesocket(listener);
351 evutil_closesocket(connector);
353 evutil_closesocket(acceptor);
355 DeleteFileA(tmp_file);
357 EVUTIL_SET_SOCKET_ERROR(saved_errno);
364 evutil_win_socketpair(int family, int type, int protocol,
365 evutil_socket_t fd[2])
367 #ifdef EVENT__HAVE_AFUNIX_H
368 /* The family only support AF_UNIX and AF_INET */
369 if (protocol || (family != AF_UNIX && family != AF_INET)) {
370 EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
373 if (evutil_check_working_afunix_()) {
374 /* If the AF_UNIX socket works, we will change the family to
375 * AF_UNIX forcely. */
377 if (type != SOCK_STREAM) {
378 /* Win10 does not support AF_UNIX socket of a type other
379 * than SOCK_STREAM still now. */
380 EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
384 /* If the AF_UNIX socket does not work, we will change the
385 * family to AF_INET forcely. */
388 if (family == AF_UNIX)
389 return evutil_win_socketpair_afunix(family, type, protocol, fd);
392 return evutil_ersatz_socketpair_(family, type, protocol, fd);
397 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
400 return socketpair(family, type, protocol, fd);
402 return evutil_win_socketpair(family, type, protocol, fd);
407 evutil_ersatz_socketpair_(int family, int type, int protocol,
408 evutil_socket_t fd[2])
410 /* This code is originally from Tor. Used with permission. */
412 /* This socketpair does not work when localhost is down. So
413 * it's really not the same thing at all. But it's close enough
414 * for now, and really, when localhost is down sometimes, we
415 * have other problems too.
418 #define ERR(e) WSA##e
422 evutil_socket_t listener = -1;
423 evutil_socket_t connector = -1;
424 evutil_socket_t acceptor = -1;
425 struct sockaddr_in listen_addr;
426 struct sockaddr_in connect_addr;
428 int saved_errno = -1;
431 family_test = family != AF_INET;
433 family_test = family_test && (family != AF_UNIX);
435 if (protocol || family_test) {
436 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
441 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
445 listener = socket(AF_INET, type, 0);
448 memset(&listen_addr, 0, sizeof(listen_addr));
449 listen_addr.sin_family = AF_INET;
450 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
451 listen_addr.sin_port = 0; /* kernel chooses port. */
452 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
454 goto tidy_up_and_fail;
455 if (listen(listener, 1) == -1)
456 goto tidy_up_and_fail;
458 connector = socket(AF_INET, type, 0);
460 goto tidy_up_and_fail;
462 memset(&connect_addr, 0, sizeof(connect_addr));
464 /* We want to find out the port number to connect to. */
465 size = sizeof(connect_addr);
466 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
467 goto tidy_up_and_fail;
468 if (size != sizeof (connect_addr))
469 goto abort_tidy_up_and_fail;
470 if (connect(connector, (struct sockaddr *) &connect_addr,
471 sizeof(connect_addr)) == -1)
472 goto tidy_up_and_fail;
474 size = sizeof(listen_addr);
475 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
477 goto tidy_up_and_fail;
478 if (size != sizeof(listen_addr))
479 goto abort_tidy_up_and_fail;
480 /* Now check we are talking to ourself by matching port and host on the
482 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
483 goto tidy_up_and_fail;
484 if (size != sizeof (connect_addr)
485 || listen_addr.sin_family != connect_addr.sin_family
486 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
487 || listen_addr.sin_port != connect_addr.sin_port)
488 goto abort_tidy_up_and_fail;
489 evutil_closesocket(listener);
495 abort_tidy_up_and_fail:
496 saved_errno = ERR(ECONNABORTED);
499 saved_errno = EVUTIL_SOCKET_ERROR();
501 evutil_closesocket(listener);
503 evutil_closesocket(connector);
505 evutil_closesocket(acceptor);
507 EVUTIL_SET_SOCKET_ERROR(saved_errno);
513 evutil_make_socket_nonblocking(evutil_socket_t fd)
517 unsigned long nonblocking = 1;
518 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
519 event_sock_warn(fd, "ioctlsocket(%d, FIONBIO, &%lu)", (int)fd, (unsigned long)nonblocking);
526 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
527 event_warn("fcntl(%d, F_GETFL)", fd);
530 if (!(flags & O_NONBLOCK)) {
531 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
532 event_warn("fcntl(%d, F_SETFL)", fd);
541 /* Faster version of evutil_make_socket_nonblocking for internal use.
543 * Requires that no F_SETFL flags were previously set on the fd.
546 evutil_fast_socket_nonblocking(evutil_socket_t fd)
549 return evutil_make_socket_nonblocking(fd);
551 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
552 event_warn("fcntl(%d, F_SETFL)", fd);
560 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
562 #if defined(SO_REUSEADDR) && !defined(_WIN32)
564 /* REUSEADDR on Unix means, "don't hang on to this address after the
565 * listener is closed." On Windows, though, it means "don't keep other
566 * processes from binding to this address while we're using it. */
567 return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
568 (ev_socklen_t)sizeof(one));
575 evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
577 #if defined __linux__ && defined(SO_REUSEPORT)
579 /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
580 * threads) can bind to the same port if they each set the option. */
581 return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
582 (ev_socklen_t)sizeof(one));
589 evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
591 #if defined(IPV6_V6ONLY)
593 return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
594 (ev_socklen_t)sizeof(one));
600 evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
602 #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
605 /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
606 * has arrived and ready to read */
607 return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
608 (ev_socklen_t)sizeof(one));
614 evutil_make_socket_closeonexec(evutil_socket_t fd)
616 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
618 if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
619 event_warn("fcntl(%d, F_GETFD)", fd);
622 if (!(flags & FD_CLOEXEC)) {
623 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
624 event_warn("fcntl(%d, F_SETFD)", fd);
632 /* Faster version of evutil_make_socket_closeonexec for internal use.
634 * Requires that no F_SETFD flags were previously set on the fd.
637 evutil_fast_socket_closeonexec(evutil_socket_t fd)
639 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
640 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
641 event_warn("fcntl(%d, F_SETFD)", fd);
649 evutil_closesocket(evutil_socket_t sock)
654 return closesocket(sock);
659 evutil_strtoll(const char *s, char **endptr, int base)
661 #ifdef EVENT__HAVE_STRTOLL
662 return (ev_int64_t)strtoll(s, endptr, base);
663 #elif EVENT__SIZEOF_LONG == 8
664 return (ev_int64_t)strtol(s, endptr, base);
665 #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
666 /* XXXX on old versions of MS APIs, we only support base
671 r = (ev_int64_t) _atoi64(s);
681 #elif defined(_WIN32)
682 return (ev_int64_t) _strtoi64(s, endptr, base);
683 #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
686 if (base != 10 && base != 16)
689 n = sscanf(s, "%lld", &r);
691 unsigned long long ru=0;
692 n = sscanf(s, "%llx", &ru);
693 if (ru > EV_INT64_MAX)
699 while (EVUTIL_ISSPACE_(*s))
704 while (EVUTIL_ISDIGIT_(*s))
707 while (EVUTIL_ISXDIGIT_(*s))
714 #error "I don't know how to parse 64-bit integers."
720 evutil_socket_geterror(evutil_socket_t sock)
722 int optval, optvallen=sizeof(optval);
723 int err = WSAGetLastError();
724 if (err == WSAEWOULDBLOCK && sock >= 0) {
725 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
735 /* XXX we should use an enum here. */
736 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
738 evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
743 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
746 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
751 if (connect(*fd_ptr, sa, socklen) < 0) {
752 int e = evutil_socket_geterror(*fd_ptr);
753 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
755 if (EVUTIL_ERR_CONNECT_REFUSED(e))
764 evutil_closesocket(*fd_ptr);
770 /* Check whether a socket on which we called connect() is done
771 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
772 error case, set the current socket errno to the error that happened during
773 the connect operation. */
775 evutil_socket_finished_connecting_(evutil_socket_t fd)
778 ev_socklen_t elen = sizeof(e);
780 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
784 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
786 EVUTIL_SET_SOCKET_ERROR(e);
793 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
794 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
795 EVUTIL_AI_ADDRCONFIG) != \
796 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
797 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
798 EVUTIL_AI_ADDRCONFIG)
799 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
802 /* We sometimes need to know whether we have an ipv4 address and whether we
803 have an ipv6 address. If 'have_checked_interfaces', then we've already done
804 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
805 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
806 set by evutil_check_interfaces. */
807 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
809 /* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
810 static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
811 { return addr>>24 == 127; }
813 /* True iff the IPv4 address 'addr', in host order, is link-local
814 * 169.254.0.0/16 (RFC3927) */
815 static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
816 { return ((addr & 0xffff0000U) == 0xa9fe0000U); }
818 /* True iff the IPv4 address 'addr', in host order, is a class D
819 * (multiclass) address. */
820 static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
821 { return ((addr>>24) & 0xf0) == 0xe0; }
824 evutil_v4addr_is_local_(const struct in_addr *in)
826 const ev_uint32_t addr = ntohl(in->s_addr);
827 return addr == INADDR_ANY ||
828 evutil_v4addr_is_localhost(addr) ||
829 evutil_v4addr_is_linklocal(addr) ||
830 evutil_v4addr_is_classd(addr);
833 evutil_v6addr_is_local_(const struct in6_addr *in)
835 static const char ZEROES[] =
836 "\x00\x00\x00\x00\x00\x00\x00\x00"
837 "\x00\x00\x00\x00\x00\x00\x00\x00";
839 const unsigned char *addr = (const unsigned char *)in->s6_addr;
840 return !memcmp(addr, ZEROES, 8) ||
841 ((addr[0] & 0xfe) == 0xfc) ||
842 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
843 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
848 evutil_found_ifaddr(const struct sockaddr *sa)
850 if (sa->sa_family == AF_INET) {
851 const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
852 if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
853 event_debug(("Detected an IPv4 interface"));
854 had_ipv4_address = 1;
856 } else if (sa->sa_family == AF_INET6) {
857 const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
858 if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
859 event_debug(("Detected an IPv6 interface"));
860 had_ipv6_address = 1;
866 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
867 ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
871 evutil_check_ifaddrs(void)
873 #if defined(EVENT__HAVE_GETIFADDRS)
874 /* Most free Unixy systems provide getifaddrs, which gives us a linked list
875 * of struct ifaddrs. */
876 struct ifaddrs *ifa = NULL;
877 const struct ifaddrs *i;
878 if (getifaddrs(&ifa) < 0) {
879 event_warn("Unable to call getifaddrs()");
883 for (i = ifa; i; i = i->ifa_next) {
886 evutil_found_ifaddr(i->ifa_addr);
891 #elif defined(_WIN32)
892 /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
893 "GetAdaptersInfo", but that's deprecated; let's just try
894 GetAdaptersAddresses and fall back to connect+getsockname.
896 HMODULE lib = evutil_load_windows_system_library_(TEXT("iphlpapi.dll"));
897 GetAdaptersAddresses_fn_t fn;
899 IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
902 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
903 GAA_FLAG_SKIP_MULTICAST | \
904 GAA_FLAG_SKIP_DNS_SERVER)
909 if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
912 /* Guess how much space we need. */
914 addresses = mm_malloc(size);
917 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
918 if (res == ERROR_BUFFER_OVERFLOW) {
919 /* we didn't guess that we needed enough space; try again */
921 addresses = mm_malloc(size);
924 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
929 for (address = addresses; address; address = address->Next) {
930 IP_ADAPTER_UNICAST_ADDRESS *a;
931 for (a = address->FirstUnicastAddress; a; a = a->Next) {
932 /* Yes, it's a linked list inside a linked list */
933 struct sockaddr *sa = a->Address.lpSockaddr;
934 evutil_found_ifaddr(sa);
950 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
951 * the test seemed successful. */
953 evutil_check_interfaces(void)
955 evutil_socket_t fd = -1;
956 struct sockaddr_in sin, sin_out;
957 struct sockaddr_in6 sin6, sin6_out;
958 ev_socklen_t sin_out_len = sizeof(sin_out);
959 ev_socklen_t sin6_out_len = sizeof(sin6_out);
961 if (have_checked_interfaces)
964 /* From this point on we have done the ipv4/ipv6 interface check */
965 have_checked_interfaces = 1;
967 if (evutil_check_ifaddrs() == 0) {
968 /* Use a nice sane interface, if this system has one. */
972 /* Ugh. There was no nice sane interface. So to check whether we have
973 * an interface open for a given protocol, will try to make a UDP
974 * 'connection' to a remote host on the internet. We don't actually
975 * use it, so the address doesn't matter, but we want to pick one that
976 * keep us from using a host- or link-local interface. */
977 memset(&sin, 0, sizeof(sin));
978 sin.sin_family = AF_INET;
979 sin.sin_port = htons(53);
980 r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
983 memset(&sin6, 0, sizeof(sin6));
984 sin6.sin6_family = AF_INET6;
985 sin6.sin6_port = htons(53);
986 r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
989 memset(&sin_out, 0, sizeof(sin_out));
990 memset(&sin6_out, 0, sizeof(sin6_out));
992 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
993 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
994 connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
995 getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
996 /* We might have an IPv4 interface. */
997 evutil_found_ifaddr((struct sockaddr*) &sin_out);
1000 evutil_closesocket(fd);
1002 if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
1003 connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
1004 getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
1005 /* We might have an IPv6 interface. */
1006 evutil_found_ifaddr((struct sockaddr*) &sin6_out);
1010 evutil_closesocket(fd);
1015 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
1016 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
1017 * it, and we should trust what they said.
1019 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
1021 /* Helper: construct a new addrinfo containing the socket address in
1022 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
1023 * socktype and protocol info from hints. If they weren't set, then
1024 * allocate both a TCP and a UDP addrinfo.
1026 struct evutil_addrinfo *
1027 evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
1028 const struct evutil_addrinfo *hints)
1030 struct evutil_addrinfo *res;
1031 EVUTIL_ASSERT(hints);
1033 if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
1034 /* Indecisive user! Give them a UDP and a TCP. */
1035 struct evutil_addrinfo *r1, *r2;
1036 struct evutil_addrinfo tmp;
1037 memcpy(&tmp, hints, sizeof(tmp));
1038 tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
1039 r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
1042 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
1043 r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
1045 evutil_freeaddrinfo(r1);
1052 /* We're going to allocate extra space to hold the sockaddr. */
1053 res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
1056 res->ai_addr = (struct sockaddr*)
1057 (((char*)res) + sizeof(struct evutil_addrinfo));
1058 memcpy(res->ai_addr, sa, socklen);
1059 res->ai_addrlen = socklen;
1060 res->ai_family = sa->sa_family; /* Same or not? XXX */
1061 res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
1062 res->ai_socktype = hints->ai_socktype;
1063 res->ai_protocol = hints->ai_protocol;
1068 /* Append the addrinfo 'append' to the end of 'first', and return the start of
1069 * the list. Either element can be NULL, in which case we return the element
1070 * that is not NULL. */
1071 struct evutil_addrinfo *
1072 evutil_addrinfo_append_(struct evutil_addrinfo *first,
1073 struct evutil_addrinfo *append)
1075 struct evutil_addrinfo *ai = first;
1080 ai->ai_next = append;
1086 parse_numeric_servname(const char *servname)
1090 n = (int) strtol(servname, &endptr, 10);
1091 if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
1097 /** Parse a service name in 'servname', which can be a decimal port.
1098 * Return the port number, or -1 on error.
1101 evutil_parse_servname(const char *servname, const char *protocol,
1102 const struct evutil_addrinfo *hints)
1104 int n = parse_numeric_servname(servname);
1107 #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
1108 if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
1109 struct servent *ent = getservbyname(servname, protocol);
1111 return ntohs(ent->s_port);
1118 /* Return a string corresponding to a protocol number that we can pass to
1121 evutil_unparse_protoname(int proto)
1135 #ifdef EVENT__HAVE_GETPROTOBYNUMBER
1137 struct protoent *ent = getprotobynumber(proto);
1147 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
1149 /* If we can guess the protocol from the socktype, do so. */
1150 if (!hints->ai_protocol && hints->ai_socktype) {
1151 if (hints->ai_socktype == SOCK_DGRAM)
1152 hints->ai_protocol = IPPROTO_UDP;
1153 else if (hints->ai_socktype == SOCK_STREAM)
1154 hints->ai_protocol = IPPROTO_TCP;
1157 /* Set the socktype if it isn't set. */
1158 if (!hints->ai_socktype && hints->ai_protocol) {
1159 if (hints->ai_protocol == IPPROTO_UDP)
1160 hints->ai_socktype = SOCK_DGRAM;
1161 else if (hints->ai_protocol == IPPROTO_TCP)
1162 hints->ai_socktype = SOCK_STREAM;
1164 else if (hints->ai_protocol == IPPROTO_SCTP)
1165 hints->ai_socktype = SOCK_STREAM;
1170 #if AF_UNSPEC != PF_UNSPEC
1171 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
1174 /** Implements the part of looking up hosts by name that's common to both
1175 * the blocking and nonblocking resolver:
1176 * - Adjust 'hints' to have a reasonable socktype and protocol.
1177 * - Look up the port based on 'servname', and store it in *portnum,
1178 * - Handle the nodename==NULL case
1179 * - Handle some invalid arguments cases.
1180 * - Handle the cases where nodename is an IPv4 or IPv6 address.
1182 * If we need the resolver to look up the hostname, we return
1183 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
1184 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
1185 * set *res as getaddrinfo would.
1188 evutil_getaddrinfo_common_(const char *nodename, const char *servname,
1189 struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
1192 unsigned int if_index;
1195 if (nodename == NULL && servname == NULL)
1196 return EVUTIL_EAI_NONAME;
1198 /* We only understand 3 families */
1199 if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
1200 hints->ai_family != PF_INET6)
1201 return EVUTIL_EAI_FAMILY;
1203 evutil_getaddrinfo_infer_protocols(hints);
1205 /* Look up the port number and protocol, if possible. */
1206 pname = evutil_unparse_protoname(hints->ai_protocol);
1208 /* XXXX We could look at the protocol we got back from
1209 * getservbyname, but it doesn't seem too useful. */
1210 port = evutil_parse_servname(servname, pname, hints);
1212 return EVUTIL_EAI_NONAME;
1216 /* If we have no node name, then we're supposed to bind to 'any' and
1217 * connect to localhost. */
1218 if (nodename == NULL) {
1219 struct evutil_addrinfo *res4=NULL, *res6=NULL;
1220 if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
1221 struct sockaddr_in6 sin6;
1222 memset(&sin6, 0, sizeof(sin6));
1223 sin6.sin6_family = AF_INET6;
1224 sin6.sin6_port = htons(port);
1225 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1228 /* connect to ::1 */
1229 sin6.sin6_addr.s6_addr[15] = 1;
1231 res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1232 sizeof(sin6), hints);
1234 return EVUTIL_EAI_MEMORY;
1237 if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
1238 struct sockaddr_in sin;
1239 memset(&sin, 0, sizeof(sin));
1240 sin.sin_family = AF_INET;
1241 sin.sin_port = htons(port);
1242 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1243 /* Bind to 0.0.0.0 */
1245 /* connect to 127.0.0.1 */
1246 sin.sin_addr.s_addr = htonl(0x7f000001);
1248 res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
1249 sizeof(sin), hints);
1252 evutil_freeaddrinfo(res6);
1253 return EVUTIL_EAI_MEMORY;
1256 *res = evutil_addrinfo_append_(res4, res6);
1260 /* If we can, we should try to parse the hostname without resolving
1263 if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
1264 struct sockaddr_in6 sin6;
1265 memset(&sin6, 0, sizeof(sin6));
1266 if (1 == evutil_inet_pton_scope(
1267 AF_INET6, nodename, &sin6.sin6_addr, &if_index)) {
1268 /* Got an ipv6 address. */
1269 sin6.sin6_family = AF_INET6;
1270 sin6.sin6_port = htons(port);
1271 sin6.sin6_scope_id = if_index;
1272 *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1273 sizeof(sin6), hints);
1275 return EVUTIL_EAI_MEMORY;
1281 if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
1282 struct sockaddr_in sin;
1283 memset(&sin, 0, sizeof(sin));
1284 if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
1285 /* Got an ipv4 address. */
1286 sin.sin_family = AF_INET;
1287 sin.sin_port = htons(port);
1288 *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
1289 sizeof(sin), hints);
1291 return EVUTIL_EAI_MEMORY;
1297 /* If we have reached this point, we definitely need to do a DNS
1299 if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
1300 /* If we're not allowed to do one, then say so. */
1301 return EVUTIL_EAI_NONAME;
1304 return EVUTIL_EAI_NEED_RESOLVE;
1307 #ifdef EVENT__HAVE_GETADDRINFO
1308 #define USE_NATIVE_GETADDRINFO
1311 #ifdef USE_NATIVE_GETADDRINFO
1312 /* A mask of all the flags that we declare, so we can clear them before calling
1313 * the native getaddrinfo */
1314 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
1318 #ifndef AI_CANONNAME
1319 EVUTIL_AI_CANONNAME |
1321 #ifndef AI_NUMERICHOST
1322 EVUTIL_AI_NUMERICHOST |
1324 #ifndef AI_NUMERICSERV
1325 EVUTIL_AI_NUMERICSERV |
1327 #ifndef AI_ADDRCONFIG
1328 EVUTIL_AI_ADDRCONFIG |
1334 EVUTIL_AI_V4MAPPED |
1336 EVUTIL_AI_LIBEVENT_ALLOCATED;
1338 static const unsigned int ALL_NATIVE_AI_FLAGS =
1345 #ifdef AI_NUMERICHOST
1348 #ifdef AI_NUMERICSERV
1351 #ifdef AI_ADDRCONFIG
1363 #ifndef USE_NATIVE_GETADDRINFO
1364 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1367 static struct evutil_addrinfo *
1368 addrinfo_from_hostent(const struct hostent *ent,
1369 int port, const struct evutil_addrinfo *hints)
1372 struct sockaddr_in sin;
1373 struct sockaddr_in6 sin6;
1374 struct sockaddr *sa;
1376 struct evutil_addrinfo *res=NULL, *ai;
1379 if (ent->h_addrtype == PF_INET) {
1380 memset(&sin, 0, sizeof(sin));
1381 sin.sin_family = AF_INET;
1382 sin.sin_port = htons(port);
1383 sa = (struct sockaddr *)&sin;
1384 socklen = sizeof(struct sockaddr_in);
1385 addrp = &sin.sin_addr;
1386 if (ent->h_length != sizeof(sin.sin_addr)) {
1387 event_warnx("Weird h_length from gethostbyname");
1390 } else if (ent->h_addrtype == PF_INET6) {
1391 memset(&sin6, 0, sizeof(sin6));
1392 sin6.sin6_family = AF_INET6;
1393 sin6.sin6_port = htons(port);
1394 sa = (struct sockaddr *)&sin6;
1395 socklen = sizeof(struct sockaddr_in6);
1396 addrp = &sin6.sin6_addr;
1397 if (ent->h_length != sizeof(sin6.sin6_addr)) {
1398 event_warnx("Weird h_length from gethostbyname");
1404 for (i = 0; ent->h_addr_list[i]; ++i) {
1405 memcpy(addrp, ent->h_addr_list[i], ent->h_length);
1406 ai = evutil_new_addrinfo_(sa, socklen, hints);
1408 evutil_freeaddrinfo(res);
1411 res = evutil_addrinfo_append_(res, ai);
1414 if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1415 res->ai_canonname = mm_strdup(ent->h_name);
1416 if (res->ai_canonname == NULL) {
1417 evutil_freeaddrinfo(res);
1426 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1427 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1428 * that we'll only get addresses we could maybe connect to.
1431 evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
1433 if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1435 if (hints->ai_family != PF_UNSPEC)
1437 evutil_check_interfaces();
1438 if (had_ipv4_address && !had_ipv6_address) {
1439 hints->ai_family = PF_INET;
1440 } else if (!had_ipv4_address && had_ipv6_address) {
1441 hints->ai_family = PF_INET6;
1445 #ifdef USE_NATIVE_GETADDRINFO
1446 static int need_numeric_port_hack_=0;
1447 static int need_socktype_protocol_hack_=0;
1448 static int tested_for_getaddrinfo_hacks=0;
1450 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1451 giving a numeric port without giving an ai_socktype was verboten.
1452 We test for this so we can apply an appropriate workaround. If it
1453 turns out that the bug is present, then:
1455 - If nodename==NULL and servname is numeric, we build an answer
1456 ourselves using evutil_getaddrinfo_common_().
1458 - If nodename!=NULL and servname is numeric, then we set
1459 servname=NULL when calling getaddrinfo, and post-process the
1460 result to set the ports on it.
1462 We test for this bug at runtime, since otherwise we can't have the
1463 same binary run on multiple BSD versions.
1465 - Some versions of Solaris believe that it's nice to leave to protocol
1466 field set to 0. We test for this so we can apply an appropriate
1469 static struct evutil_addrinfo *ai_find_protocol(struct evutil_addrinfo *ai)
1472 if (ai->ai_protocol)
1479 test_for_getaddrinfo_hacks(void)
1482 struct evutil_addrinfo *ai=NULL, *ai2=NULL, *ai3=NULL;
1483 struct evutil_addrinfo hints;
1485 memset(&hints,0,sizeof(hints));
1486 hints.ai_family = PF_UNSPEC;
1488 #ifdef AI_NUMERICHOST
1491 #ifdef AI_NUMERICSERV
1495 r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1496 getaddrinfo("1.2.3.4", NULL, &hints, &ai3);
1497 hints.ai_socktype = SOCK_STREAM;
1498 r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1499 if (r2 == 0 && r != 0) {
1500 need_numeric_port_hack_=1;
1502 if (!ai_find_protocol(ai2) || !ai_find_protocol(ai3)) {
1503 need_socktype_protocol_hack_=1;
1512 tested_for_getaddrinfo_hacks=1;
1516 need_numeric_port_hack(void)
1518 if (!tested_for_getaddrinfo_hacks)
1519 test_for_getaddrinfo_hacks();
1520 return need_numeric_port_hack_;
1524 need_socktype_protocol_hack(void)
1526 if (!tested_for_getaddrinfo_hacks)
1527 test_for_getaddrinfo_hacks();
1528 return need_socktype_protocol_hack_;
1532 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1534 /* Now we run through the list and set the ports on all of the
1535 * results where ports would make sense. */
1536 for ( ; *ai; ai = &(*ai)->ai_next) {
1537 struct sockaddr *sa = (*ai)->ai_addr;
1538 if (sa && sa->sa_family == AF_INET) {
1539 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1540 sin->sin_port = htons(port);
1541 } else if (sa && sa->sa_family == AF_INET6) {
1542 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1543 sin6->sin6_port = htons(port);
1545 /* A numeric port makes no sense here; remove this one
1547 struct evutil_addrinfo *victim = *ai;
1548 *ai = victim->ai_next;
1549 victim->ai_next = NULL;
1550 freeaddrinfo(victim);
1556 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1558 struct evutil_addrinfo *ai_new;
1559 for (; ai; ai = ai->ai_next) {
1560 evutil_getaddrinfo_infer_protocols(ai);
1561 if (ai->ai_socktype || ai->ai_protocol)
1563 ai_new = mm_malloc(sizeof(*ai_new));
1566 memcpy(ai_new, ai, sizeof(*ai_new));
1567 ai->ai_socktype = SOCK_STREAM;
1568 ai->ai_protocol = IPPROTO_TCP;
1569 ai_new->ai_socktype = SOCK_DGRAM;
1570 ai_new->ai_protocol = IPPROTO_UDP;
1571 ai_new->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
1572 if (ai_new->ai_canonname != NULL) {
1573 ai_new->ai_canonname = mm_strdup(ai_new->ai_canonname);
1574 if (ai_new->ai_canonname == NULL) {
1580 ai_new->ai_next = ai->ai_next;
1581 ai->ai_next = ai_new;
1588 evutil_getaddrinfo(const char *nodename, const char *servname,
1589 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1591 #ifdef USE_NATIVE_GETADDRINFO
1592 struct evutil_addrinfo hints;
1593 int portnum=-1, need_np_hack, err;
1596 memcpy(&hints, hints_in, sizeof(hints));
1598 memset(&hints, 0, sizeof(hints));
1599 hints.ai_family = PF_UNSPEC;
1602 #ifndef AI_ADDRCONFIG
1603 /* Not every system has AI_ADDRCONFIG, so fake it. */
1604 if (hints.ai_family == PF_UNSPEC &&
1605 (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1606 evutil_adjust_hints_for_addrconfig_(&hints);
1610 #ifndef AI_NUMERICSERV
1611 /* Not every system has AI_NUMERICSERV, so fake it. */
1612 if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1613 if (servname && parse_numeric_servname(servname)<0)
1614 return EVUTIL_EAI_NONAME;
1618 /* Enough operating systems handle enough common non-resolve
1619 * cases here weirdly enough that we are better off just
1620 * overriding them. For example:
1622 * - Windows doesn't like to infer the protocol from the
1623 * socket type, or fill in socket or protocol types much at
1624 * all. It also seems to do its own broken implicit
1625 * always-on version of AI_ADDRCONFIG that keeps it from
1626 * ever resolving even a literal IPv6 address when
1627 * ai_addrtype is PF_UNSPEC.
1632 err = evutil_getaddrinfo_common_(nodename,servname,&hints,
1635 err == EVUTIL_EAI_MEMORY ||
1636 err == EVUTIL_EAI_NONAME)
1638 /* If we make it here, the system getaddrinfo can
1639 * have a crack at it. */
1643 /* See documentation for need_numeric_port_hack above.*/
1644 need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1645 && ((portnum=parse_numeric_servname(servname)) >= 0);
1648 return evutil_getaddrinfo_common_(
1649 NULL,servname,&hints, res, &portnum);
1653 if (need_socktype_protocol_hack()) {
1654 evutil_getaddrinfo_infer_protocols(&hints);
1657 /* Make sure that we didn't actually steal any AI_FLAGS values that
1658 * the system is using. (This is a constant expression, and should ge
1661 * XXXX Turn this into a compile-time failure rather than a run-time
1664 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1666 /* Clear any flags that only libevent understands. */
1667 hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1669 err = getaddrinfo(nodename, servname, &hints, res);
1671 apply_numeric_port_hack(portnum, res);
1673 if (need_socktype_protocol_hack()) {
1674 if (apply_socktype_protocol_hack(*res) < 0) {
1675 evutil_freeaddrinfo(*res);
1677 return EVUTIL_EAI_MEMORY;
1683 struct hostent *ent = NULL;
1684 struct evutil_addrinfo hints;
1687 memcpy(&hints, hints_in, sizeof(hints));
1689 memset(&hints, 0, sizeof(hints));
1690 hints.ai_family = PF_UNSPEC;
1693 evutil_adjust_hints_for_addrconfig_(&hints);
1695 err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
1696 if (err != EVUTIL_EAI_NEED_RESOLVE) {
1697 /* We either succeeded or failed. No need to continue */
1702 /* Use any of the various gethostbyname_r variants as available. */
1704 #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1705 /* This one is what glibc provides. */
1707 struct hostent hostent;
1709 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1711 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1713 struct hostent hostent;
1714 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1716 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1717 struct hostent_data data;
1718 struct hostent hostent;
1719 memset(&data, 0, sizeof(data));
1720 err = gethostbyname_r(nodename, &hostent, &data);
1721 ent = err ? NULL : &hostent;
1723 /* fall back to gethostbyname. */
1724 /* XXXX This needs a lock everywhere but Windows. */
1725 ent = gethostbyname(nodename);
1727 err = WSAGetLastError();
1733 /* Now we have either ent or err set. */
1735 /* XXX is this right for windows ? */
1738 return EVUTIL_EAI_AGAIN;
1741 return EVUTIL_EAI_FAIL;
1742 case HOST_NOT_FOUND:
1743 return EVUTIL_EAI_NONAME;
1745 #if NO_DATA != NO_ADDRESS
1748 return EVUTIL_EAI_NODATA;
1752 if (ent->h_addrtype != hints.ai_family &&
1753 hints.ai_family != PF_UNSPEC) {
1754 /* This wasn't the type we were hoping for. Too bad
1755 * we never had a chance to ask gethostbyname for what
1757 return EVUTIL_EAI_NONAME;
1760 /* Make sure we got _some_ answers. */
1761 if (ent->h_length == 0)
1762 return EVUTIL_EAI_NODATA;
1764 /* If we got an address type we don't know how to make a
1765 sockaddr for, give up. */
1766 if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1767 return EVUTIL_EAI_FAMILY;
1769 *res = addrinfo_from_hostent(ent, port, &hints);
1771 return EVUTIL_EAI_MEMORY;
1779 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1781 #ifdef EVENT__HAVE_GETADDRINFO
1782 struct evutil_addrinfo *ai_prev = NULL;
1783 struct evutil_addrinfo *ai_temp = ai;
1784 /* Linked list may be the result of a native getaddrinfo() call plus
1785 * locally allocated nodes, Before releasing it using freeaddrinfo(),
1786 * these custom structs need to be freed separately.
1789 struct evutil_addrinfo *next = ai_temp->ai_next;
1790 if (ai_temp->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED) {
1791 /* Remove this node from the linked list */
1792 if (ai_temp->ai_canonname)
1793 mm_free(ai_temp->ai_canonname);
1795 if (ai_prev == NULL) {
1798 ai_prev->ai_next = next;
1810 struct evutil_addrinfo *next = ai->ai_next;
1811 if (ai->ai_canonname)
1812 mm_free(ai->ai_canonname);
1819 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1820 static evdns_getaddrinfo_cancel_fn evdns_getaddrinfo_cancel_impl = NULL;
1823 evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
1825 if (!evdns_getaddrinfo_impl)
1826 evdns_getaddrinfo_impl = fn;
1829 evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn)
1831 if (!evdns_getaddrinfo_cancel_impl)
1832 evdns_getaddrinfo_cancel_impl = fn;
1835 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1836 * otherwise do a blocking resolve and pass the result to the callback in the
1837 * way that evdns_getaddrinfo would.
1839 struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
1840 struct evdns_base *dns_base,
1841 const char *nodename, const char *servname,
1842 const struct evutil_addrinfo *hints_in,
1843 void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1845 if (dns_base && evdns_getaddrinfo_impl) {
1846 return evdns_getaddrinfo_impl(
1847 dns_base, nodename, servname, hints_in, cb, arg);
1849 struct evutil_addrinfo *ai=NULL;
1851 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1857 void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data)
1859 if (evdns_getaddrinfo_cancel_impl && data) {
1860 evdns_getaddrinfo_cancel_impl(data);
1865 evutil_gai_strerror(int err)
1867 /* As a sneaky side-benefit, this case statement will get most
1868 * compilers to tell us if any of the error codes we defined
1869 * conflict with the platform's native error codes. */
1871 case EVUTIL_EAI_CANCEL:
1872 return "Request canceled";
1876 case EVUTIL_EAI_ADDRFAMILY:
1877 return "address family for nodename not supported";
1878 case EVUTIL_EAI_AGAIN:
1879 return "temporary failure in name resolution";
1880 case EVUTIL_EAI_BADFLAGS:
1881 return "invalid value for ai_flags";
1882 case EVUTIL_EAI_FAIL:
1883 return "non-recoverable failure in name resolution";
1884 case EVUTIL_EAI_FAMILY:
1885 return "ai_family not supported";
1886 case EVUTIL_EAI_MEMORY:
1887 return "memory allocation failure";
1888 case EVUTIL_EAI_NODATA:
1889 return "no address associated with nodename";
1890 case EVUTIL_EAI_NONAME:
1891 return "nodename nor servname provided, or not known";
1892 case EVUTIL_EAI_SERVICE:
1893 return "servname not supported for ai_socktype";
1894 case EVUTIL_EAI_SOCKTYPE:
1895 return "ai_socktype not supported";
1896 case EVUTIL_EAI_SYSTEM:
1897 return "system error";
1899 #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1900 return gai_strerrorA(err);
1901 #elif defined(USE_NATIVE_GETADDRINFO)
1902 return gai_strerror(err);
1904 return "Unknown error code";
1910 /* destructively remove a trailing line terminator from s */
1915 if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
1917 if (len > 0 && s[len - 1] == '\r')
1922 /* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1923 * is supposed to return a string which is good indefinitely without having
1924 * to be freed. To make this work without leaking memory, we cache the
1925 * string the first time FormatMessage is called on a particular error
1926 * code, and then return the cached string on subsequent calls with the
1927 * same code. The strings aren't freed until libevent_global_shutdown
1928 * (or never). We use a linked list to cache the errors, because we
1929 * only expect there to be a few dozen, and that should be fast enough.
1932 struct cached_sock_errs_entry {
1933 HT_ENTRY(cached_sock_errs_entry) node;
1935 char *msg; /* allocated with LocalAlloc; free with LocalFree */
1938 static inline unsigned
1939 hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
1941 /* Use Murmur3's 32-bit finalizer as an integer hash function */
1952 eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
1953 const struct cached_sock_errs_entry *b)
1955 return a->code == b->code;
1958 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1959 static void *windows_socket_errors_lock_ = NULL;
1962 static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
1963 windows_socket_errors = HT_INITIALIZER();
1965 HT_PROTOTYPE(cached_sock_errs_map,
1966 cached_sock_errs_entry,
1968 hash_cached_sock_errs,
1969 eq_cached_sock_errs);
1971 HT_GENERATE(cached_sock_errs_map,
1972 cached_sock_errs_entry,
1974 hash_cached_sock_errs,
1975 eq_cached_sock_errs,
1981 /** Equivalent to strerror, but for windows socket errors. */
1983 evutil_socket_error_to_string(int errcode)
1985 struct cached_sock_errs_entry *errs, *newerr, find;
1988 EVLOCK_LOCK(windows_socket_errors_lock_, 0);
1990 find.code = errcode;
1991 errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
1997 if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1998 FORMAT_MESSAGE_IGNORE_INSERTS |
1999 FORMAT_MESSAGE_ALLOCATE_BUFFER,
2000 NULL, errcode, 0, (char *)&msg, 0, NULL))
2001 chomp (msg); /* because message has trailing newline */
2004 /* use LocalAlloc because FormatMessage does */
2005 msg = LocalAlloc(LMEM_FIXED, len);
2007 msg = (char *)"LocalAlloc failed during Winsock error";
2010 evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
2013 newerr = (struct cached_sock_errs_entry *)
2014 mm_malloc(sizeof (struct cached_sock_errs_entry));
2018 msg = (char *)"malloc failed during Winsock error";
2022 newerr->code = errcode;
2024 HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
2027 EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
2032 #ifndef EVENT__DISABLE_THREAD_SUPPORT
2034 evutil_global_setup_locks_(const int enable_locks)
2036 EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
2042 evutil_free_sock_err_globals(void)
2044 struct cached_sock_errs_entry **errs, *tofree;
2046 for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
2049 errs = HT_NEXT_RMV(cached_sock_errs_map,
2050 &windows_socket_errors,
2052 LocalFree(tofree->msg);
2056 HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
2058 #ifndef EVENT__DISABLE_THREAD_SUPPORT
2059 if (windows_socket_errors_lock_ != NULL) {
2060 EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
2061 windows_socket_errors_lock_ = NULL;
2068 #ifndef EVENT__DISABLE_THREAD_SUPPORT
2070 evutil_global_setup_locks_(const int enable_locks)
2077 evutil_free_sock_err_globals(void)
2084 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
2088 va_start(ap, format);
2089 r = evutil_vsnprintf(buf, buflen, format, ap);
2095 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
2100 #if defined(_MSC_VER) || defined(_WIN32)
2101 r = _vsnprintf(buf, buflen, format, ap);
2103 r = _vscprintf(format, ap);
2105 /* Make sure we always use the correct vsnprintf on IRIX */
2106 extern int _xpg5_vsnprintf(char * __restrict,
2107 __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
2108 const char * __restrict, /* va_list */ char *);
2110 r = _xpg5_vsnprintf(buf, buflen, format, ap);
2112 r = vsnprintf(buf, buflen, format, ap);
2114 buf[buflen-1] = '\0';
2118 #define USE_INTERNAL_NTOP
2119 #define USE_INTERNAL_PTON
2122 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
2124 #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
2125 return inet_ntop(af, src, dst, len);
2127 if (af == AF_INET) {
2128 const struct in_addr *in = src;
2129 const ev_uint32_t a = ntohl(in->s_addr);
2131 r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
2132 (int)(ev_uint8_t)((a>>24)&0xff),
2133 (int)(ev_uint8_t)((a>>16)&0xff),
2134 (int)(ev_uint8_t)((a>>8 )&0xff),
2135 (int)(ev_uint8_t)((a )&0xff));
2136 if (r<0||(size_t)r>=len)
2141 } else if (af == AF_INET6) {
2142 const struct in6_addr *addr = src;
2144 int longestGapLen = 0, longestGapPos = -1, i,
2145 curGapPos = -1, curGapLen = 0;
2146 ev_uint16_t words[8];
2147 for (i = 0; i < 8; ++i) {
2149 (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
2151 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
2152 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
2153 (words[5] == 0xffff))) {
2154 /* This is an IPv4 address. */
2155 if (words[5] == 0) {
2156 evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
2157 addr->s6_addr[12], addr->s6_addr[13],
2158 addr->s6_addr[14], addr->s6_addr[15]);
2160 evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
2161 addr->s6_addr[12], addr->s6_addr[13],
2162 addr->s6_addr[14], addr->s6_addr[15]);
2164 if (strlen(buf) > len)
2166 strlcpy(dst, buf, len);
2171 if (words[i] == 0) {
2174 while (i<8 && words[i] == 0) {
2177 if (curGapLen > longestGapLen) {
2178 longestGapPos = curGapPos;
2179 longestGapLen = curGapLen;
2185 if (longestGapLen<=1)
2189 for (i = 0; i < 8; ++i) {
2190 if (words[i] == 0 && longestGapPos == i) {
2194 while (i < 8 && words[i] == 0)
2196 --i; /* to compensate for loop increment. */
2199 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
2206 if (strlen(buf) > len)
2208 strlcpy(dst, buf, len);
2218 evutil_inet_pton_scope(int af, const char *src, void *dst, unsigned *indexp)
2222 char *check, *cp, *tmp_src;
2224 *indexp = 0; /* Reasonable default */
2226 /* Bail out if not IPv6 */
2228 return evutil_inet_pton(af, src, dst);
2230 cp = strchr(src, '%');
2232 /* Bail out if no zone ID */
2234 return evutil_inet_pton(af, src, dst);
2236 if_index = if_nametoindex(cp + 1);
2237 if (if_index == 0) {
2238 /* Could be numeric */
2239 if_index = strtoul(cp + 1, &check, 10);
2240 if (check[0] != '\0')
2244 tmp_src = mm_strdup(src);
2245 cp = strchr(tmp_src, '%');
2247 r = evutil_inet_pton(af, tmp_src, dst);
2253 evutil_inet_pton(int af, const char *src, void *dst)
2255 #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
2256 return inet_pton(af, src, dst);
2258 if (af == AF_INET) {
2261 struct in_addr *addr = dst;
2262 if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
2264 if (a > 255) return 0;
2265 if (b > 255) return 0;
2266 if (c > 255) return 0;
2267 if (d > 255) return 0;
2268 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2271 } else if (af == AF_INET6) {
2272 struct in6_addr *out = dst;
2273 ev_uint16_t words[8];
2274 int gapPos = -1, i, setWords=0;
2275 const char *dot = strchr(src, '.');
2276 const char *eow; /* end of words. */
2280 eow = src+strlen(src);
2282 unsigned byte1,byte2,byte3,byte4;
2284 for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
2288 /* We use "scanf" because some platform inet_aton()s are too lax
2289 * about IPv4 addresses of the form "1.2.3" */
2290 if (sscanf(eow, "%u.%u.%u.%u%c",
2291 &byte1,&byte2,&byte3,&byte4,&more) != 4)
2300 words[6] = (byte1<<8) | byte2;
2301 words[7] = (byte3<<8) | byte4;
2309 if (EVUTIL_ISXDIGIT_(*src)) {
2311 long r = strtol(src, &next, 16);
2319 words[i++] = (ev_uint16_t)r;
2322 if (*src != ':' && src != eow)
2325 } else if (*src == ':' && i > 0 && gapPos==-1) {
2328 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
2337 (setWords == 8 && gapPos != -1) ||
2338 (setWords < 8 && gapPos == -1))
2342 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2343 int gapLen = 8 - setWords;
2344 /* assert(nToMove >= 0); */
2346 return -1; /* should be impossible */
2347 memmove(&words[gapPos+gapLen], &words[gapPos],
2348 sizeof(ev_uint16_t)*nToMove);
2349 memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
2351 for (i = 0; i < 8; ++i) {
2352 out->s6_addr[2*i ] = words[i] >> 8;
2353 out->s6_addr[2*i+1] = words[i] & 0xff;
2365 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
2368 unsigned int if_index;
2370 const char *cp, *addr_part, *port_part;
2372 /* recognized formats are:
2380 cp = strchr(ip_as_string, ':');
2381 if (*ip_as_string == '[') {
2383 if (!(cp = strchr(ip_as_string, ']'))) {
2386 len = ( cp-(ip_as_string + 1) );
2387 if (len > sizeof(buf)-1) {
2390 memcpy(buf, ip_as_string+1, len);
2398 } else if (cp && strchr(cp+1, ':')) {
2400 addr_part = ip_as_string;
2404 if (cp - ip_as_string > (int)sizeof(buf)-1) {
2407 memcpy(buf, ip_as_string, cp-ip_as_string);
2408 buf[cp-ip_as_string] = '\0';
2412 addr_part = ip_as_string;
2417 if (port_part == NULL) {
2420 port = atoi(port_part);
2421 if (port <= 0 || port > 65535) {
2427 return -1; /* Should be impossible. */
2431 struct sockaddr_in6 sin6;
2432 memset(&sin6, 0, sizeof(sin6));
2433 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2434 sin6.sin6_len = sizeof(sin6);
2436 sin6.sin6_family = AF_INET6;
2437 sin6.sin6_port = htons(port);
2438 if (1 != evutil_inet_pton_scope(
2439 AF_INET6, addr_part, &sin6.sin6_addr, &if_index)) {
2442 if ((int)sizeof(sin6) > *outlen)
2444 sin6.sin6_scope_id = if_index;
2445 memset(out, 0, *outlen);
2446 memcpy(out, &sin6, sizeof(sin6));
2447 *outlen = sizeof(sin6);
2453 struct sockaddr_in sin;
2454 memset(&sin, 0, sizeof(sin));
2455 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2456 sin.sin_len = sizeof(sin);
2458 sin.sin_family = AF_INET;
2459 sin.sin_port = htons(port);
2460 if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
2462 if ((int)sizeof(sin) > *outlen)
2464 memset(out, 0, *outlen);
2465 memcpy(out, &sin, sizeof(sin));
2466 *outlen = sizeof(sin);
2472 evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
2475 const char *res=NULL;
2477 if (sa->sa_family == AF_INET) {
2478 const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
2479 res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
2480 port = ntohs(sin->sin_port);
2482 evutil_snprintf(out, outlen, "%s:%d", b, port);
2485 } else if (sa->sa_family == AF_INET6) {
2486 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
2487 res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
2488 port = ntohs(sin6->sin6_port);
2490 evutil_snprintf(out, outlen, "[%s]:%d", b, port);
2495 evutil_snprintf(out, outlen, "<addr with socktype %d>",
2496 (int)sa->sa_family);
2501 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
2505 if (0 != (r = (sa1->sa_family - sa2->sa_family)))
2508 if (sa1->sa_family == AF_INET) {
2509 const struct sockaddr_in *sin1, *sin2;
2510 sin1 = (const struct sockaddr_in *)sa1;
2511 sin2 = (const struct sockaddr_in *)sa2;
2512 if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
2514 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
2516 else if (include_port &&
2517 (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
2523 else if (sa1->sa_family == AF_INET6) {
2524 const struct sockaddr_in6 *sin1, *sin2;
2525 sin1 = (const struct sockaddr_in6 *)sa1;
2526 sin2 = (const struct sockaddr_in6 *)sa2;
2527 if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
2529 else if (include_port &&
2530 (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
2539 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
2540 * has 256 bits to look up whether a character is in some set or not. This
2541 * fails on non-ASCII platforms, but so does every other place where we
2542 * take a char and write it onto the network.
2544 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
2545 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2546 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
2547 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2548 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2549 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
2550 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2551 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2552 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
2553 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2554 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2555 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2556 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
2558 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
2559 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2560 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2561 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2562 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2563 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2564 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2565 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2566 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2567 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2568 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2569 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2570 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2571 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2572 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2573 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2574 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2576 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
2577 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2578 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2579 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2580 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2581 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2582 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2583 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2584 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2585 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2586 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2587 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2588 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2589 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2590 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2591 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2592 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2595 #define IMPL_CTYPE_FN(name) \
2596 int EVUTIL_##name##_(char c) { \
2598 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1U << (u & 31))); \
2600 IMPL_CTYPE_FN(ISALPHA)
2601 IMPL_CTYPE_FN(ISALNUM)
2602 IMPL_CTYPE_FN(ISSPACE)
2603 IMPL_CTYPE_FN(ISDIGIT)
2604 IMPL_CTYPE_FN(ISXDIGIT)
2605 IMPL_CTYPE_FN(ISPRINT)
2606 IMPL_CTYPE_FN(ISLOWER)
2607 IMPL_CTYPE_FN(ISUPPER)
2609 char EVUTIL_TOLOWER_(char c)
2611 return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2613 char EVUTIL_TOUPPER_(char c)
2615 return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2618 evutil_ascii_strcasecmp(const char *s1, const char *s2)
2622 c1 = EVUTIL_TOLOWER_(*s1++);
2623 c2 = EVUTIL_TOLOWER_(*s2++);
2632 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2636 c1 = EVUTIL_TOLOWER_(*s1++);
2637 c2 = EVUTIL_TOLOWER_(*s2++);
2649 evutil_rtrim_lws_(char *str)
2656 if ((cp = strchr(str, '\0')) == NULL || (cp == str))
2661 while (*cp == ' ' || *cp == '\t') {
2670 evutil_issetugid(void)
2672 #ifdef EVENT__HAVE_ISSETUGID
2676 #ifdef EVENT__HAVE_GETEUID
2677 if (getuid() != geteuid())
2680 #ifdef EVENT__HAVE_GETEGID
2681 if (getgid() != getegid())
2689 evutil_getenv_(const char *varname)
2691 if (evutil_issetugid())
2694 return getenv(varname);
2698 evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
2702 evutil_gettimeofday(&tv, NULL);
2703 seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
2705 seed += (ev_uint32_t) _getpid();
2707 seed += (ev_uint32_t) getpid();
2715 evutil_weakrand_(struct evutil_weakrand_state *state)
2717 /* This RNG implementation is a linear congruential generator, with
2718 * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
2719 * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2721 * The linear congruential generator is not an industrial-strength
2722 * RNG! It's fast, but it can have higher-order patterns. Notably,
2723 * the low bits tend to have periodicity.
2725 state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
2726 return (ev_int32_t)(state->seed);
2730 evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
2732 ev_int32_t divisor, result;
2734 /* We can't just do weakrand() % top, since the low bits of the LCG
2735 * are less random than the high ones. (Specifically, since the LCG
2736 * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2737 * therefore the low m bits of the LCG will have period 2^m.) */
2738 divisor = EVUTIL_WEAKRAND_MAX / top;
2740 result = evutil_weakrand_(state) / divisor;
2741 } while (result >= top);
2746 * Volatile pointer to memset: we use this to keep the compiler from
2747 * eliminating our call to memset.
2749 void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
2752 evutil_memclear_(void *mem, size_t len)
2754 evutil_memset_volatile_(mem, 0, len);
2758 evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
2760 static const char LOOPBACK_S6[16] =
2761 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2762 if (addr->sa_family == AF_INET) {
2763 struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2764 return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2765 } else if (addr->sa_family == AF_INET6) {
2766 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2767 return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2773 evutil_hex_char_to_int_(char c)
2787 case 'A': case 'a': return 10;
2788 case 'B': case 'b': return 11;
2789 case 'C': case 'c': return 12;
2790 case 'D': case 'd': return 13;
2791 case 'E': case 'e': return 14;
2792 case 'F': case 'f': return 15;
2799 evutil_load_windows_system_library_(const TCHAR *library_name)
2801 TCHAR path[MAX_PATH];
2803 n = GetSystemDirectory(path, MAX_PATH);
2804 if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2806 _tcscat(path, TEXT("\\"));
2807 _tcscat(path, library_name);
2808 return LoadLibrary(path);
2812 /* Internal wrapper around 'socket' to provide Linux-style support for
2813 * syscall-saving methods where available.
2815 * In addition to regular socket behavior, you can use a bitwise or to set the
2816 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2817 * to make the socket nonblocking or close-on-exec with as few syscalls as
2821 evutil_socket_(int domain, int type, int protocol)
2824 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2825 r = socket(domain, type, protocol);
2828 else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
2831 #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2832 r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
2835 if (type & EVUTIL_SOCK_NONBLOCK) {
2836 if (evutil_fast_socket_nonblocking(r) < 0) {
2837 evutil_closesocket(r);
2841 if (type & EVUTIL_SOCK_CLOEXEC) {
2842 if (evutil_fast_socket_closeonexec(r) < 0) {
2843 evutil_closesocket(r);
2850 /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2851 * support for syscall-saving methods where available.
2853 * In addition to regular accept behavior, you can set one or more of flags
2854 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2855 * make the socket nonblocking or close-on-exec with as few syscalls as
2859 evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
2860 ev_socklen_t *addrlen, int flags)
2862 evutil_socket_t result;
2863 #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2864 result = accept4(sockfd, addr, addrlen, flags);
2865 if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
2866 /* A nonnegative result means that we succeeded, so return.
2867 * Failing with EINVAL means that an option wasn't supported,
2868 * and failing with ENOSYS means that the syscall wasn't
2869 * there: in those cases we want to fall back. Otherwise, we
2870 * got a real error, and we should return. */
2874 result = accept(sockfd, addr, addrlen);
2878 if (flags & EVUTIL_SOCK_CLOEXEC) {
2879 if (evutil_fast_socket_closeonexec(result) < 0) {
2880 evutil_closesocket(result);
2884 if (flags & EVUTIL_SOCK_NONBLOCK) {
2885 if (evutil_fast_socket_nonblocking(result) < 0) {
2886 evutil_closesocket(result);
2893 /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2894 * fd[1] get read from fd[0]. Make both fds nonblocking and close-on-exec.
2895 * Return 0 on success, -1 on failure.
2898 evutil_make_internal_pipe_(evutil_socket_t fd[2])
2901 Making the second socket nonblocking is a bit subtle, given that we
2902 ignore any EAGAIN returns when writing to it, and you don't usally
2903 do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2904 then there's no need to add any more data to the buffer, since
2905 the main thread is already either about to wake up and drain it,
2906 or woken up and in the process of draining it.
2909 #if defined(EVENT__HAVE_PIPE2)
2910 if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
2913 #if defined(EVENT__HAVE_PIPE)
2914 if (pipe(fd) == 0) {
2915 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2916 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2917 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2918 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2926 event_warn("%s: pipe", __func__);
2930 #if defined(_WIN32) && !defined(EVENT__HAVE_AFUNIX_H)
2931 #define LOCAL_SOCKETPAIR_AF AF_INET
2933 #define LOCAL_SOCKETPAIR_AF AF_UNIX
2935 if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
2936 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2937 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2938 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2939 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2940 evutil_closesocket(fd[0]);
2941 evutil_closesocket(fd[1]);
2951 /* Wrapper around eventfd on systems that provide it. Unlike the system
2952 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2953 * flags. Returns -1 on error or if eventfd is not supported.
2956 evutil_eventfd_(unsigned initval, int flags)
2958 #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
2960 #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
2961 r = eventfd(initval, flags);
2962 if (r >= 0 || flags == 0)
2965 r = eventfd(initval, 0);
2968 if (flags & EVUTIL_EFD_CLOEXEC) {
2969 if (evutil_fast_socket_closeonexec(r) < 0) {
2970 evutil_closesocket(r);
2974 if (flags & EVUTIL_EFD_NONBLOCK) {
2975 if (evutil_fast_socket_nonblocking(r) < 0) {
2976 evutil_closesocket(r);
2987 evutil_free_globals_(void)
2989 evutil_free_secure_rng_globals_();
2990 evutil_free_sock_err_globals();