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 #include <stringapiset.h>
35 #ifdef EVENT__HAVE_AFUNIX_H
38 #define WIN32_LEAN_AND_MEAN
40 #undef WIN32_LEAN_AND_MEAN
45 /* For structs needed by GetAdaptersAddresses */
46 #define _WIN32_WINNT 0x0501
51 #include <sys/types.h>
52 #ifdef EVENT__HAVE_SYS_SOCKET_H
53 #include <sys/socket.h>
55 #ifdef EVENT__HAVE_UNISTD_H
58 #ifdef EVENT__HAVE_FCNTL_H
61 #ifdef EVENT__HAVE_STDLIB_H
68 #ifdef EVENT__HAVE_NETINET_IN_H
69 #include <netinet/in.h>
71 #ifdef EVENT__HAVE_NETINET_IN6_H
72 #include <netinet/in6.h>
74 #ifdef EVENT__HAVE_NETINET_TCP_H
75 #include <netinet/tcp.h>
77 #ifdef EVENT__HAVE_ARPA_INET_H
78 #include <arpa/inet.h>
85 #ifdef EVENT__HAVE_IFADDRS_H
89 #include "event2/util.h"
90 #include "util-internal.h"
91 #include "log-internal.h"
92 #include "mm-internal.h"
93 #include "evthread-internal.h"
95 #include "strlcpy-internal.h"
96 #include "ipv6-internal.h"
99 #define HT_NO_CACHE_HASH_VALUES
100 #include "ht-internal.h"
105 #define fstat _fstati64
108 #define stat _stati64
114 #define O_RDONLY _O_RDONLY
117 #ifdef EVENT__HAVE_AFUNIX_H
118 int have_working_afunix_ = -1;
122 evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
127 fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
128 if (fd >= 0 || errno == EINVAL)
130 /* If we got an EINVAL, fall through and try without O_CLOEXEC */
132 fd = open(pathname, flags, (mode_t)mode);
136 #if defined(FD_CLOEXEC)
137 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
147 Read the contents of 'filename' into a newly allocated NUL-terminated
148 string. Set *content_out to hold this string, and *len_out to hold its
149 length (not including the appended NUL). If 'is_binary', open the file in
152 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
154 Used internally only; may go away in a future version.
157 evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
163 size_t read_so_far=0;
166 EVUTIL_ASSERT(content_out);
167 EVUTIL_ASSERT(len_out);
176 fd = evutil_open_closeonexec_(filename, mode, 0);
179 if (fstat(fd, &st) || st.st_size < 0 ||
180 st.st_size > EV_SSIZE_MAX-1 ) {
184 mem = mm_malloc((size_t)st.st_size + 1);
191 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
193 #define N_TO_READ(x) (x)
195 while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
197 if (read_so_far >= (size_t)st.st_size)
199 EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
206 mem[read_so_far] = 0;
208 *len_out = read_so_far;
216 create_tmpfile(WCHAR tmpfile[MAX_PATH])
218 WCHAR short_path[MAX_PATH] = {0};
219 WCHAR long_path[MAX_PATH] = {0};
220 WCHAR prefix[4] = {0};
221 // GetTempFileNameW() uses up to the first three characters of the prefix
222 // and windows filesystems are case-insensitive
223 const WCHAR *base32set = L"abcdefghijklmnopqrstuvwxyz012345";
226 evutil_secure_rng_get_bytes(&rnd, sizeof(rnd));
227 prefix[0] = base32set[(rnd ) & 31];
228 prefix[1] = base32set[(rnd >> 5) & 31];
229 prefix[2] = base32set[(rnd >> 10) & 31];
232 GetTempPathW(MAX_PATH, short_path);
233 GetLongPathNameW(short_path, long_path, MAX_PATH);
234 if (!GetTempFileNameW(long_path, prefix, 0, tmpfile)) {
235 event_warnx("GetTempFileName failed: %d", EVUTIL_SOCKET_ERROR());
241 #ifdef EVENT__HAVE_AFUNIX_H
242 /* Test whether Unix domain socket works.
243 * Return 1 if it works, otherwise 0 */
245 evutil_check_working_afunix_()
247 /* Windows 10 began to support Unix domain socket. Let's just try
248 * socket(AF_UNIX, , ) and fall back to socket(AF_INET, , ).
249 * https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/
251 evutil_socket_t sd = -1;
252 if (have_working_afunix_ < 0) {
253 if ((sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
254 have_working_afunix_ = 0;
256 have_working_afunix_ = 1;
257 evutil_closesocket(sd);
260 return have_working_afunix_;
263 /* XXX Copy from evutil_ersatz_socketpair_() */
265 evutil_win_socketpair_afunix(int family, int type, int protocol,
266 evutil_socket_t fd[2])
268 #define ERR(e) WSA##e
269 evutil_socket_t listener = -1;
270 evutil_socket_t connector = -1;
271 evutil_socket_t acceptor = -1;
273 struct sockaddr_un listen_addr;
274 struct sockaddr_un connect_addr;
275 WCHAR tmp_file[MAX_PATH] = {0};
276 char tmp_file_utf8[MAX_PATH] = {0};
279 int saved_errno = -1;
282 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
286 listener = socket(family, type, 0);
289 memset(&listen_addr, 0, sizeof(listen_addr));
291 if (create_tmpfile(tmp_file)) {
292 goto tidy_up_and_fail;
294 DeleteFileW(tmp_file);
296 /* Windows requires `sun_path` to be encoded by UTF-8 */
298 CP_UTF8, 0, tmp_file, MAX_PATH, tmp_file_utf8, MAX_PATH, NULL, NULL);
300 listen_addr.sun_family = AF_UNIX;
301 if (strlcpy(listen_addr.sun_path, tmp_file_utf8, UNIX_PATH_MAX) >=
303 event_warnx("Temp file name is too long");
304 goto tidy_up_and_fail;
307 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
309 goto tidy_up_and_fail;
310 if (listen(listener, 1) == -1)
311 goto tidy_up_and_fail;
313 connector = socket(family, type, 0);
315 goto tidy_up_and_fail;
317 memset(&connect_addr, 0, sizeof(connect_addr));
319 /* We want to find out the port number to connect to. */
320 size = sizeof(connect_addr);
321 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
322 goto tidy_up_and_fail;
324 if (connect(connector, (struct sockaddr *) &connect_addr,
325 sizeof(connect_addr)) == -1)
326 goto tidy_up_and_fail;
328 size = sizeof(listen_addr);
329 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
331 goto tidy_up_and_fail;
332 if (size != sizeof(listen_addr))
333 goto abort_tidy_up_and_fail;
334 /* Now check we are talking to ourself by matching port and host on the
336 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
337 goto tidy_up_and_fail;
339 if (size != sizeof(connect_addr) ||
340 listen_addr.sun_family != connect_addr.sun_family ||
341 evutil_ascii_strcasecmp(listen_addr.sun_path, connect_addr.sun_path))
342 goto abort_tidy_up_and_fail;
344 evutil_closesocket(listener);
350 abort_tidy_up_and_fail:
351 saved_errno = ERR(ECONNABORTED);
354 saved_errno = EVUTIL_SOCKET_ERROR();
356 evutil_closesocket(listener);
358 evutil_closesocket(connector);
360 evutil_closesocket(acceptor);
362 DeleteFileW(tmp_file);
364 EVUTIL_SET_SOCKET_ERROR(saved_errno);
371 evutil_win_socketpair(int family, int type, int protocol,
372 evutil_socket_t fd[2])
374 #ifdef EVENT__HAVE_AFUNIX_H
375 /* The family only support AF_UNIX and AF_INET */
376 if (protocol || (family != AF_UNIX && family != AF_INET)) {
377 EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
380 if (evutil_check_working_afunix_()) {
381 /* If the AF_UNIX socket works, we will change the family to
382 * AF_UNIX forcely. */
384 if (type != SOCK_STREAM) {
385 /* Win10 does not support AF_UNIX socket of a type other
386 * than SOCK_STREAM still now. */
387 EVUTIL_SET_SOCKET_ERROR(WSAEAFNOSUPPORT);
391 /* If the AF_UNIX socket does not work, we will change the
392 * family to AF_INET forcely. */
395 if (family == AF_UNIX)
396 return evutil_win_socketpair_afunix(family, type, protocol, fd);
399 return evutil_ersatz_socketpair_(family, type, protocol, fd);
404 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
407 return socketpair(family, type, protocol, fd);
409 return evutil_win_socketpair(family, type, protocol, fd);
414 evutil_ersatz_socketpair_(int family, int type, int protocol,
415 evutil_socket_t fd[2])
417 /* This code is originally from Tor. Used with permission. */
419 /* This socketpair does not work when localhost is down. So
420 * it's really not the same thing at all. But it's close enough
421 * for now, and really, when localhost is down sometimes, we
422 * have other problems too.
425 #define ERR(e) WSA##e
429 evutil_socket_t listener = -1;
430 evutil_socket_t connector = -1;
431 evutil_socket_t acceptor = -1;
432 struct sockaddr_in listen_addr;
433 struct sockaddr_in connect_addr;
435 int saved_errno = -1;
438 family_test = family != AF_INET;
440 family_test = family_test && (family != AF_UNIX);
442 if (protocol || family_test) {
443 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
448 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
452 listener = socket(AF_INET, type, 0);
455 memset(&listen_addr, 0, sizeof(listen_addr));
456 listen_addr.sin_family = AF_INET;
457 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
458 listen_addr.sin_port = 0; /* kernel chooses port. */
459 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
461 goto tidy_up_and_fail;
462 if (listen(listener, 1) == -1)
463 goto tidy_up_and_fail;
465 connector = socket(AF_INET, type, 0);
467 goto tidy_up_and_fail;
469 memset(&connect_addr, 0, sizeof(connect_addr));
471 /* We want to find out the port number to connect to. */
472 size = sizeof(connect_addr);
473 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
474 goto tidy_up_and_fail;
475 if (size != sizeof (connect_addr))
476 goto abort_tidy_up_and_fail;
477 if (connect(connector, (struct sockaddr *) &connect_addr,
478 sizeof(connect_addr)) == -1)
479 goto tidy_up_and_fail;
481 size = sizeof(listen_addr);
482 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
484 goto tidy_up_and_fail;
485 if (size != sizeof(listen_addr))
486 goto abort_tidy_up_and_fail;
487 /* Now check we are talking to ourself by matching port and host on the
489 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
490 goto tidy_up_and_fail;
491 if (size != sizeof (connect_addr)
492 || listen_addr.sin_family != connect_addr.sin_family
493 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
494 || listen_addr.sin_port != connect_addr.sin_port)
495 goto abort_tidy_up_and_fail;
496 evutil_closesocket(listener);
502 abort_tidy_up_and_fail:
503 saved_errno = ERR(ECONNABORTED);
506 saved_errno = EVUTIL_SOCKET_ERROR();
508 evutil_closesocket(listener);
510 evutil_closesocket(connector);
512 evutil_closesocket(acceptor);
514 EVUTIL_SET_SOCKET_ERROR(saved_errno);
520 evutil_make_socket_nonblocking(evutil_socket_t fd)
524 unsigned long nonblocking = 1;
525 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
526 event_sock_warn(fd, "ioctlsocket(%d, FIONBIO, &%lu)", (int)fd, (unsigned long)nonblocking);
533 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
534 event_warn("fcntl(%d, F_GETFL)", fd);
537 if (!(flags & O_NONBLOCK)) {
538 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
539 event_warn("fcntl(%d, F_SETFL)", fd);
548 /* Faster version of evutil_make_socket_nonblocking for internal use.
550 * Requires that no F_SETFL flags were previously set on the fd.
553 evutil_fast_socket_nonblocking(evutil_socket_t fd)
556 return evutil_make_socket_nonblocking(fd);
558 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
559 event_warn("fcntl(%d, F_SETFL)", fd);
567 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
569 #if defined(SO_REUSEADDR) && !defined(_WIN32)
571 /* REUSEADDR on Unix means, "don't hang on to this address after the
572 * listener is closed." On Windows, though, it means "don't keep other
573 * processes from binding to this address while we're using it. */
574 return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
575 (ev_socklen_t)sizeof(one));
582 evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
584 #if defined __linux__ && defined(SO_REUSEPORT)
586 /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
587 * threads) can bind to the same port if they each set the option. */
588 return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
589 (ev_socklen_t)sizeof(one));
596 evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
598 #if defined(IPV6_V6ONLY)
600 return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
601 (ev_socklen_t)sizeof(one));
607 evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
609 #if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
612 /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
613 * has arrived and ready to read */
614 return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
615 (ev_socklen_t)sizeof(one));
621 evutil_make_socket_closeonexec(evutil_socket_t fd)
623 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
625 if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
626 event_warn("fcntl(%d, F_GETFD)", fd);
629 if (!(flags & FD_CLOEXEC)) {
630 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
631 event_warn("fcntl(%d, F_SETFD)", fd);
639 /* Faster version of evutil_make_socket_closeonexec for internal use.
641 * Requires that no F_SETFD flags were previously set on the fd.
644 evutil_fast_socket_closeonexec(evutil_socket_t fd)
646 #if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
647 if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
648 event_warn("fcntl(%d, F_SETFD)", fd);
656 evutil_closesocket(evutil_socket_t sock)
661 return closesocket(sock);
666 evutil_strtoll(const char *s, char **endptr, int base)
668 #ifdef EVENT__HAVE_STRTOLL
669 return (ev_int64_t)strtoll(s, endptr, base);
670 #elif EVENT__SIZEOF_LONG == 8
671 return (ev_int64_t)strtol(s, endptr, base);
672 #elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
673 /* XXXX on old versions of MS APIs, we only support base
678 r = (ev_int64_t) _atoi64(s);
688 #elif defined(_WIN32)
689 return (ev_int64_t) _strtoi64(s, endptr, base);
690 #elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
693 if (base != 10 && base != 16)
696 n = sscanf(s, "%lld", &r);
698 unsigned long long ru=0;
699 n = sscanf(s, "%llx", &ru);
700 if (ru > EV_INT64_MAX)
706 while (EVUTIL_ISSPACE_(*s))
711 while (EVUTIL_ISDIGIT_(*s))
714 while (EVUTIL_ISXDIGIT_(*s))
721 #error "I don't know how to parse 64-bit integers."
727 evutil_socket_geterror(evutil_socket_t sock)
729 int optval, optvallen=sizeof(optval);
730 int err = WSAGetLastError();
731 if (err == WSAEWOULDBLOCK && sock >= 0) {
732 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
742 /* XXX we should use an enum here. */
743 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
745 evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
750 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
753 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
758 if (connect(*fd_ptr, sa, socklen) < 0) {
759 int e = evutil_socket_geterror(*fd_ptr);
760 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
762 if (EVUTIL_ERR_CONNECT_REFUSED(e))
771 evutil_closesocket(*fd_ptr);
777 /* Check whether a socket on which we called connect() is done
778 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
779 error case, set the current socket errno to the error that happened during
780 the connect operation. */
782 evutil_socket_finished_connecting_(evutil_socket_t fd)
785 ev_socklen_t elen = sizeof(e);
787 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
791 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
793 EVUTIL_SET_SOCKET_ERROR(e);
800 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
801 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
802 EVUTIL_AI_ADDRCONFIG) != \
803 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
804 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
805 EVUTIL_AI_ADDRCONFIG)
806 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
809 /* We sometimes need to know whether we have an ipv4 address and whether we
810 have an ipv6 address. If 'have_checked_interfaces', then we've already done
811 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
812 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
813 set by evutil_check_interfaces. */
814 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
816 /* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
817 static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
818 { return addr>>24 == 127; }
820 /* True iff the IPv4 address 'addr', in host order, is link-local
821 * 169.254.0.0/16 (RFC3927) */
822 static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
823 { return ((addr & 0xffff0000U) == 0xa9fe0000U); }
825 /* True iff the IPv4 address 'addr', in host order, is a class D
826 * (multiclass) address. */
827 static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
828 { return ((addr>>24) & 0xf0) == 0xe0; }
831 evutil_v4addr_is_local_(const struct in_addr *in)
833 const ev_uint32_t addr = ntohl(in->s_addr);
834 return addr == INADDR_ANY ||
835 evutil_v4addr_is_localhost(addr) ||
836 evutil_v4addr_is_linklocal(addr) ||
837 evutil_v4addr_is_classd(addr);
840 evutil_v6addr_is_local_(const struct in6_addr *in)
842 static const char ZEROES[] =
843 "\x00\x00\x00\x00\x00\x00\x00\x00"
844 "\x00\x00\x00\x00\x00\x00\x00\x00";
846 const unsigned char *addr = (const unsigned char *)in->s6_addr;
847 return !memcmp(addr, ZEROES, 8) ||
848 ((addr[0] & 0xfe) == 0xfc) ||
849 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
850 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
855 evutil_found_ifaddr(const struct sockaddr *sa)
857 if (sa->sa_family == AF_INET) {
858 const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
859 if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
860 event_debug(("Detected an IPv4 interface"));
861 had_ipv4_address = 1;
863 } else if (sa->sa_family == AF_INET6) {
864 const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
865 if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
866 event_debug(("Detected an IPv6 interface"));
867 had_ipv6_address = 1;
873 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
874 ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
878 evutil_check_ifaddrs(void)
880 #if defined(EVENT__HAVE_GETIFADDRS)
881 /* Most free Unixy systems provide getifaddrs, which gives us a linked list
882 * of struct ifaddrs. */
883 struct ifaddrs *ifa = NULL;
884 const struct ifaddrs *i;
885 if (getifaddrs(&ifa) < 0) {
886 event_warn("Unable to call getifaddrs()");
890 for (i = ifa; i; i = i->ifa_next) {
893 evutil_found_ifaddr(i->ifa_addr);
898 #elif defined(_WIN32)
899 /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
900 "GetAdaptersInfo", but that's deprecated; let's just try
901 GetAdaptersAddresses and fall back to connect+getsockname.
903 HMODULE lib = evutil_load_windows_system_library_(TEXT("iphlpapi.dll"));
904 GetAdaptersAddresses_fn_t fn;
906 IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
909 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
910 GAA_FLAG_SKIP_MULTICAST | \
911 GAA_FLAG_SKIP_DNS_SERVER)
916 if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
919 /* Guess how much space we need. */
921 addresses = mm_malloc(size);
924 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
925 if (res == ERROR_BUFFER_OVERFLOW) {
926 /* we didn't guess that we needed enough space; try again */
928 addresses = mm_malloc(size);
931 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
936 for (address = addresses; address; address = address->Next) {
937 IP_ADAPTER_UNICAST_ADDRESS *a;
938 for (a = address->FirstUnicastAddress; a; a = a->Next) {
939 /* Yes, it's a linked list inside a linked list */
940 struct sockaddr *sa = a->Address.lpSockaddr;
941 evutil_found_ifaddr(sa);
957 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
958 * the test seemed successful. */
960 evutil_check_interfaces(void)
962 evutil_socket_t fd = -1;
963 struct sockaddr_in sin, sin_out;
964 struct sockaddr_in6 sin6, sin6_out;
965 ev_socklen_t sin_out_len = sizeof(sin_out);
966 ev_socklen_t sin6_out_len = sizeof(sin6_out);
968 if (have_checked_interfaces)
971 /* From this point on we have done the ipv4/ipv6 interface check */
972 have_checked_interfaces = 1;
974 if (evutil_check_ifaddrs() == 0) {
975 /* Use a nice sane interface, if this system has one. */
979 /* Ugh. There was no nice sane interface. So to check whether we have
980 * an interface open for a given protocol, will try to make a UDP
981 * 'connection' to a remote host on the internet. We don't actually
982 * use it, so the address doesn't matter, but we want to pick one that
983 * keep us from using a host- or link-local interface. */
984 memset(&sin, 0, sizeof(sin));
985 sin.sin_family = AF_INET;
986 sin.sin_port = htons(53);
987 r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
990 memset(&sin6, 0, sizeof(sin6));
991 sin6.sin6_family = AF_INET6;
992 sin6.sin6_port = htons(53);
993 r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
996 memset(&sin_out, 0, sizeof(sin_out));
997 memset(&sin6_out, 0, sizeof(sin6_out));
999 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
1000 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
1001 connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
1002 getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
1003 /* We might have an IPv4 interface. */
1004 evutil_found_ifaddr((struct sockaddr*) &sin_out);
1007 evutil_closesocket(fd);
1009 if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
1010 connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
1011 getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
1012 /* We might have an IPv6 interface. */
1013 evutil_found_ifaddr((struct sockaddr*) &sin6_out);
1017 evutil_closesocket(fd);
1022 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
1023 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
1024 * it, and we should trust what they said.
1026 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
1028 /* Helper: construct a new addrinfo containing the socket address in
1029 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
1030 * socktype and protocol info from hints. If they weren't set, then
1031 * allocate both a TCP and a UDP addrinfo.
1033 struct evutil_addrinfo *
1034 evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
1035 const struct evutil_addrinfo *hints)
1037 struct evutil_addrinfo *res;
1038 EVUTIL_ASSERT(hints);
1040 if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
1041 /* Indecisive user! Give them a UDP and a TCP. */
1042 struct evutil_addrinfo *r1, *r2;
1043 struct evutil_addrinfo tmp;
1044 memcpy(&tmp, hints, sizeof(tmp));
1045 tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
1046 r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
1049 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
1050 r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
1052 evutil_freeaddrinfo(r1);
1059 /* We're going to allocate extra space to hold the sockaddr. */
1060 res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
1063 res->ai_addr = (struct sockaddr*)
1064 (((char*)res) + sizeof(struct evutil_addrinfo));
1065 memcpy(res->ai_addr, sa, socklen);
1066 res->ai_addrlen = socklen;
1067 res->ai_family = sa->sa_family; /* Same or not? XXX */
1068 res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
1069 res->ai_socktype = hints->ai_socktype;
1070 res->ai_protocol = hints->ai_protocol;
1075 /* Append the addrinfo 'append' to the end of 'first', and return the start of
1076 * the list. Either element can be NULL, in which case we return the element
1077 * that is not NULL. */
1078 struct evutil_addrinfo *
1079 evutil_addrinfo_append_(struct evutil_addrinfo *first,
1080 struct evutil_addrinfo *append)
1082 struct evutil_addrinfo *ai = first;
1087 ai->ai_next = append;
1093 parse_numeric_servname(const char *servname)
1097 n = (int) strtol(servname, &endptr, 10);
1098 if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
1104 /** Parse a service name in 'servname', which can be a decimal port.
1105 * Return the port number, or -1 on error.
1108 evutil_parse_servname(const char *servname, const char *protocol,
1109 const struct evutil_addrinfo *hints)
1111 int n = parse_numeric_servname(servname);
1114 #if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
1115 if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
1116 struct servent *ent = getservbyname(servname, protocol);
1118 return ntohs(ent->s_port);
1125 /* Return a string corresponding to a protocol number that we can pass to
1128 evutil_unparse_protoname(int proto)
1142 #ifdef EVENT__HAVE_GETPROTOBYNUMBER
1144 struct protoent *ent = getprotobynumber(proto);
1154 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
1156 /* If we can guess the protocol from the socktype, do so. */
1157 if (!hints->ai_protocol && hints->ai_socktype) {
1158 if (hints->ai_socktype == SOCK_DGRAM)
1159 hints->ai_protocol = IPPROTO_UDP;
1160 else if (hints->ai_socktype == SOCK_STREAM)
1161 hints->ai_protocol = IPPROTO_TCP;
1164 /* Set the socktype if it isn't set. */
1165 if (!hints->ai_socktype && hints->ai_protocol) {
1166 if (hints->ai_protocol == IPPROTO_UDP)
1167 hints->ai_socktype = SOCK_DGRAM;
1168 else if (hints->ai_protocol == IPPROTO_TCP)
1169 hints->ai_socktype = SOCK_STREAM;
1171 else if (hints->ai_protocol == IPPROTO_SCTP)
1172 hints->ai_socktype = SOCK_STREAM;
1177 #if AF_UNSPEC != PF_UNSPEC
1178 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
1181 /** Implements the part of looking up hosts by name that's common to both
1182 * the blocking and nonblocking resolver:
1183 * - Adjust 'hints' to have a reasonable socktype and protocol.
1184 * - Look up the port based on 'servname', and store it in *portnum,
1185 * - Handle the nodename==NULL case
1186 * - Handle some invalid arguments cases.
1187 * - Handle the cases where nodename is an IPv4 or IPv6 address.
1189 * If we need the resolver to look up the hostname, we return
1190 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
1191 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
1192 * set *res as getaddrinfo would.
1195 evutil_getaddrinfo_common_(const char *nodename, const char *servname,
1196 struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
1199 unsigned int if_index;
1202 if (nodename == NULL && servname == NULL)
1203 return EVUTIL_EAI_NONAME;
1205 /* We only understand 3 families */
1206 if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
1207 hints->ai_family != PF_INET6)
1208 return EVUTIL_EAI_FAMILY;
1210 evutil_getaddrinfo_infer_protocols(hints);
1212 /* Look up the port number and protocol, if possible. */
1213 pname = evutil_unparse_protoname(hints->ai_protocol);
1215 /* XXXX We could look at the protocol we got back from
1216 * getservbyname, but it doesn't seem too useful. */
1217 port = evutil_parse_servname(servname, pname, hints);
1219 return EVUTIL_EAI_NONAME;
1223 /* If we have no node name, then we're supposed to bind to 'any' and
1224 * connect to localhost. */
1225 if (nodename == NULL) {
1226 struct evutil_addrinfo *res4=NULL, *res6=NULL;
1227 if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
1228 struct sockaddr_in6 sin6;
1229 memset(&sin6, 0, sizeof(sin6));
1230 sin6.sin6_family = AF_INET6;
1231 sin6.sin6_port = htons(port);
1232 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1235 /* connect to ::1 */
1236 sin6.sin6_addr.s6_addr[15] = 1;
1238 res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1239 sizeof(sin6), hints);
1241 return EVUTIL_EAI_MEMORY;
1244 if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
1245 struct sockaddr_in sin;
1246 memset(&sin, 0, sizeof(sin));
1247 sin.sin_family = AF_INET;
1248 sin.sin_port = htons(port);
1249 if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1250 /* Bind to 0.0.0.0 */
1252 /* connect to 127.0.0.1 */
1253 sin.sin_addr.s_addr = htonl(0x7f000001);
1255 res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
1256 sizeof(sin), hints);
1259 evutil_freeaddrinfo(res6);
1260 return EVUTIL_EAI_MEMORY;
1263 *res = evutil_addrinfo_append_(res4, res6);
1267 /* If we can, we should try to parse the hostname without resolving
1270 if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
1271 struct sockaddr_in6 sin6;
1272 memset(&sin6, 0, sizeof(sin6));
1273 if (1 == evutil_inet_pton_scope(
1274 AF_INET6, nodename, &sin6.sin6_addr, &if_index)) {
1275 /* Got an ipv6 address. */
1276 sin6.sin6_family = AF_INET6;
1277 sin6.sin6_port = htons(port);
1278 sin6.sin6_scope_id = if_index;
1279 *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1280 sizeof(sin6), hints);
1282 return EVUTIL_EAI_MEMORY;
1288 if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
1289 struct sockaddr_in sin;
1290 memset(&sin, 0, sizeof(sin));
1291 if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
1292 /* Got an ipv4 address. */
1293 sin.sin_family = AF_INET;
1294 sin.sin_port = htons(port);
1295 *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
1296 sizeof(sin), hints);
1298 return EVUTIL_EAI_MEMORY;
1304 /* If we have reached this point, we definitely need to do a DNS
1306 if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
1307 /* If we're not allowed to do one, then say so. */
1308 return EVUTIL_EAI_NONAME;
1311 return EVUTIL_EAI_NEED_RESOLVE;
1314 #ifdef EVENT__HAVE_GETADDRINFO
1315 #define USE_NATIVE_GETADDRINFO
1318 #ifdef USE_NATIVE_GETADDRINFO
1319 /* A mask of all the flags that we declare, so we can clear them before calling
1320 * the native getaddrinfo */
1321 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
1325 #ifndef AI_CANONNAME
1326 EVUTIL_AI_CANONNAME |
1328 #ifndef AI_NUMERICHOST
1329 EVUTIL_AI_NUMERICHOST |
1331 #ifndef AI_NUMERICSERV
1332 EVUTIL_AI_NUMERICSERV |
1334 #ifndef AI_ADDRCONFIG
1335 EVUTIL_AI_ADDRCONFIG |
1341 EVUTIL_AI_V4MAPPED |
1343 EVUTIL_AI_LIBEVENT_ALLOCATED;
1345 static const unsigned int ALL_NATIVE_AI_FLAGS =
1352 #ifdef AI_NUMERICHOST
1355 #ifdef AI_NUMERICSERV
1358 #ifdef AI_ADDRCONFIG
1370 #ifndef USE_NATIVE_GETADDRINFO
1371 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1374 static struct evutil_addrinfo *
1375 addrinfo_from_hostent(const struct hostent *ent,
1376 int port, const struct evutil_addrinfo *hints)
1379 struct sockaddr_in sin;
1380 struct sockaddr_in6 sin6;
1381 struct sockaddr *sa;
1383 struct evutil_addrinfo *res=NULL, *ai;
1386 if (ent->h_addrtype == PF_INET) {
1387 memset(&sin, 0, sizeof(sin));
1388 sin.sin_family = AF_INET;
1389 sin.sin_port = htons(port);
1390 sa = (struct sockaddr *)&sin;
1391 socklen = sizeof(struct sockaddr_in);
1392 addrp = &sin.sin_addr;
1393 if (ent->h_length != sizeof(sin.sin_addr)) {
1394 event_warnx("Weird h_length from gethostbyname");
1397 } else if (ent->h_addrtype == PF_INET6) {
1398 memset(&sin6, 0, sizeof(sin6));
1399 sin6.sin6_family = AF_INET6;
1400 sin6.sin6_port = htons(port);
1401 sa = (struct sockaddr *)&sin6;
1402 socklen = sizeof(struct sockaddr_in6);
1403 addrp = &sin6.sin6_addr;
1404 if (ent->h_length != sizeof(sin6.sin6_addr)) {
1405 event_warnx("Weird h_length from gethostbyname");
1411 for (i = 0; ent->h_addr_list[i]; ++i) {
1412 memcpy(addrp, ent->h_addr_list[i], ent->h_length);
1413 ai = evutil_new_addrinfo_(sa, socklen, hints);
1415 evutil_freeaddrinfo(res);
1418 res = evutil_addrinfo_append_(res, ai);
1421 if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1422 res->ai_canonname = mm_strdup(ent->h_name);
1423 if (res->ai_canonname == NULL) {
1424 evutil_freeaddrinfo(res);
1433 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1434 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1435 * that we'll only get addresses we could maybe connect to.
1438 evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
1440 if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1442 if (hints->ai_family != PF_UNSPEC)
1444 evutil_check_interfaces();
1445 if (had_ipv4_address && !had_ipv6_address) {
1446 hints->ai_family = PF_INET;
1447 } else if (!had_ipv4_address && had_ipv6_address) {
1448 hints->ai_family = PF_INET6;
1452 #ifdef USE_NATIVE_GETADDRINFO
1453 static int need_numeric_port_hack_=0;
1454 static int need_socktype_protocol_hack_=0;
1455 static int tested_for_getaddrinfo_hacks=0;
1457 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1458 giving a numeric port without giving an ai_socktype was verboten.
1459 We test for this so we can apply an appropriate workaround. If it
1460 turns out that the bug is present, then:
1462 - If nodename==NULL and servname is numeric, we build an answer
1463 ourselves using evutil_getaddrinfo_common_().
1465 - If nodename!=NULL and servname is numeric, then we set
1466 servname=NULL when calling getaddrinfo, and post-process the
1467 result to set the ports on it.
1469 We test for this bug at runtime, since otherwise we can't have the
1470 same binary run on multiple BSD versions.
1472 - Some versions of Solaris believe that it's nice to leave to protocol
1473 field set to 0. We test for this so we can apply an appropriate
1476 static struct evutil_addrinfo *ai_find_protocol(struct evutil_addrinfo *ai)
1479 if (ai->ai_protocol)
1486 test_for_getaddrinfo_hacks(void)
1489 struct evutil_addrinfo *ai=NULL, *ai2=NULL, *ai3=NULL;
1490 struct evutil_addrinfo hints;
1492 memset(&hints,0,sizeof(hints));
1493 hints.ai_family = PF_UNSPEC;
1495 #ifdef AI_NUMERICHOST
1498 #ifdef AI_NUMERICSERV
1502 r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1503 getaddrinfo("1.2.3.4", NULL, &hints, &ai3);
1504 hints.ai_socktype = SOCK_STREAM;
1505 r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1506 if (r2 == 0 && r != 0) {
1507 need_numeric_port_hack_=1;
1509 if (!ai_find_protocol(ai2) || !ai_find_protocol(ai3)) {
1510 need_socktype_protocol_hack_=1;
1519 tested_for_getaddrinfo_hacks=1;
1523 need_numeric_port_hack(void)
1525 if (!tested_for_getaddrinfo_hacks)
1526 test_for_getaddrinfo_hacks();
1527 return need_numeric_port_hack_;
1531 need_socktype_protocol_hack(void)
1533 if (!tested_for_getaddrinfo_hacks)
1534 test_for_getaddrinfo_hacks();
1535 return need_socktype_protocol_hack_;
1539 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1541 /* Now we run through the list and set the ports on all of the
1542 * results where ports would make sense. */
1543 for ( ; *ai; ai = &(*ai)->ai_next) {
1544 struct sockaddr *sa = (*ai)->ai_addr;
1545 if (sa && sa->sa_family == AF_INET) {
1546 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1547 sin->sin_port = htons(port);
1548 } else if (sa && sa->sa_family == AF_INET6) {
1549 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1550 sin6->sin6_port = htons(port);
1552 /* A numeric port makes no sense here; remove this one
1554 struct evutil_addrinfo *victim = *ai;
1555 *ai = victim->ai_next;
1556 victim->ai_next = NULL;
1557 freeaddrinfo(victim);
1563 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1565 struct evutil_addrinfo *ai_new;
1566 for (; ai; ai = ai->ai_next) {
1567 evutil_getaddrinfo_infer_protocols(ai);
1568 if (ai->ai_socktype || ai->ai_protocol)
1570 ai_new = mm_malloc(sizeof(*ai_new));
1573 memcpy(ai_new, ai, sizeof(*ai_new));
1574 ai->ai_socktype = SOCK_STREAM;
1575 ai->ai_protocol = IPPROTO_TCP;
1576 ai_new->ai_socktype = SOCK_DGRAM;
1577 ai_new->ai_protocol = IPPROTO_UDP;
1578 ai_new->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
1579 if (ai_new->ai_canonname != NULL) {
1580 ai_new->ai_canonname = mm_strdup(ai_new->ai_canonname);
1581 if (ai_new->ai_canonname == NULL) {
1587 ai_new->ai_next = ai->ai_next;
1588 ai->ai_next = ai_new;
1595 evutil_getaddrinfo(const char *nodename, const char *servname,
1596 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1598 #ifdef USE_NATIVE_GETADDRINFO
1599 struct evutil_addrinfo hints;
1600 int portnum=-1, need_np_hack, err;
1603 memcpy(&hints, hints_in, sizeof(hints));
1605 memset(&hints, 0, sizeof(hints));
1606 hints.ai_family = PF_UNSPEC;
1609 #ifndef AI_ADDRCONFIG
1610 /* Not every system has AI_ADDRCONFIG, so fake it. */
1611 if (hints.ai_family == PF_UNSPEC &&
1612 (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1613 evutil_adjust_hints_for_addrconfig_(&hints);
1617 #ifndef AI_NUMERICSERV
1618 /* Not every system has AI_NUMERICSERV, so fake it. */
1619 if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1620 if (servname && parse_numeric_servname(servname)<0)
1621 return EVUTIL_EAI_NONAME;
1625 /* Enough operating systems handle enough common non-resolve
1626 * cases here weirdly enough that we are better off just
1627 * overriding them. For example:
1629 * - Windows doesn't like to infer the protocol from the
1630 * socket type, or fill in socket or protocol types much at
1631 * all. It also seems to do its own broken implicit
1632 * always-on version of AI_ADDRCONFIG that keeps it from
1633 * ever resolving even a literal IPv6 address when
1634 * ai_addrtype is PF_UNSPEC.
1639 err = evutil_getaddrinfo_common_(nodename,servname,&hints,
1642 err == EVUTIL_EAI_MEMORY ||
1643 err == EVUTIL_EAI_NONAME)
1645 /* If we make it here, the system getaddrinfo can
1646 * have a crack at it. */
1650 /* See documentation for need_numeric_port_hack above.*/
1651 need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1652 && ((portnum=parse_numeric_servname(servname)) >= 0);
1655 return evutil_getaddrinfo_common_(
1656 NULL,servname,&hints, res, &portnum);
1660 if (need_socktype_protocol_hack()) {
1661 evutil_getaddrinfo_infer_protocols(&hints);
1664 /* Make sure that we didn't actually steal any AI_FLAGS values that
1665 * the system is using. (This is a constant expression, and should ge
1668 * XXXX Turn this into a compile-time failure rather than a run-time
1671 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1673 /* Clear any flags that only libevent understands. */
1674 hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1676 err = getaddrinfo(nodename, servname, &hints, res);
1678 apply_numeric_port_hack(portnum, res);
1680 if (need_socktype_protocol_hack()) {
1681 if (apply_socktype_protocol_hack(*res) < 0) {
1682 evutil_freeaddrinfo(*res);
1684 return EVUTIL_EAI_MEMORY;
1690 struct hostent *ent = NULL;
1691 struct evutil_addrinfo hints;
1694 memcpy(&hints, hints_in, sizeof(hints));
1696 memset(&hints, 0, sizeof(hints));
1697 hints.ai_family = PF_UNSPEC;
1700 evutil_adjust_hints_for_addrconfig_(&hints);
1702 err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
1703 if (err != EVUTIL_EAI_NEED_RESOLVE) {
1704 /* We either succeeded or failed. No need to continue */
1709 /* Use any of the various gethostbyname_r variants as available. */
1711 #ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1712 /* This one is what glibc provides. */
1714 struct hostent hostent;
1716 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1718 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1720 struct hostent hostent;
1721 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1723 #elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1724 struct hostent_data data;
1725 struct hostent hostent;
1726 memset(&data, 0, sizeof(data));
1727 err = gethostbyname_r(nodename, &hostent, &data);
1728 ent = err ? NULL : &hostent;
1730 /* fall back to gethostbyname. */
1731 /* XXXX This needs a lock everywhere but Windows. */
1732 ent = gethostbyname(nodename);
1734 err = WSAGetLastError();
1740 /* Now we have either ent or err set. */
1742 /* XXX is this right for windows ? */
1745 return EVUTIL_EAI_AGAIN;
1748 return EVUTIL_EAI_FAIL;
1749 case HOST_NOT_FOUND:
1750 return EVUTIL_EAI_NONAME;
1752 #if NO_DATA != NO_ADDRESS
1755 return EVUTIL_EAI_NODATA;
1759 if (ent->h_addrtype != hints.ai_family &&
1760 hints.ai_family != PF_UNSPEC) {
1761 /* This wasn't the type we were hoping for. Too bad
1762 * we never had a chance to ask gethostbyname for what
1764 return EVUTIL_EAI_NONAME;
1767 /* Make sure we got _some_ answers. */
1768 if (ent->h_length == 0)
1769 return EVUTIL_EAI_NODATA;
1771 /* If we got an address type we don't know how to make a
1772 sockaddr for, give up. */
1773 if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1774 return EVUTIL_EAI_FAMILY;
1776 *res = addrinfo_from_hostent(ent, port, &hints);
1778 return EVUTIL_EAI_MEMORY;
1786 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1788 #ifdef EVENT__HAVE_GETADDRINFO
1789 struct evutil_addrinfo *ai_prev = NULL;
1790 struct evutil_addrinfo *ai_temp = ai;
1791 /* Linked list may be the result of a native getaddrinfo() call plus
1792 * locally allocated nodes, Before releasing it using freeaddrinfo(),
1793 * these custom structs need to be freed separately.
1796 struct evutil_addrinfo *next = ai_temp->ai_next;
1797 if (ai_temp->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED) {
1798 /* Remove this node from the linked list */
1799 if (ai_temp->ai_canonname)
1800 mm_free(ai_temp->ai_canonname);
1802 if (ai_prev == NULL) {
1805 ai_prev->ai_next = next;
1817 struct evutil_addrinfo *next = ai->ai_next;
1818 if (ai->ai_canonname)
1819 mm_free(ai->ai_canonname);
1826 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1827 static evdns_getaddrinfo_cancel_fn evdns_getaddrinfo_cancel_impl = NULL;
1830 evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
1832 if (!evdns_getaddrinfo_impl)
1833 evdns_getaddrinfo_impl = fn;
1836 evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn)
1838 if (!evdns_getaddrinfo_cancel_impl)
1839 evdns_getaddrinfo_cancel_impl = fn;
1842 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1843 * otherwise do a blocking resolve and pass the result to the callback in the
1844 * way that evdns_getaddrinfo would.
1846 struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
1847 struct evdns_base *dns_base,
1848 const char *nodename, const char *servname,
1849 const struct evutil_addrinfo *hints_in,
1850 void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1852 if (dns_base && evdns_getaddrinfo_impl) {
1853 return evdns_getaddrinfo_impl(
1854 dns_base, nodename, servname, hints_in, cb, arg);
1856 struct evutil_addrinfo *ai=NULL;
1858 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1864 void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data)
1866 if (evdns_getaddrinfo_cancel_impl && data) {
1867 evdns_getaddrinfo_cancel_impl(data);
1872 evutil_gai_strerror(int err)
1874 /* As a sneaky side-benefit, this case statement will get most
1875 * compilers to tell us if any of the error codes we defined
1876 * conflict with the platform's native error codes. */
1878 case EVUTIL_EAI_CANCEL:
1879 return "Request canceled";
1883 case EVUTIL_EAI_ADDRFAMILY:
1884 return "address family for nodename not supported";
1885 case EVUTIL_EAI_AGAIN:
1886 return "temporary failure in name resolution";
1887 case EVUTIL_EAI_BADFLAGS:
1888 return "invalid value for ai_flags";
1889 case EVUTIL_EAI_FAIL:
1890 return "non-recoverable failure in name resolution";
1891 case EVUTIL_EAI_FAMILY:
1892 return "ai_family not supported";
1893 case EVUTIL_EAI_MEMORY:
1894 return "memory allocation failure";
1895 case EVUTIL_EAI_NODATA:
1896 return "no address associated with nodename";
1897 case EVUTIL_EAI_NONAME:
1898 return "nodename nor servname provided, or not known";
1899 case EVUTIL_EAI_SERVICE:
1900 return "servname not supported for ai_socktype";
1901 case EVUTIL_EAI_SOCKTYPE:
1902 return "ai_socktype not supported";
1903 case EVUTIL_EAI_SYSTEM:
1904 return "system error";
1906 #if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1907 return gai_strerrorA(err);
1908 #elif defined(USE_NATIVE_GETADDRINFO)
1909 return gai_strerror(err);
1911 return "Unknown error code";
1917 /* destructively remove a trailing line terminator from s */
1922 if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
1924 if (len > 0 && s[len - 1] == '\r')
1929 /* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1930 * is supposed to return a string which is good indefinitely without having
1931 * to be freed. To make this work without leaking memory, we cache the
1932 * string the first time FormatMessage is called on a particular error
1933 * code, and then return the cached string on subsequent calls with the
1934 * same code. The strings aren't freed until libevent_global_shutdown
1935 * (or never). We use a linked list to cache the errors, because we
1936 * only expect there to be a few dozen, and that should be fast enough.
1939 struct cached_sock_errs_entry {
1940 HT_ENTRY(cached_sock_errs_entry) node;
1942 char *msg; /* allocated with LocalAlloc; free with LocalFree */
1945 static inline unsigned
1946 hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
1948 /* Use Murmur3's 32-bit finalizer as an integer hash function */
1959 eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
1960 const struct cached_sock_errs_entry *b)
1962 return a->code == b->code;
1965 #ifndef EVENT__DISABLE_THREAD_SUPPORT
1966 static void *windows_socket_errors_lock_ = NULL;
1969 static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
1970 windows_socket_errors = HT_INITIALIZER();
1972 HT_PROTOTYPE(cached_sock_errs_map,
1973 cached_sock_errs_entry,
1975 hash_cached_sock_errs,
1976 eq_cached_sock_errs);
1978 HT_GENERATE(cached_sock_errs_map,
1979 cached_sock_errs_entry,
1981 hash_cached_sock_errs,
1982 eq_cached_sock_errs,
1988 /** Equivalent to strerror, but for windows socket errors. */
1990 evutil_socket_error_to_string(int errcode)
1992 struct cached_sock_errs_entry *errs, *newerr, find;
1995 EVLOCK_LOCK(windows_socket_errors_lock_, 0);
1997 find.code = errcode;
1998 errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
2004 if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
2005 FORMAT_MESSAGE_IGNORE_INSERTS |
2006 FORMAT_MESSAGE_ALLOCATE_BUFFER,
2007 NULL, errcode, 0, (char *)&msg, 0, NULL))
2008 chomp (msg); /* because message has trailing newline */
2011 /* use LocalAlloc because FormatMessage does */
2012 msg = LocalAlloc(LMEM_FIXED, len);
2014 msg = (char *)"LocalAlloc failed during Winsock error";
2017 evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
2020 newerr = (struct cached_sock_errs_entry *)
2021 mm_malloc(sizeof (struct cached_sock_errs_entry));
2025 msg = (char *)"malloc failed during Winsock error";
2029 newerr->code = errcode;
2031 HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
2034 EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
2039 #ifndef EVENT__DISABLE_THREAD_SUPPORT
2041 evutil_global_setup_locks_(const int enable_locks)
2043 EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
2049 evutil_free_sock_err_globals(void)
2051 struct cached_sock_errs_entry **errs, *tofree;
2053 for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
2056 errs = HT_NEXT_RMV(cached_sock_errs_map,
2057 &windows_socket_errors,
2059 LocalFree(tofree->msg);
2063 HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
2065 #ifndef EVENT__DISABLE_THREAD_SUPPORT
2066 if (windows_socket_errors_lock_ != NULL) {
2067 EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
2068 windows_socket_errors_lock_ = NULL;
2075 #ifndef EVENT__DISABLE_THREAD_SUPPORT
2077 evutil_global_setup_locks_(const int enable_locks)
2084 evutil_free_sock_err_globals(void)
2091 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
2095 va_start(ap, format);
2096 r = evutil_vsnprintf(buf, buflen, format, ap);
2102 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
2107 #if defined(_MSC_VER) || defined(_WIN32)
2108 r = _vsnprintf(buf, buflen, format, ap);
2110 r = _vscprintf(format, ap);
2112 /* Make sure we always use the correct vsnprintf on IRIX */
2113 extern int _xpg5_vsnprintf(char * __restrict,
2114 __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
2115 const char * __restrict, /* va_list */ char *);
2117 r = _xpg5_vsnprintf(buf, buflen, format, ap);
2119 r = vsnprintf(buf, buflen, format, ap);
2121 buf[buflen-1] = '\0';
2125 #define USE_INTERNAL_NTOP
2126 #define USE_INTERNAL_PTON
2129 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
2131 #if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
2132 return inet_ntop(af, src, dst, len);
2134 if (af == AF_INET) {
2135 const struct in_addr *in = src;
2136 const ev_uint32_t a = ntohl(in->s_addr);
2138 r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
2139 (int)(ev_uint8_t)((a>>24)&0xff),
2140 (int)(ev_uint8_t)((a>>16)&0xff),
2141 (int)(ev_uint8_t)((a>>8 )&0xff),
2142 (int)(ev_uint8_t)((a )&0xff));
2143 if (r<0||(size_t)r>=len)
2148 } else if (af == AF_INET6) {
2149 const struct in6_addr *addr = src;
2151 int longestGapLen = 0, longestGapPos = -1, i,
2152 curGapPos = -1, curGapLen = 0;
2153 ev_uint16_t words[8];
2154 for (i = 0; i < 8; ++i) {
2156 (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
2158 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
2159 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
2160 (words[5] == 0xffff))) {
2161 /* This is an IPv4 address. */
2162 if (words[5] == 0) {
2163 evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
2164 addr->s6_addr[12], addr->s6_addr[13],
2165 addr->s6_addr[14], addr->s6_addr[15]);
2167 evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
2168 addr->s6_addr[12], addr->s6_addr[13],
2169 addr->s6_addr[14], addr->s6_addr[15]);
2171 if (strlen(buf) > len)
2173 strlcpy(dst, buf, len);
2178 if (words[i] == 0) {
2181 while (i<8 && words[i] == 0) {
2184 if (curGapLen > longestGapLen) {
2185 longestGapPos = curGapPos;
2186 longestGapLen = curGapLen;
2192 if (longestGapLen<=1)
2196 for (i = 0; i < 8; ++i) {
2197 if (words[i] == 0 && longestGapPos == i) {
2201 while (i < 8 && words[i] == 0)
2203 --i; /* to compensate for loop increment. */
2206 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
2213 if (strlen(buf) > len)
2215 strlcpy(dst, buf, len);
2225 evutil_inet_pton_scope(int af, const char *src, void *dst, unsigned *indexp)
2229 char *check, *cp, *tmp_src;
2231 *indexp = 0; /* Reasonable default */
2233 /* Bail out if not IPv6 */
2235 return evutil_inet_pton(af, src, dst);
2237 cp = strchr(src, '%');
2239 /* Bail out if no zone ID */
2241 return evutil_inet_pton(af, src, dst);
2243 if_index = if_nametoindex(cp + 1);
2244 if (if_index == 0) {
2245 /* Could be numeric */
2246 if_index = strtoul(cp + 1, &check, 10);
2247 if (check[0] != '\0')
2251 if (!(tmp_src = mm_strdup(src))) {
2254 cp = strchr(tmp_src, '%');
2256 r = evutil_inet_pton(af, tmp_src, dst);
2262 evutil_inet_pton(int af, const char *src, void *dst)
2264 #if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
2265 return inet_pton(af, src, dst);
2267 if (af == AF_INET) {
2270 struct in_addr *addr = dst;
2271 if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
2273 if (a > 255) return 0;
2274 if (b > 255) return 0;
2275 if (c > 255) return 0;
2276 if (d > 255) return 0;
2277 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
2280 } else if (af == AF_INET6) {
2281 struct in6_addr *out = dst;
2282 ev_uint16_t words[8];
2283 int gapPos = -1, i, setWords=0;
2284 const char *dot = strchr(src, '.');
2285 const char *eow; /* end of words. */
2289 eow = src+strlen(src);
2291 unsigned byte1,byte2,byte3,byte4;
2293 for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
2297 /* We use "scanf" because some platform inet_aton()s are too lax
2298 * about IPv4 addresses of the form "1.2.3" */
2299 if (sscanf(eow, "%u.%u.%u.%u%c",
2300 &byte1,&byte2,&byte3,&byte4,&more) != 4)
2309 words[6] = (byte1<<8) | byte2;
2310 words[7] = (byte3<<8) | byte4;
2318 if (EVUTIL_ISXDIGIT_(*src)) {
2320 long r = strtol(src, &next, 16);
2328 words[i++] = (ev_uint16_t)r;
2331 if (*src != ':' && src != eow)
2334 } else if (*src == ':' && i > 0 && gapPos==-1) {
2337 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
2346 (setWords == 8 && gapPos != -1) ||
2347 (setWords < 8 && gapPos == -1))
2351 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2352 int gapLen = 8 - setWords;
2353 /* assert(nToMove >= 0); */
2355 return -1; /* should be impossible */
2356 memmove(&words[gapPos+gapLen], &words[gapPos],
2357 sizeof(ev_uint16_t)*nToMove);
2358 memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
2360 for (i = 0; i < 8; ++i) {
2361 out->s6_addr[2*i ] = words[i] >> 8;
2362 out->s6_addr[2*i+1] = words[i] & 0xff;
2374 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
2377 unsigned int if_index;
2379 const char *cp, *addr_part, *port_part;
2381 /* recognized formats are:
2389 cp = strchr(ip_as_string, ':');
2390 if (*ip_as_string == '[') {
2392 if (!(cp = strchr(ip_as_string, ']'))) {
2395 len = ( cp-(ip_as_string + 1) );
2396 if (len > sizeof(buf)-1) {
2399 memcpy(buf, ip_as_string+1, len);
2407 } else if (cp && strchr(cp+1, ':')) {
2409 addr_part = ip_as_string;
2413 if (cp - ip_as_string > (int)sizeof(buf)-1) {
2416 memcpy(buf, ip_as_string, cp-ip_as_string);
2417 buf[cp-ip_as_string] = '\0';
2421 addr_part = ip_as_string;
2426 if (port_part == NULL) {
2429 port = atoi(port_part);
2430 if (port <= 0 || port > 65535) {
2436 return -1; /* Should be impossible. */
2440 struct sockaddr_in6 sin6;
2441 memset(&sin6, 0, sizeof(sin6));
2442 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2443 sin6.sin6_len = sizeof(sin6);
2445 sin6.sin6_family = AF_INET6;
2446 sin6.sin6_port = htons(port);
2447 if (1 != evutil_inet_pton_scope(
2448 AF_INET6, addr_part, &sin6.sin6_addr, &if_index)) {
2451 if ((int)sizeof(sin6) > *outlen)
2453 sin6.sin6_scope_id = if_index;
2454 memset(out, 0, *outlen);
2455 memcpy(out, &sin6, sizeof(sin6));
2456 *outlen = sizeof(sin6);
2462 struct sockaddr_in sin;
2463 memset(&sin, 0, sizeof(sin));
2464 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2465 sin.sin_len = sizeof(sin);
2467 sin.sin_family = AF_INET;
2468 sin.sin_port = htons(port);
2469 if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
2471 if ((int)sizeof(sin) > *outlen)
2473 memset(out, 0, *outlen);
2474 memcpy(out, &sin, sizeof(sin));
2475 *outlen = sizeof(sin);
2481 evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
2484 const char *res=NULL;
2486 if (sa->sa_family == AF_INET) {
2487 const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
2488 res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
2489 port = ntohs(sin->sin_port);
2491 evutil_snprintf(out, outlen, "%s:%d", b, port);
2494 } else if (sa->sa_family == AF_INET6) {
2495 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
2496 res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
2497 port = ntohs(sin6->sin6_port);
2499 evutil_snprintf(out, outlen, "[%s]:%d", b, port);
2504 evutil_snprintf(out, outlen, "<addr with socktype %d>",
2505 (int)sa->sa_family);
2510 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
2514 if (0 != (r = (sa1->sa_family - sa2->sa_family)))
2517 if (sa1->sa_family == AF_INET) {
2518 const struct sockaddr_in *sin1, *sin2;
2519 sin1 = (const struct sockaddr_in *)sa1;
2520 sin2 = (const struct sockaddr_in *)sa2;
2521 if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
2523 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
2525 else if (include_port &&
2526 (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
2532 else if (sa1->sa_family == AF_INET6) {
2533 const struct sockaddr_in6 *sin1, *sin2;
2534 sin1 = (const struct sockaddr_in6 *)sa1;
2535 sin2 = (const struct sockaddr_in6 *)sa2;
2536 if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
2538 else if (include_port &&
2539 (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
2548 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
2549 * has 256 bits to look up whether a character is in some set or not. This
2550 * fails on non-ASCII platforms, but so does every other place where we
2551 * take a char and write it onto the network.
2553 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
2554 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2555 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
2556 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2557 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2558 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
2559 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2560 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2561 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
2562 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2563 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2564 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2565 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
2567 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
2568 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2569 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2570 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2571 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2572 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2573 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2574 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2575 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2576 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2577 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2578 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2579 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2580 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2581 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2582 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2583 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2585 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
2586 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2587 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2588 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2589 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2590 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2591 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2592 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2593 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2594 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2595 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2596 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2597 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2598 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2599 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2600 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2601 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2604 #define IMPL_CTYPE_FN(name) \
2605 int EVUTIL_##name##_(char c) { \
2607 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1U << (u & 31))); \
2609 IMPL_CTYPE_FN(ISALPHA)
2610 IMPL_CTYPE_FN(ISALNUM)
2611 IMPL_CTYPE_FN(ISSPACE)
2612 IMPL_CTYPE_FN(ISDIGIT)
2613 IMPL_CTYPE_FN(ISXDIGIT)
2614 IMPL_CTYPE_FN(ISPRINT)
2615 IMPL_CTYPE_FN(ISLOWER)
2616 IMPL_CTYPE_FN(ISUPPER)
2618 char EVUTIL_TOLOWER_(char c)
2620 return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2622 char EVUTIL_TOUPPER_(char c)
2624 return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2627 evutil_ascii_strcasecmp(const char *s1, const char *s2)
2631 c1 = EVUTIL_TOLOWER_(*s1++);
2632 c2 = EVUTIL_TOLOWER_(*s2++);
2641 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2645 c1 = EVUTIL_TOLOWER_(*s1++);
2646 c2 = EVUTIL_TOLOWER_(*s2++);
2658 evutil_rtrim_lws_(char *str)
2665 if ((cp = strchr(str, '\0')) == NULL || (cp == str))
2670 while (*cp == ' ' || *cp == '\t') {
2679 evutil_issetugid(void)
2681 #ifdef EVENT__HAVE_ISSETUGID
2685 #ifdef EVENT__HAVE_GETEUID
2686 if (getuid() != geteuid())
2689 #ifdef EVENT__HAVE_GETEGID
2690 if (getgid() != getegid())
2698 evutil_getenv_(const char *varname)
2700 if (evutil_issetugid())
2703 return getenv(varname);
2707 evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
2711 evutil_gettimeofday(&tv, NULL);
2712 seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
2714 seed += (ev_uint32_t) _getpid();
2716 seed += (ev_uint32_t) getpid();
2724 evutil_weakrand_(struct evutil_weakrand_state *state)
2726 /* This RNG implementation is a linear congruential generator, with
2727 * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
2728 * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2730 * The linear congruential generator is not an industrial-strength
2731 * RNG! It's fast, but it can have higher-order patterns. Notably,
2732 * the low bits tend to have periodicity.
2734 state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
2735 return (ev_int32_t)(state->seed);
2739 evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
2741 ev_int32_t divisor, result;
2743 /* We can't just do weakrand() % top, since the low bits of the LCG
2744 * are less random than the high ones. (Specifically, since the LCG
2745 * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2746 * therefore the low m bits of the LCG will have period 2^m.) */
2747 divisor = EVUTIL_WEAKRAND_MAX / top;
2749 result = evutil_weakrand_(state) / divisor;
2750 } while (result >= top);
2755 * Volatile pointer to memset: we use this to keep the compiler from
2756 * eliminating our call to memset.
2758 void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
2761 evutil_memclear_(void *mem, size_t len)
2763 evutil_memset_volatile_(mem, 0, len);
2767 evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
2769 static const char LOOPBACK_S6[16] =
2770 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2771 if (addr->sa_family == AF_INET) {
2772 struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2773 return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2774 } else if (addr->sa_family == AF_INET6) {
2775 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2776 return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2782 evutil_hex_char_to_int_(char c)
2796 case 'A': case 'a': return 10;
2797 case 'B': case 'b': return 11;
2798 case 'C': case 'c': return 12;
2799 case 'D': case 'd': return 13;
2800 case 'E': case 'e': return 14;
2801 case 'F': case 'f': return 15;
2808 evutil_load_windows_system_library_(const TCHAR *library_name)
2810 TCHAR path[MAX_PATH];
2812 n = GetSystemDirectory(path, MAX_PATH);
2813 if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2815 _tcscat(path, TEXT("\\"));
2816 _tcscat(path, library_name);
2817 return LoadLibrary(path);
2821 /* Internal wrapper around 'socket' to provide Linux-style support for
2822 * syscall-saving methods where available.
2824 * In addition to regular socket behavior, you can use a bitwise or to set the
2825 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2826 * to make the socket nonblocking or close-on-exec with as few syscalls as
2830 evutil_socket_(int domain, int type, int protocol)
2833 #if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2834 r = socket(domain, type, protocol);
2837 else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
2840 #define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2841 r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
2844 if (type & EVUTIL_SOCK_NONBLOCK) {
2845 if (evutil_fast_socket_nonblocking(r) < 0) {
2846 evutil_closesocket(r);
2850 if (type & EVUTIL_SOCK_CLOEXEC) {
2851 if (evutil_fast_socket_closeonexec(r) < 0) {
2852 evutil_closesocket(r);
2859 /* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2860 * support for syscall-saving methods where available.
2862 * In addition to regular accept behavior, you can set one or more of flags
2863 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2864 * make the socket nonblocking or close-on-exec with as few syscalls as
2868 evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
2869 ev_socklen_t *addrlen, int flags)
2871 evutil_socket_t result;
2872 #if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2873 result = accept4(sockfd, addr, addrlen, flags);
2874 if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
2875 /* A nonnegative result means that we succeeded, so return.
2876 * Failing with EINVAL means that an option wasn't supported,
2877 * and failing with ENOSYS means that the syscall wasn't
2878 * there: in those cases we want to fall back. Otherwise, we
2879 * got a real error, and we should return. */
2883 result = accept(sockfd, addr, addrlen);
2887 if (flags & EVUTIL_SOCK_CLOEXEC) {
2888 if (evutil_fast_socket_closeonexec(result) < 0) {
2889 evutil_closesocket(result);
2893 if (flags & EVUTIL_SOCK_NONBLOCK) {
2894 if (evutil_fast_socket_nonblocking(result) < 0) {
2895 evutil_closesocket(result);
2902 /* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2903 * fd[1] get read from fd[0]. Make both fds nonblocking and close-on-exec.
2904 * Return 0 on success, -1 on failure.
2907 evutil_make_internal_pipe_(evutil_socket_t fd[2])
2910 Making the second socket nonblocking is a bit subtle, given that we
2911 ignore any EAGAIN returns when writing to it, and you don't usally
2912 do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2913 then there's no need to add any more data to the buffer, since
2914 the main thread is already either about to wake up and drain it,
2915 or woken up and in the process of draining it.
2918 #if defined(EVENT__HAVE_PIPE2)
2919 if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
2922 #if defined(EVENT__HAVE_PIPE)
2923 if (pipe(fd) == 0) {
2924 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2925 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2926 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2927 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2935 event_warn("%s: pipe", __func__);
2939 #if defined(_WIN32) && !defined(EVENT__HAVE_AFUNIX_H)
2940 #define LOCAL_SOCKETPAIR_AF AF_INET
2942 #define LOCAL_SOCKETPAIR_AF AF_UNIX
2944 if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
2945 if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2946 evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2947 evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2948 evutil_fast_socket_closeonexec(fd[1]) < 0) {
2949 evutil_closesocket(fd[0]);
2950 evutil_closesocket(fd[1]);
2960 /* Wrapper around eventfd on systems that provide it. Unlike the system
2961 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2962 * flags. Returns -1 on error or if eventfd is not supported.
2965 evutil_eventfd_(unsigned initval, int flags)
2967 #if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
2969 #if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
2970 r = eventfd(initval, flags);
2971 if (r >= 0 || flags == 0)
2974 r = eventfd(initval, 0);
2977 if (flags & EVUTIL_EFD_CLOEXEC) {
2978 if (evutil_fast_socket_closeonexec(r) < 0) {
2979 evutil_closesocket(r);
2983 if (flags & EVUTIL_EFD_NONBLOCK) {
2984 if (evutil_fast_socket_nonblocking(r) < 0) {
2985 evutil_closesocket(r);
2996 evutil_free_globals_(void)
2998 evutil_free_secure_rng_globals_();
2999 evutil_free_sock_err_globals();