evutil.c revision 290001
1/*
2 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
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.
14 *
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.
25 */
26
27#include "event2/event-config.h"
28#include "evconfig-private.h"
29
30#ifdef _WIN32
31#include <winsock2.h>
32#include <ws2tcpip.h>
33#define WIN32_LEAN_AND_MEAN
34#include <windows.h>
35#undef WIN32_LEAN_AND_MEAN
36#include <io.h>
37#include <tchar.h>
38#include <process.h>
39#undef _WIN32_WINNT
40/* For structs needed by GetAdaptersAddresses */
41#define _WIN32_WINNT 0x0501
42#include <iphlpapi.h>
43#endif
44
45#include <sys/types.h>
46#ifdef EVENT__HAVE_SYS_SOCKET_H
47#include <sys/socket.h>
48#endif
49#ifdef EVENT__HAVE_UNISTD_H
50#include <unistd.h>
51#endif
52#ifdef EVENT__HAVE_FCNTL_H
53#include <fcntl.h>
54#endif
55#ifdef EVENT__HAVE_STDLIB_H
56#include <stdlib.h>
57#endif
58#include <errno.h>
59#include <limits.h>
60#include <stdio.h>
61#include <string.h>
62#ifdef EVENT__HAVE_NETINET_IN_H
63#include <netinet/in.h>
64#endif
65#ifdef EVENT__HAVE_NETINET_IN6_H
66#include <netinet/in6.h>
67#endif
68#ifdef EVENT__HAVE_NETINET_TCP_H
69#include <netinet/tcp.h>
70#endif
71#ifdef EVENT__HAVE_ARPA_INET_H
72#include <arpa/inet.h>
73#endif
74#include <time.h>
75#include <sys/stat.h>
76#ifdef EVENT__HAVE_IFADDRS_H
77#include <ifaddrs.h>
78#endif
79
80#include "event2/util.h"
81#include "util-internal.h"
82#include "log-internal.h"
83#include "mm-internal.h"
84#include "evthread-internal.h"
85
86#include "strlcpy-internal.h"
87#include "ipv6-internal.h"
88
89#ifdef _WIN32
90#define HT_NO_CACHE_HASH_VALUES
91#include "ht-internal.h"
92#define open _open
93#define read _read
94#define close _close
95#ifndef fstat
96#define fstat _fstati64
97#endif
98#ifndef stat
99#define stat _stati64
100#endif
101#define mode_t int
102#endif
103
104int
105evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
106{
107	int fd;
108
109#ifdef O_CLOEXEC
110	fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
111	if (fd >= 0 || errno == EINVAL)
112		return fd;
113	/* If we got an EINVAL, fall through and try without O_CLOEXEC */
114#endif
115	fd = open(pathname, flags, (mode_t)mode);
116	if (fd < 0)
117		return -1;
118
119#if defined(FD_CLOEXEC)
120	if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
121		close(fd);
122		return -1;
123	}
124#endif
125
126	return fd;
127}
128
129/**
130   Read the contents of 'filename' into a newly allocated NUL-terminated
131   string.  Set *content_out to hold this string, and *len_out to hold its
132   length (not including the appended NUL).  If 'is_binary', open the file in
133   binary mode.
134
135   Returns 0 on success, -1 if the open fails, and -2 for all other failures.
136
137   Used internally only; may go away in a future version.
138 */
139int
140evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
141    int is_binary)
142{
143	int fd, r;
144	struct stat st;
145	char *mem;
146	size_t read_so_far=0;
147	int mode = O_RDONLY;
148
149	EVUTIL_ASSERT(content_out);
150	EVUTIL_ASSERT(len_out);
151	*content_out = NULL;
152	*len_out = 0;
153
154#ifdef O_BINARY
155	if (is_binary)
156		mode |= O_BINARY;
157#endif
158
159	fd = evutil_open_closeonexec_(filename, mode, 0);
160	if (fd < 0)
161		return -1;
162	if (fstat(fd, &st) || st.st_size < 0 ||
163	    st.st_size > EV_SSIZE_MAX-1 ) {
164		close(fd);
165		return -2;
166	}
167	mem = mm_malloc((size_t)st.st_size + 1);
168	if (!mem) {
169		close(fd);
170		return -2;
171	}
172	read_so_far = 0;
173#ifdef _WIN32
174#define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
175#else
176#define N_TO_READ(x) (x)
177#endif
178	while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
179		read_so_far += r;
180		if (read_so_far >= (size_t)st.st_size)
181			break;
182		EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
183	}
184	close(fd);
185	if (r < 0) {
186		mm_free(mem);
187		return -2;
188	}
189	mem[read_so_far] = 0;
190
191	*len_out = read_so_far;
192	*content_out = mem;
193	return 0;
194}
195
196int
197evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
198{
199#ifndef _WIN32
200	return socketpair(family, type, protocol, fd);
201#else
202	return evutil_ersatz_socketpair_(family, type, protocol, fd);
203#endif
204}
205
206int
207evutil_ersatz_socketpair_(int family, int type, int protocol,
208    evutil_socket_t fd[2])
209{
210	/* This code is originally from Tor.  Used with permission. */
211
212	/* This socketpair does not work when localhost is down. So
213	 * it's really not the same thing at all. But it's close enough
214	 * for now, and really, when localhost is down sometimes, we
215	 * have other problems too.
216	 */
217#ifdef _WIN32
218#define ERR(e) WSA##e
219#else
220#define ERR(e) e
221#endif
222	evutil_socket_t listener = -1;
223	evutil_socket_t connector = -1;
224	evutil_socket_t acceptor = -1;
225	struct sockaddr_in listen_addr;
226	struct sockaddr_in connect_addr;
227	ev_socklen_t size;
228	int saved_errno = -1;
229
230	if (protocol
231		|| (family != AF_INET
232#ifdef AF_UNIX
233		    && family != AF_UNIX
234#endif
235		)) {
236		EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
237		return -1;
238	}
239	if (!fd) {
240		EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
241		return -1;
242	}
243
244	listener = socket(AF_INET, type, 0);
245	if (listener < 0)
246		return -1;
247	memset(&listen_addr, 0, sizeof(listen_addr));
248	listen_addr.sin_family = AF_INET;
249	listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
250	listen_addr.sin_port = 0;	/* kernel chooses port.	 */
251	if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
252		== -1)
253		goto tidy_up_and_fail;
254	if (listen(listener, 1) == -1)
255		goto tidy_up_and_fail;
256
257	connector = socket(AF_INET, type, 0);
258	if (connector < 0)
259		goto tidy_up_and_fail;
260	/* We want to find out the port number to connect to.  */
261	size = sizeof(connect_addr);
262	if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
263		goto tidy_up_and_fail;
264	if (size != sizeof (connect_addr))
265		goto abort_tidy_up_and_fail;
266	if (connect(connector, (struct sockaddr *) &connect_addr,
267				sizeof(connect_addr)) == -1)
268		goto tidy_up_and_fail;
269
270	size = sizeof(listen_addr);
271	acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
272	if (acceptor < 0)
273		goto tidy_up_and_fail;
274	if (size != sizeof(listen_addr))
275		goto abort_tidy_up_and_fail;
276	/* Now check we are talking to ourself by matching port and host on the
277	   two sockets.	 */
278	if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
279		goto tidy_up_and_fail;
280	if (size != sizeof (connect_addr)
281		|| listen_addr.sin_family != connect_addr.sin_family
282		|| listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
283		|| listen_addr.sin_port != connect_addr.sin_port)
284		goto abort_tidy_up_and_fail;
285	evutil_closesocket(listener);
286	fd[0] = connector;
287	fd[1] = acceptor;
288
289	return 0;
290
291 abort_tidy_up_and_fail:
292	saved_errno = ERR(ECONNABORTED);
293 tidy_up_and_fail:
294	if (saved_errno < 0)
295		saved_errno = EVUTIL_SOCKET_ERROR();
296	if (listener != -1)
297		evutil_closesocket(listener);
298	if (connector != -1)
299		evutil_closesocket(connector);
300	if (acceptor != -1)
301		evutil_closesocket(acceptor);
302
303	EVUTIL_SET_SOCKET_ERROR(saved_errno);
304	return -1;
305#undef ERR
306}
307
308int
309evutil_make_socket_nonblocking(evutil_socket_t fd)
310{
311#ifdef _WIN32
312	{
313		u_long nonblocking = 1;
314		if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
315			event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
316			return -1;
317		}
318	}
319#else
320	{
321		int flags;
322		if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
323			event_warn("fcntl(%d, F_GETFL)", fd);
324			return -1;
325		}
326		if (!(flags & O_NONBLOCK)) {
327			if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
328				event_warn("fcntl(%d, F_SETFL)", fd);
329				return -1;
330			}
331		}
332	}
333#endif
334	return 0;
335}
336
337/* Faster version of evutil_make_socket_nonblocking for internal use.
338 *
339 * Requires that no F_SETFL flags were previously set on the fd.
340 */
341static int
342evutil_fast_socket_nonblocking(evutil_socket_t fd)
343{
344#ifdef _WIN32
345	return evutil_make_socket_nonblocking(fd);
346#else
347	if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
348		event_warn("fcntl(%d, F_SETFL)", fd);
349		return -1;
350	}
351	return 0;
352#endif
353}
354
355int
356evutil_make_listen_socket_reuseable(evutil_socket_t sock)
357{
358#ifndef _WIN32
359	int one = 1;
360	/* REUSEADDR on Unix means, "don't hang on to this address after the
361	 * listener is closed."  On Windows, though, it means "don't keep other
362	 * processes from binding to this address while we're using it. */
363	return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
364	    (ev_socklen_t)sizeof(one));
365#else
366	return 0;
367#endif
368}
369
370int
371evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
372{
373#if defined __linux__ && defined(SO_REUSEPORT)
374	int one = 1;
375	/* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
376	 * threads) can bind to the same port if they each set the option. */
377	return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
378	    (ev_socklen_t)sizeof(one));
379#else
380	return 0;
381#endif
382}
383
384int
385evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
386{
387#if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
388	int one = 1;
389
390	/* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
391	 * has arrived and ready to read */
392	return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
393		(ev_socklen_t)sizeof(one));
394#endif
395	return 0;
396}
397
398int
399evutil_make_socket_closeonexec(evutil_socket_t fd)
400{
401#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
402	int flags;
403	if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
404		event_warn("fcntl(%d, F_GETFD)", fd);
405		return -1;
406	}
407	if (!(flags & FD_CLOEXEC)) {
408		if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
409			event_warn("fcntl(%d, F_SETFD)", fd);
410			return -1;
411		}
412	}
413#endif
414	return 0;
415}
416
417/* Faster version of evutil_make_socket_closeonexec for internal use.
418 *
419 * Requires that no F_SETFD flags were previously set on the fd.
420 */
421static int
422evutil_fast_socket_closeonexec(evutil_socket_t fd)
423{
424#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
425	if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
426		event_warn("fcntl(%d, F_SETFD)", fd);
427		return -1;
428	}
429#endif
430	return 0;
431}
432
433int
434evutil_closesocket(evutil_socket_t sock)
435{
436#ifndef _WIN32
437	return close(sock);
438#else
439	return closesocket(sock);
440#endif
441}
442
443ev_int64_t
444evutil_strtoll(const char *s, char **endptr, int base)
445{
446#ifdef EVENT__HAVE_STRTOLL
447	return (ev_int64_t)strtoll(s, endptr, base);
448#elif EVENT__SIZEOF_LONG == 8
449	return (ev_int64_t)strtol(s, endptr, base);
450#elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
451	/* XXXX on old versions of MS APIs, we only support base
452	 * 10. */
453	ev_int64_t r;
454	if (base != 10)
455		return 0;
456	r = (ev_int64_t) _atoi64(s);
457	while (isspace(*s))
458		++s;
459	if (*s == '-')
460		++s;
461	while (isdigit(*s))
462		++s;
463	if (endptr)
464		*endptr = (char*) s;
465	return r;
466#elif defined(_WIN32)
467	return (ev_int64_t) _strtoi64(s, endptr, base);
468#elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
469	long long r;
470	int n;
471	if (base != 10 && base != 16)
472		return 0;
473	if (base == 10) {
474		n = sscanf(s, "%lld", &r);
475	} else {
476		unsigned long long ru=0;
477		n = sscanf(s, "%llx", &ru);
478		if (ru > EV_INT64_MAX)
479			return 0;
480		r = (long long) ru;
481	}
482	if (n != 1)
483		return 0;
484	while (EVUTIL_ISSPACE_(*s))
485		++s;
486	if (*s == '-')
487		++s;
488	if (base == 10) {
489		while (EVUTIL_ISDIGIT_(*s))
490			++s;
491	} else {
492		while (EVUTIL_ISXDIGIT_(*s))
493			++s;
494	}
495	if (endptr)
496		*endptr = (char*) s;
497	return r;
498#else
499#error "I don't know how to parse 64-bit integers."
500#endif
501}
502
503#ifdef _WIN32
504int
505evutil_socket_geterror(evutil_socket_t sock)
506{
507	int optval, optvallen=sizeof(optval);
508	int err = WSAGetLastError();
509	if (err == WSAEWOULDBLOCK && sock >= 0) {
510		if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
511					   &optvallen))
512			return err;
513		if (optval)
514			return optval;
515	}
516	return err;
517}
518#endif
519
520/* XXX we should use an enum here. */
521/* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
522int
523evutil_socket_connect_(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
524{
525	int made_fd = 0;
526
527	if (*fd_ptr < 0) {
528		if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
529			goto err;
530		made_fd = 1;
531		if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
532			goto err;
533		}
534	}
535
536	if (connect(*fd_ptr, sa, socklen) < 0) {
537		int e = evutil_socket_geterror(*fd_ptr);
538		if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
539			return 0;
540		if (EVUTIL_ERR_CONNECT_REFUSED(e))
541			return 2;
542		goto err;
543	} else {
544		return 1;
545	}
546
547err:
548	if (made_fd) {
549		evutil_closesocket(*fd_ptr);
550		*fd_ptr = -1;
551	}
552	return -1;
553}
554
555/* Check whether a socket on which we called connect() is done
556   connecting. Return 1 for connected, 0 for not yet, -1 for error.  In the
557   error case, set the current socket errno to the error that happened during
558   the connect operation. */
559int
560evutil_socket_finished_connecting_(evutil_socket_t fd)
561{
562	int e;
563	ev_socklen_t elen = sizeof(e);
564
565	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
566		return -1;
567
568	if (e) {
569		if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
570			return 0;
571		EVUTIL_SET_SOCKET_ERROR(e);
572		return -1;
573	}
574
575	return 1;
576}
577
578#if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
579     EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
580     EVUTIL_AI_ADDRCONFIG) != \
581    (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
582     EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
583     EVUTIL_AI_ADDRCONFIG)
584#error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
585#endif
586
587/* We sometimes need to know whether we have an ipv4 address and whether we
588   have an ipv6 address. If 'have_checked_interfaces', then we've already done
589   the test.  If 'had_ipv4_address', then it turns out we had an ipv4 address.
590   If 'had_ipv6_address', then it turns out we had an ipv6 address.   These are
591   set by evutil_check_interfaces. */
592static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
593
594/* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
595 */
596#define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
597
598/* Macro: True iff the IPv4 address 'addr', in host order, is a class D
599 * (multiclass) address.
600 */
601#define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
602
603static void
604evutil_found_ifaddr(const struct sockaddr *sa)
605{
606	const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
607	    "\x00\x00\x00\x00\x00\x00\x00\x00";
608
609	if (sa->sa_family == AF_INET) {
610		const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
611		ev_uint32_t addr = ntohl(sin->sin_addr.s_addr);
612		if (addr == 0 ||
613		    EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
614		    EVUTIL_V4ADDR_IS_CLASSD(addr)) {
615			/* Not actually a usable external address. */
616		} else {
617			event_debug(("Detected an IPv4 interface"));
618			had_ipv4_address = 1;
619		}
620	} else if (sa->sa_family == AF_INET6) {
621		const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
622		const unsigned char *addr =
623		    (unsigned char*)sin6->sin6_addr.s6_addr;
624		if (!memcmp(addr, ZEROES, 8) ||
625		    ((addr[0] & 0xfe) == 0xfc) ||
626		    (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
627		    (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
628		    (addr[0] == 0xff)) {
629			/* This is a reserved, ipv4compat, ipv4map, loopback,
630			 * link-local, multicast, or unspecified address. */
631		} else {
632			event_debug(("Detected an IPv6 interface"));
633			had_ipv6_address = 1;
634		}
635	}
636}
637
638#ifdef _WIN32
639typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
640              ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
641#endif
642
643static int
644evutil_check_ifaddrs(void)
645{
646#if defined(EVENT__HAVE_GETIFADDRS)
647	/* Most free Unixy systems provide getifaddrs, which gives us a linked list
648	 * of struct ifaddrs. */
649	struct ifaddrs *ifa = NULL;
650	const struct ifaddrs *i;
651	if (getifaddrs(&ifa) < 0) {
652		event_warn("Unable to call getifaddrs()");
653		return -1;
654	}
655
656	for (i = ifa; i; i = i->ifa_next) {
657		if (!i->ifa_addr)
658			continue;
659		evutil_found_ifaddr(i->ifa_addr);
660	}
661
662	freeifaddrs(ifa);
663	return 0;
664#elif defined(_WIN32)
665	/* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
666	   "GetAdaptersInfo", but that's deprecated; let's just try
667	   GetAdaptersAddresses and fall back to connect+getsockname.
668	*/
669	HMODULE lib = evutil_load_windows_system_library_(TEXT("ihplapi.dll"));
670	GetAdaptersAddresses_fn_t fn;
671	ULONG size, res;
672	IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
673	int result = -1;
674
675#define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
676               GAA_FLAG_SKIP_MULTICAST | \
677               GAA_FLAG_SKIP_DNS_SERVER)
678
679	if (!lib)
680		goto done;
681
682	if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
683		goto done;
684
685	/* Guess how much space we need. */
686	size = 15*1024;
687	addresses = mm_malloc(size);
688	if (!addresses)
689		goto done;
690	res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
691	if (res == ERROR_BUFFER_OVERFLOW) {
692		/* we didn't guess that we needed enough space; try again */
693		mm_free(addresses);
694		addresses = mm_malloc(size);
695		if (!addresses)
696			goto done;
697		res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
698	}
699	if (res != NO_ERROR)
700		goto done;
701
702	for (address = addresses; address; address = address->Next) {
703		IP_ADAPTER_UNICAST_ADDRESS *a;
704		for (a = address->FirstUnicastAddress; a; a = a->Next) {
705			/* Yes, it's a linked list inside a linked list */
706			struct sockaddr *sa = a->Address.lpSockaddr;
707			evutil_found_ifaddr(sa);
708		}
709	}
710
711	result = 0;
712done:
713	if (lib)
714		FreeLibrary(lib);
715	if (addresses)
716		mm_free(addresses);
717	return result;
718#else
719	return -1;
720#endif
721}
722
723/* Test whether we have an ipv4 interface and an ipv6 interface.  Return 0 if
724 * the test seemed successful. */
725static int
726evutil_check_interfaces(int force_recheck)
727{
728	evutil_socket_t fd = -1;
729	struct sockaddr_in sin, sin_out;
730	struct sockaddr_in6 sin6, sin6_out;
731	ev_socklen_t sin_out_len = sizeof(sin_out);
732	ev_socklen_t sin6_out_len = sizeof(sin6_out);
733	int r;
734	if (have_checked_interfaces && !force_recheck)
735		return 0;
736
737	if (evutil_check_ifaddrs() == 0) {
738		/* Use a nice sane interface, if this system has one. */
739		return 0;
740	}
741
742	/* Ugh. There was no nice sane interface.  So to check whether we have
743	 * an interface open for a given protocol, will try to make a UDP
744	 * 'connection' to a remote host on the internet.  We don't actually
745	 * use it, so the address doesn't matter, but we want to pick one that
746	 * keep us from using a host- or link-local interface. */
747	memset(&sin, 0, sizeof(sin));
748	sin.sin_family = AF_INET;
749	sin.sin_port = htons(53);
750	r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
751	EVUTIL_ASSERT(r);
752
753	memset(&sin6, 0, sizeof(sin6));
754	sin6.sin6_family = AF_INET6;
755	sin6.sin6_port = htons(53);
756	r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
757	EVUTIL_ASSERT(r);
758
759	memset(&sin_out, 0, sizeof(sin_out));
760	memset(&sin6_out, 0, sizeof(sin6_out));
761
762	/* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
763	if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
764	    connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
765	    getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
766		/* We might have an IPv4 interface. */
767		evutil_found_ifaddr((struct sockaddr*) &sin_out);
768	}
769	if (fd >= 0)
770		evutil_closesocket(fd);
771
772	if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
773	    connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
774	    getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
775		/* We might have an IPv6 interface. */
776		evutil_found_ifaddr((struct sockaddr*) &sin6_out);
777	}
778
779	if (fd >= 0)
780		evutil_closesocket(fd);
781
782	return 0;
783}
784
785/* Internal addrinfo flag.  This one is set when we allocate the addrinfo from
786 * inside libevent.  Otherwise, the built-in getaddrinfo() function allocated
787 * it, and we should trust what they said.
788 **/
789#define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
790
791/* Helper: construct a new addrinfo containing the socket address in
792 * 'sa', which must be a sockaddr_in or a sockaddr_in6.  Take the
793 * socktype and protocol info from hints.  If they weren't set, then
794 * allocate both a TCP and a UDP addrinfo.
795 */
796struct evutil_addrinfo *
797evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
798    const struct evutil_addrinfo *hints)
799{
800	struct evutil_addrinfo *res;
801	EVUTIL_ASSERT(hints);
802
803	if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
804		/* Indecisive user! Give them a UDP and a TCP. */
805		struct evutil_addrinfo *r1, *r2;
806		struct evutil_addrinfo tmp;
807		memcpy(&tmp, hints, sizeof(tmp));
808		tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
809		r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
810		if (!r1)
811			return NULL;
812		tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
813		r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
814		if (!r2) {
815			evutil_freeaddrinfo(r1);
816			return NULL;
817		}
818		r1->ai_next = r2;
819		return r1;
820	}
821
822	/* We're going to allocate extra space to hold the sockaddr. */
823	res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
824	if (!res)
825		return NULL;
826	res->ai_addr = (struct sockaddr*)
827	    (((char*)res) + sizeof(struct evutil_addrinfo));
828	memcpy(res->ai_addr, sa, socklen);
829	res->ai_addrlen = socklen;
830	res->ai_family = sa->sa_family; /* Same or not? XXX */
831	res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
832	res->ai_socktype = hints->ai_socktype;
833	res->ai_protocol = hints->ai_protocol;
834
835	return res;
836}
837
838/* Append the addrinfo 'append' to the end of 'first', and return the start of
839 * the list.  Either element can be NULL, in which case we return the element
840 * that is not NULL. */
841struct evutil_addrinfo *
842evutil_addrinfo_append_(struct evutil_addrinfo *first,
843    struct evutil_addrinfo *append)
844{
845	struct evutil_addrinfo *ai = first;
846	if (!ai)
847		return append;
848	while (ai->ai_next)
849		ai = ai->ai_next;
850	ai->ai_next = append;
851
852	return first;
853}
854
855static int
856parse_numeric_servname(const char *servname)
857{
858	int n;
859	char *endptr=NULL;
860	n = (int) strtol(servname, &endptr, 10);
861	if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
862		return n;
863	else
864		return -1;
865}
866
867/** Parse a service name in 'servname', which can be a decimal port.
868 * Return the port number, or -1 on error.
869 */
870static int
871evutil_parse_servname(const char *servname, const char *protocol,
872    const struct evutil_addrinfo *hints)
873{
874	int n = parse_numeric_servname(servname);
875	if (n>=0)
876		return n;
877#if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
878	if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
879		struct servent *ent = getservbyname(servname, protocol);
880		if (ent) {
881			return ntohs(ent->s_port);
882		}
883	}
884#endif
885	return -1;
886}
887
888/* Return a string corresponding to a protocol number that we can pass to
889 * getservyname.  */
890static const char *
891evutil_unparse_protoname(int proto)
892{
893	switch (proto) {
894	case 0:
895		return NULL;
896	case IPPROTO_TCP:
897		return "tcp";
898	case IPPROTO_UDP:
899		return "udp";
900#ifdef IPPROTO_SCTP
901	case IPPROTO_SCTP:
902		return "sctp";
903#endif
904	default:
905#ifdef EVENT__HAVE_GETPROTOBYNUMBER
906		{
907			struct protoent *ent = getprotobynumber(proto);
908			if (ent)
909				return ent->p_name;
910		}
911#endif
912		return NULL;
913	}
914}
915
916static void
917evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
918{
919	/* If we can guess the protocol from the socktype, do so. */
920	if (!hints->ai_protocol && hints->ai_socktype) {
921		if (hints->ai_socktype == SOCK_DGRAM)
922			hints->ai_protocol = IPPROTO_UDP;
923		else if (hints->ai_socktype == SOCK_STREAM)
924			hints->ai_protocol = IPPROTO_TCP;
925	}
926
927	/* Set the socktype if it isn't set. */
928	if (!hints->ai_socktype && hints->ai_protocol) {
929		if (hints->ai_protocol == IPPROTO_UDP)
930			hints->ai_socktype = SOCK_DGRAM;
931		else if (hints->ai_protocol == IPPROTO_TCP)
932			hints->ai_socktype = SOCK_STREAM;
933#ifdef IPPROTO_SCTP
934		else if (hints->ai_protocol == IPPROTO_SCTP)
935			hints->ai_socktype = SOCK_STREAM;
936#endif
937	}
938}
939
940#if AF_UNSPEC != PF_UNSPEC
941#error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
942#endif
943
944/** Implements the part of looking up hosts by name that's common to both
945 * the blocking and nonblocking resolver:
946 *   - Adjust 'hints' to have a reasonable socktype and protocol.
947 *   - Look up the port based on 'servname', and store it in *portnum,
948 *   - Handle the nodename==NULL case
949 *   - Handle some invalid arguments cases.
950 *   - Handle the cases where nodename is an IPv4 or IPv6 address.
951 *
952 * If we need the resolver to look up the hostname, we return
953 * EVUTIL_EAI_NEED_RESOLVE.  Otherwise, we can completely implement
954 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
955 * set *res as getaddrinfo would.
956 */
957int
958evutil_getaddrinfo_common_(const char *nodename, const char *servname,
959    struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
960{
961	int port = 0;
962	const char *pname;
963
964	if (nodename == NULL && servname == NULL)
965		return EVUTIL_EAI_NONAME;
966
967	/* We only understand 3 families */
968	if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
969	    hints->ai_family != PF_INET6)
970		return EVUTIL_EAI_FAMILY;
971
972	evutil_getaddrinfo_infer_protocols(hints);
973
974	/* Look up the port number and protocol, if possible. */
975	pname = evutil_unparse_protoname(hints->ai_protocol);
976	if (servname) {
977		/* XXXX We could look at the protocol we got back from
978		 * getservbyname, but it doesn't seem too useful. */
979		port = evutil_parse_servname(servname, pname, hints);
980		if (port < 0) {
981			return EVUTIL_EAI_NONAME;
982		}
983	}
984
985	/* If we have no node name, then we're supposed to bind to 'any' and
986	 * connect to localhost. */
987	if (nodename == NULL) {
988		struct evutil_addrinfo *res4=NULL, *res6=NULL;
989		if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
990			struct sockaddr_in6 sin6;
991			memset(&sin6, 0, sizeof(sin6));
992			sin6.sin6_family = AF_INET6;
993			sin6.sin6_port = htons(port);
994			if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
995				/* Bind to :: */
996			} else {
997				/* connect to ::1 */
998				sin6.sin6_addr.s6_addr[15] = 1;
999			}
1000			res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1001			    sizeof(sin6), hints);
1002			if (!res6)
1003				return EVUTIL_EAI_MEMORY;
1004		}
1005
1006		if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
1007			struct sockaddr_in sin;
1008			memset(&sin, 0, sizeof(sin));
1009			sin.sin_family = AF_INET;
1010			sin.sin_port = htons(port);
1011			if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
1012				/* Bind to 0.0.0.0 */
1013			} else {
1014				/* connect to 127.0.0.1 */
1015				sin.sin_addr.s_addr = htonl(0x7f000001);
1016			}
1017			res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
1018			    sizeof(sin), hints);
1019			if (!res4) {
1020				if (res6)
1021					evutil_freeaddrinfo(res6);
1022				return EVUTIL_EAI_MEMORY;
1023			}
1024		}
1025		*res = evutil_addrinfo_append_(res4, res6);
1026		return 0;
1027	}
1028
1029	/* If we can, we should try to parse the hostname without resolving
1030	 * it. */
1031	/* Try ipv6. */
1032	if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
1033		struct sockaddr_in6 sin6;
1034		memset(&sin6, 0, sizeof(sin6));
1035		if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
1036			/* Got an ipv6 address. */
1037			sin6.sin6_family = AF_INET6;
1038			sin6.sin6_port = htons(port);
1039			*res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
1040			    sizeof(sin6), hints);
1041			if (!*res)
1042				return EVUTIL_EAI_MEMORY;
1043			return 0;
1044		}
1045	}
1046
1047	/* Try ipv4. */
1048	if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
1049		struct sockaddr_in sin;
1050		memset(&sin, 0, sizeof(sin));
1051		if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
1052			/* Got an ipv6 address. */
1053			sin.sin_family = AF_INET;
1054			sin.sin_port = htons(port);
1055			*res = evutil_new_addrinfo_((struct sockaddr*)&sin,
1056			    sizeof(sin), hints);
1057			if (!*res)
1058				return EVUTIL_EAI_MEMORY;
1059			return 0;
1060		}
1061	}
1062
1063
1064	/* If we have reached this point, we definitely need to do a DNS
1065	 * lookup. */
1066	if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
1067		/* If we're not allowed to do one, then say so. */
1068		return EVUTIL_EAI_NONAME;
1069	}
1070	*portnum = port;
1071	return EVUTIL_EAI_NEED_RESOLVE;
1072}
1073
1074#ifdef EVENT__HAVE_GETADDRINFO
1075#define USE_NATIVE_GETADDRINFO
1076#endif
1077
1078#ifdef USE_NATIVE_GETADDRINFO
1079/* A mask of all the flags that we declare, so we can clear them before calling
1080 * the native getaddrinfo */
1081static const unsigned int ALL_NONNATIVE_AI_FLAGS =
1082#ifndef AI_PASSIVE
1083    EVUTIL_AI_PASSIVE |
1084#endif
1085#ifndef AI_CANONNAME
1086    EVUTIL_AI_CANONNAME |
1087#endif
1088#ifndef AI_NUMERICHOST
1089    EVUTIL_AI_NUMERICHOST |
1090#endif
1091#ifndef AI_NUMERICSERV
1092    EVUTIL_AI_NUMERICSERV |
1093#endif
1094#ifndef AI_ADDRCONFIG
1095    EVUTIL_AI_ADDRCONFIG |
1096#endif
1097#ifndef AI_ALL
1098    EVUTIL_AI_ALL |
1099#endif
1100#ifndef AI_V4MAPPED
1101    EVUTIL_AI_V4MAPPED |
1102#endif
1103    EVUTIL_AI_LIBEVENT_ALLOCATED;
1104
1105static const unsigned int ALL_NATIVE_AI_FLAGS =
1106#ifdef AI_PASSIVE
1107    AI_PASSIVE |
1108#endif
1109#ifdef AI_CANONNAME
1110    AI_CANONNAME |
1111#endif
1112#ifdef AI_NUMERICHOST
1113    AI_NUMERICHOST |
1114#endif
1115#ifdef AI_NUMERICSERV
1116    AI_NUMERICSERV |
1117#endif
1118#ifdef AI_ADDRCONFIG
1119    AI_ADDRCONFIG |
1120#endif
1121#ifdef AI_ALL
1122    AI_ALL |
1123#endif
1124#ifdef AI_V4MAPPED
1125    AI_V4MAPPED |
1126#endif
1127    0;
1128#endif
1129
1130#ifndef USE_NATIVE_GETADDRINFO
1131/* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
1132 * a struct hostent.
1133 */
1134static struct evutil_addrinfo *
1135addrinfo_from_hostent(const struct hostent *ent,
1136    int port, const struct evutil_addrinfo *hints)
1137{
1138	int i;
1139	struct sockaddr_in sin;
1140	struct sockaddr_in6 sin6;
1141	struct sockaddr *sa;
1142	int socklen;
1143	struct evutil_addrinfo *res=NULL, *ai;
1144	void *addrp;
1145
1146	if (ent->h_addrtype == PF_INET) {
1147		memset(&sin, 0, sizeof(sin));
1148		sin.sin_family = AF_INET;
1149		sin.sin_port = htons(port);
1150		sa = (struct sockaddr *)&sin;
1151		socklen = sizeof(struct sockaddr_in);
1152		addrp = &sin.sin_addr;
1153		if (ent->h_length != sizeof(sin.sin_addr)) {
1154			event_warnx("Weird h_length from gethostbyname");
1155			return NULL;
1156		}
1157	} else if (ent->h_addrtype == PF_INET6) {
1158		memset(&sin6, 0, sizeof(sin6));
1159		sin6.sin6_family = AF_INET6;
1160		sin6.sin6_port = htons(port);
1161		sa = (struct sockaddr *)&sin6;
1162		socklen = sizeof(struct sockaddr_in);
1163		addrp = &sin6.sin6_addr;
1164		if (ent->h_length != sizeof(sin6.sin6_addr)) {
1165			event_warnx("Weird h_length from gethostbyname");
1166			return NULL;
1167		}
1168	} else
1169		return NULL;
1170
1171	for (i = 0; ent->h_addr_list[i]; ++i) {
1172		memcpy(addrp, ent->h_addr_list[i], ent->h_length);
1173		ai = evutil_new_addrinfo_(sa, socklen, hints);
1174		if (!ai) {
1175			evutil_freeaddrinfo(res);
1176			return NULL;
1177		}
1178		res = evutil_addrinfo_append_(res, ai);
1179	}
1180
1181	if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1182		res->ai_canonname = mm_strdup(ent->h_name);
1183		if (res->ai_canonname == NULL) {
1184			evutil_freeaddrinfo(res);
1185			return NULL;
1186		}
1187	}
1188
1189	return res;
1190}
1191#endif
1192
1193/* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1194 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1195 * that we'll only get addresses we could maybe connect to.
1196 */
1197void
1198evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
1199{
1200	if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1201		return;
1202	if (hints->ai_family != PF_UNSPEC)
1203		return;
1204	if (!have_checked_interfaces)
1205		evutil_check_interfaces(0);
1206	if (had_ipv4_address && !had_ipv6_address) {
1207		hints->ai_family = PF_INET;
1208	} else if (!had_ipv4_address && had_ipv6_address) {
1209		hints->ai_family = PF_INET6;
1210	}
1211}
1212
1213#ifdef USE_NATIVE_GETADDRINFO
1214static int need_numeric_port_hack_=0;
1215static int need_socktype_protocol_hack_=0;
1216static int tested_for_getaddrinfo_hacks=0;
1217
1218/* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1219   giving a numeric port without giving an ai_socktype was verboten.
1220   We test for this so we can apply an appropriate workaround.  If it
1221   turns out that the bug is present, then:
1222
1223    - If nodename==NULL and servname is numeric, we build an answer
1224      ourselves using evutil_getaddrinfo_common_().
1225
1226    - If nodename!=NULL and servname is numeric, then we set
1227      servname=NULL when calling getaddrinfo, and post-process the
1228      result to set the ports on it.
1229
1230   We test for this bug at runtime, since otherwise we can't have the
1231   same binary run on multiple BSD versions.
1232
1233   - Some versions of Solaris believe that it's nice to leave to protocol
1234     field set to 0.  We test for this so we can apply an appropriate
1235     workaround.
1236*/
1237static void
1238test_for_getaddrinfo_hacks(void)
1239{
1240	int r, r2;
1241	struct evutil_addrinfo *ai=NULL, *ai2=NULL;
1242	struct evutil_addrinfo hints;
1243
1244	memset(&hints,0,sizeof(hints));
1245	hints.ai_family = PF_UNSPEC;
1246	hints.ai_flags =
1247#ifdef AI_NUMERICHOST
1248	    AI_NUMERICHOST |
1249#endif
1250#ifdef AI_NUMERICSERV
1251	    AI_NUMERICSERV |
1252#endif
1253	    0;
1254	r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1255	hints.ai_socktype = SOCK_STREAM;
1256	r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1257	if (r2 == 0 && r != 0) {
1258		need_numeric_port_hack_=1;
1259	}
1260	if (ai2 && ai2->ai_protocol == 0) {
1261		need_socktype_protocol_hack_=1;
1262	}
1263
1264	if (ai)
1265		freeaddrinfo(ai);
1266	if (ai2)
1267		freeaddrinfo(ai2);
1268	tested_for_getaddrinfo_hacks=1;
1269}
1270
1271static inline int
1272need_numeric_port_hack(void)
1273{
1274	if (!tested_for_getaddrinfo_hacks)
1275		test_for_getaddrinfo_hacks();
1276	return need_numeric_port_hack_;
1277}
1278
1279static inline int
1280need_socktype_protocol_hack(void)
1281{
1282	if (!tested_for_getaddrinfo_hacks)
1283		test_for_getaddrinfo_hacks();
1284	return need_socktype_protocol_hack_;
1285}
1286
1287static void
1288apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1289{
1290	/* Now we run through the list and set the ports on all of the
1291	 * results where ports would make sense. */
1292	for ( ; *ai; ai = &(*ai)->ai_next) {
1293		struct sockaddr *sa = (*ai)->ai_addr;
1294		if (sa && sa->sa_family == AF_INET) {
1295			struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1296			sin->sin_port = htons(port);
1297		} else if (sa && sa->sa_family == AF_INET6) {
1298			struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1299			sin6->sin6_port = htons(port);
1300		} else {
1301			/* A numeric port makes no sense here; remove this one
1302			 * from the list. */
1303			struct evutil_addrinfo *victim = *ai;
1304			*ai = victim->ai_next;
1305			victim->ai_next = NULL;
1306			freeaddrinfo(victim);
1307		}
1308	}
1309}
1310
1311static int
1312apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1313{
1314	struct evutil_addrinfo *ai_new;
1315	for (; ai; ai = ai->ai_next) {
1316		evutil_getaddrinfo_infer_protocols(ai);
1317		if (ai->ai_socktype || ai->ai_protocol)
1318			continue;
1319		ai_new = mm_malloc(sizeof(*ai_new));
1320		if (!ai_new)
1321			return -1;
1322		memcpy(ai_new, ai, sizeof(*ai_new));
1323		ai->ai_socktype = SOCK_STREAM;
1324		ai->ai_protocol = IPPROTO_TCP;
1325		ai_new->ai_socktype = SOCK_DGRAM;
1326		ai_new->ai_protocol = IPPROTO_UDP;
1327
1328		ai_new->ai_next = ai->ai_next;
1329		ai->ai_next = ai_new;
1330	}
1331	return 0;
1332}
1333#endif
1334
1335int
1336evutil_getaddrinfo(const char *nodename, const char *servname,
1337    const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1338{
1339#ifdef USE_NATIVE_GETADDRINFO
1340	struct evutil_addrinfo hints;
1341	int portnum=-1, need_np_hack, err;
1342
1343	if (hints_in) {
1344		memcpy(&hints, hints_in, sizeof(hints));
1345	} else {
1346		memset(&hints, 0, sizeof(hints));
1347		hints.ai_family = PF_UNSPEC;
1348	}
1349
1350#ifndef AI_ADDRCONFIG
1351	/* Not every system has AI_ADDRCONFIG, so fake it. */
1352	if (hints.ai_family == PF_UNSPEC &&
1353	    (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1354		evutil_adjust_hints_for_addrconfig_(&hints);
1355	}
1356#endif
1357
1358#ifndef AI_NUMERICSERV
1359	/* Not every system has AI_NUMERICSERV, so fake it. */
1360	if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1361		if (servname && parse_numeric_servname(servname)<0)
1362			return EVUTIL_EAI_NONAME;
1363	}
1364#endif
1365
1366	/* Enough operating systems handle enough common non-resolve
1367	 * cases here weirdly enough that we are better off just
1368	 * overriding them.  For example:
1369	 *
1370	 * - Windows doesn't like to infer the protocol from the
1371	 *   socket type, or fill in socket or protocol types much at
1372	 *   all.  It also seems to do its own broken implicit
1373	 *   always-on version of AI_ADDRCONFIG that keeps it from
1374	 *   ever resolving even a literal IPv6 address when
1375	 *   ai_addrtype is PF_UNSPEC.
1376	 */
1377#ifdef _WIN32
1378	{
1379		int tmp_port;
1380		err = evutil_getaddrinfo_common_(nodename,servname,&hints,
1381		    res, &tmp_port);
1382		if (err == 0 ||
1383		    err == EVUTIL_EAI_MEMORY ||
1384		    err == EVUTIL_EAI_NONAME)
1385			return err;
1386		/* If we make it here, the system getaddrinfo can
1387		 * have a crack at it. */
1388	}
1389#endif
1390
1391	/* See documentation for need_numeric_port_hack above.*/
1392	need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1393	    && ((portnum=parse_numeric_servname(servname)) >= 0);
1394	if (need_np_hack) {
1395		if (!nodename)
1396			return evutil_getaddrinfo_common_(
1397				NULL,servname,&hints, res, &portnum);
1398		servname = NULL;
1399	}
1400
1401	if (need_socktype_protocol_hack()) {
1402		evutil_getaddrinfo_infer_protocols(&hints);
1403	}
1404
1405	/* Make sure that we didn't actually steal any AI_FLAGS values that
1406	 * the system is using.  (This is a constant expression, and should ge
1407	 * optimized out.)
1408	 *
1409	 * XXXX Turn this into a compile-time failure rather than a run-time
1410	 * failure.
1411	 */
1412	EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1413
1414	/* Clear any flags that only libevent understands. */
1415	hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1416
1417	err = getaddrinfo(nodename, servname, &hints, res);
1418	if (need_np_hack)
1419		apply_numeric_port_hack(portnum, res);
1420
1421	if (need_socktype_protocol_hack()) {
1422		if (apply_socktype_protocol_hack(*res) < 0) {
1423			evutil_freeaddrinfo(*res);
1424			*res = NULL;
1425			return EVUTIL_EAI_MEMORY;
1426		}
1427	}
1428	return err;
1429#else
1430	int port=0, err;
1431	struct hostent *ent = NULL;
1432	struct evutil_addrinfo hints;
1433
1434	if (hints_in) {
1435		memcpy(&hints, hints_in, sizeof(hints));
1436	} else {
1437		memset(&hints, 0, sizeof(hints));
1438		hints.ai_family = PF_UNSPEC;
1439	}
1440
1441	evutil_adjust_hints_for_addrconfig_(&hints);
1442
1443	err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
1444	if (err != EVUTIL_EAI_NEED_RESOLVE) {
1445		/* We either succeeded or failed.  No need to continue */
1446		return err;
1447	}
1448
1449	err = 0;
1450	/* Use any of the various gethostbyname_r variants as available. */
1451	{
1452#ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
1453		/* This one is what glibc provides. */
1454		char buf[2048];
1455		struct hostent hostent;
1456		int r;
1457		r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1458		    &err);
1459#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
1460		char buf[2048];
1461		struct hostent hostent;
1462		ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1463		    &err);
1464#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
1465		struct hostent_data data;
1466		struct hostent hostent;
1467		memset(&data, 0, sizeof(data));
1468		err = gethostbyname_r(nodename, &hostent, &data);
1469		ent = err ? NULL : &hostent;
1470#else
1471		/* fall back to gethostbyname. */
1472		/* XXXX This needs a lock everywhere but Windows. */
1473		ent = gethostbyname(nodename);
1474#ifdef _WIN32
1475		err = WSAGetLastError();
1476#else
1477		err = h_errno;
1478#endif
1479#endif
1480
1481		/* Now we have either ent or err set. */
1482		if (!ent) {
1483			/* XXX is this right for windows ? */
1484			switch (err) {
1485			case TRY_AGAIN:
1486				return EVUTIL_EAI_AGAIN;
1487			case NO_RECOVERY:
1488			default:
1489				return EVUTIL_EAI_FAIL;
1490			case HOST_NOT_FOUND:
1491				return EVUTIL_EAI_NONAME;
1492			case NO_ADDRESS:
1493#if NO_DATA != NO_ADDRESS
1494			case NO_DATA:
1495#endif
1496				return EVUTIL_EAI_NODATA;
1497			}
1498		}
1499
1500		if (ent->h_addrtype != hints.ai_family &&
1501		    hints.ai_family != PF_UNSPEC) {
1502			/* This wasn't the type we were hoping for.  Too bad
1503			 * we never had a chance to ask gethostbyname for what
1504			 * we wanted. */
1505			return EVUTIL_EAI_NONAME;
1506		}
1507
1508		/* Make sure we got _some_ answers. */
1509		if (ent->h_length == 0)
1510			return EVUTIL_EAI_NODATA;
1511
1512		/* If we got an address type we don't know how to make a
1513		   sockaddr for, give up. */
1514		if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1515			return EVUTIL_EAI_FAMILY;
1516
1517		*res = addrinfo_from_hostent(ent, port, &hints);
1518		if (! *res)
1519			return EVUTIL_EAI_MEMORY;
1520	}
1521
1522	return 0;
1523#endif
1524}
1525
1526void
1527evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1528{
1529#ifdef EVENT__HAVE_GETADDRINFO
1530	if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
1531		freeaddrinfo(ai);
1532		return;
1533	}
1534#endif
1535	while (ai) {
1536		struct evutil_addrinfo *next = ai->ai_next;
1537		if (ai->ai_canonname)
1538			mm_free(ai->ai_canonname);
1539		mm_free(ai);
1540		ai = next;
1541	}
1542}
1543
1544static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1545
1546void
1547evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
1548{
1549	if (!evdns_getaddrinfo_impl)
1550		evdns_getaddrinfo_impl = fn;
1551}
1552
1553/* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1554 * otherwise do a blocking resolve and pass the result to the callback in the
1555 * way that evdns_getaddrinfo would.
1556 */
1557int
1558evutil_getaddrinfo_async_(struct evdns_base *dns_base,
1559    const char *nodename, const char *servname,
1560    const struct evutil_addrinfo *hints_in,
1561    void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1562{
1563	if (dns_base && evdns_getaddrinfo_impl) {
1564		evdns_getaddrinfo_impl(
1565			dns_base, nodename, servname, hints_in, cb, arg);
1566	} else {
1567		struct evutil_addrinfo *ai=NULL;
1568		int err;
1569		err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1570		cb(err, ai, arg);
1571	}
1572	return 0;
1573}
1574
1575const char *
1576evutil_gai_strerror(int err)
1577{
1578	/* As a sneaky side-benefit, this case statement will get most
1579	 * compilers to tell us if any of the error codes we defined
1580	 * conflict with the platform's native error codes. */
1581	switch (err) {
1582	case EVUTIL_EAI_CANCEL:
1583		return "Request canceled";
1584	case 0:
1585		return "No error";
1586
1587	case EVUTIL_EAI_ADDRFAMILY:
1588		return "address family for nodename not supported";
1589	case EVUTIL_EAI_AGAIN:
1590		return "temporary failure in name resolution";
1591	case EVUTIL_EAI_BADFLAGS:
1592		return "invalid value for ai_flags";
1593	case EVUTIL_EAI_FAIL:
1594		return "non-recoverable failure in name resolution";
1595	case EVUTIL_EAI_FAMILY:
1596		return "ai_family not supported";
1597	case EVUTIL_EAI_MEMORY:
1598		return "memory allocation failure";
1599	case EVUTIL_EAI_NODATA:
1600		return "no address associated with nodename";
1601	case EVUTIL_EAI_NONAME:
1602		return "nodename nor servname provided, or not known";
1603	case EVUTIL_EAI_SERVICE:
1604		return "servname not supported for ai_socktype";
1605	case EVUTIL_EAI_SOCKTYPE:
1606		return "ai_socktype not supported";
1607	case EVUTIL_EAI_SYSTEM:
1608		return "system error";
1609	default:
1610#if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
1611		return gai_strerrorA(err);
1612#elif defined(USE_NATIVE_GETADDRINFO)
1613		return gai_strerror(err);
1614#else
1615		return "Unknown error code";
1616#endif
1617	}
1618}
1619
1620#ifdef _WIN32
1621/* destructively remove a trailing line terminator from s */
1622static void
1623chomp (char *s)
1624{
1625	size_t len;
1626	if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
1627		s[--len] = 0;
1628		if (len > 0 && s[len - 1] == '\r')
1629			s[--len] = 0;
1630	}
1631}
1632
1633/* FormatMessage returns allocated strings, but evutil_socket_error_to_string
1634 * is supposed to return a string which is good indefinitely without having
1635 * to be freed.  To make this work without leaking memory, we cache the
1636 * string the first time FormatMessage is called on a particular error
1637 * code, and then return the cached string on subsequent calls with the
1638 * same code.  The strings aren't freed until libevent_global_shutdown
1639 * (or never).  We use a linked list to cache the errors, because we
1640 * only expect there to be a few dozen, and that should be fast enough.
1641 */
1642
1643struct cached_sock_errs_entry {
1644	HT_ENTRY(cached_sock_errs_entry) node;
1645	DWORD code;
1646	char *msg; /* allocated with LocalAlloc; free with LocalFree */
1647};
1648
1649static inline unsigned
1650hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
1651{
1652	/* Use Murmur3's 32-bit finalizer as an integer hash function */
1653	DWORD h = e->code;
1654	h ^= h >> 16;
1655	h *= 0x85ebca6b;
1656	h ^= h >> 13;
1657	h *= 0xc2b2ae35;
1658	h ^= h >> 16;
1659	return h;
1660}
1661
1662static inline int
1663eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
1664		    const struct cached_sock_errs_entry *b)
1665{
1666	return a->code == b->code;
1667}
1668
1669#ifndef EVENT__DISABLE_THREAD_SUPPORT
1670static void *windows_socket_errors_lock_ = NULL;
1671#endif
1672
1673static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
1674     windows_socket_errors = HT_INITIALIZER();
1675
1676HT_PROTOTYPE(cached_sock_errs_map,
1677	     cached_sock_errs_entry,
1678	     node,
1679	     hash_cached_sock_errs,
1680	     eq_cached_sock_errs);
1681
1682HT_GENERATE(cached_sock_errs_map,
1683	    cached_sock_errs_entry,
1684	    node,
1685	    hash_cached_sock_errs,
1686	    eq_cached_sock_errs,
1687	    0.5,
1688	    mm_malloc,
1689	    mm_realloc,
1690	    mm_free);
1691
1692/** Equivalent to strerror, but for windows socket errors. */
1693const char *
1694evutil_socket_error_to_string(int errcode)
1695{
1696	struct cached_sock_errs_entry *errs, *newerr, find;
1697	char *msg = NULL;
1698
1699	EVLOCK_LOCK(windows_socket_errors_lock_, 0);
1700
1701	find.code = errcode;
1702	errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
1703	if (errs) {
1704		msg = errs->msg;
1705		goto done;
1706	}
1707
1708	if (0 != FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1709			       FORMAT_MESSAGE_IGNORE_INSERTS |
1710			       FORMAT_MESSAGE_ALLOCATE_BUFFER,
1711			       NULL, errcode, 0, (LPTSTR)&msg, 0, NULL))
1712		chomp (msg);	/* because message has trailing newline */
1713	else {
1714		size_t len = 50;
1715		/* use LocalAlloc because FormatMessage does */
1716		msg = LocalAlloc(LMEM_FIXED, len);
1717		if (!msg) {
1718			msg = (char *)"LocalAlloc failed during Winsock error";
1719			goto done;
1720		}
1721		evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
1722	}
1723
1724	newerr = (struct cached_sock_errs_entry *)
1725		mm_malloc(sizeof (struct cached_sock_errs_entry));
1726
1727	if (!newerr) {
1728		LocalFree(msg);
1729		msg = (char *)"malloc failed during Winsock error";
1730		goto done;
1731	}
1732
1733	newerr->code = errcode;
1734	newerr->msg = msg;
1735	HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
1736
1737 done:
1738	EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
1739
1740	return msg;
1741}
1742
1743#ifndef EVENT__DISABLE_THREAD_SUPPORT
1744int
1745evutil_global_setup_locks_(const int enable_locks)
1746{
1747	EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
1748	return 0;
1749}
1750#endif
1751
1752static void
1753evutil_free_sock_err_globals(void)
1754{
1755	struct cached_sock_errs_entry **errs, *tofree;
1756
1757	for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
1758		     ; errs; ) {
1759		tofree = *errs;
1760		errs = HT_NEXT_RMV(cached_sock_errs_map,
1761				   &windows_socket_errors,
1762				   errs);
1763		LocalFree(tofree->msg);
1764		mm_free(tofree);
1765	}
1766
1767	HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
1768
1769#ifndef EVENT__DISABLE_THREAD_SUPPORT
1770	if (windows_socket_errors_lock_ != NULL) {
1771		EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
1772		windows_socket_errors_lock_ = NULL;
1773	}
1774#endif
1775}
1776
1777#else
1778
1779#ifndef EVENT__DISABLE_THREAD_SUPPORT
1780int
1781evutil_global_setup_locks_(const int enable_locks)
1782{
1783	return 0;
1784}
1785#endif
1786
1787static void
1788evutil_free_sock_err_globals(void)
1789{
1790}
1791
1792#endif
1793
1794int
1795evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
1796{
1797	int r;
1798	va_list ap;
1799	va_start(ap, format);
1800	r = evutil_vsnprintf(buf, buflen, format, ap);
1801	va_end(ap);
1802	return r;
1803}
1804
1805int
1806evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
1807{
1808	int r;
1809	if (!buflen)
1810		return 0;
1811#if defined(_MSC_VER) || defined(_WIN32)
1812	r = _vsnprintf(buf, buflen, format, ap);
1813	if (r < 0)
1814		r = _vscprintf(format, ap);
1815#elif defined(sgi)
1816	/* Make sure we always use the correct vsnprintf on IRIX */
1817	extern int      _xpg5_vsnprintf(char * __restrict,
1818		__SGI_LIBC_NAMESPACE_QUALIFIER size_t,
1819		const char * __restrict, /* va_list */ char *);
1820
1821	r = _xpg5_vsnprintf(buf, buflen, format, ap);
1822#else
1823	r = vsnprintf(buf, buflen, format, ap);
1824#endif
1825	buf[buflen-1] = '\0';
1826	return r;
1827}
1828
1829#define USE_INTERNAL_NTOP
1830#define USE_INTERNAL_PTON
1831
1832const char *
1833evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
1834{
1835#if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1836	return inet_ntop(af, src, dst, len);
1837#else
1838	if (af == AF_INET) {
1839		const struct in_addr *in = src;
1840		const ev_uint32_t a = ntohl(in->s_addr);
1841		int r;
1842		r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
1843		    (int)(ev_uint8_t)((a>>24)&0xff),
1844		    (int)(ev_uint8_t)((a>>16)&0xff),
1845		    (int)(ev_uint8_t)((a>>8 )&0xff),
1846		    (int)(ev_uint8_t)((a    )&0xff));
1847		if (r<0||(size_t)r>=len)
1848			return NULL;
1849		else
1850			return dst;
1851#ifdef AF_INET6
1852	} else if (af == AF_INET6) {
1853		const struct in6_addr *addr = src;
1854		char buf[64], *cp;
1855		int longestGapLen = 0, longestGapPos = -1, i,
1856			curGapPos = -1, curGapLen = 0;
1857		ev_uint16_t words[8];
1858		for (i = 0; i < 8; ++i) {
1859			words[i] =
1860			    (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1861		}
1862		if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1863		    words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1864			(words[5] == 0xffff))) {
1865			/* This is an IPv4 address. */
1866			if (words[5] == 0) {
1867				evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1868				    addr->s6_addr[12], addr->s6_addr[13],
1869				    addr->s6_addr[14], addr->s6_addr[15]);
1870			} else {
1871				evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1872				    addr->s6_addr[12], addr->s6_addr[13],
1873				    addr->s6_addr[14], addr->s6_addr[15]);
1874			}
1875			if (strlen(buf) > len)
1876				return NULL;
1877			strlcpy(dst, buf, len);
1878			return dst;
1879		}
1880		i = 0;
1881		while (i < 8) {
1882			if (words[i] == 0) {
1883				curGapPos = i++;
1884				curGapLen = 1;
1885				while (i<8 && words[i] == 0) {
1886					++i; ++curGapLen;
1887				}
1888				if (curGapLen > longestGapLen) {
1889					longestGapPos = curGapPos;
1890					longestGapLen = curGapLen;
1891				}
1892			} else {
1893				++i;
1894			}
1895		}
1896		if (longestGapLen<=1)
1897			longestGapPos = -1;
1898
1899		cp = buf;
1900		for (i = 0; i < 8; ++i) {
1901			if (words[i] == 0 && longestGapPos == i) {
1902				if (i == 0)
1903					*cp++ = ':';
1904				*cp++ = ':';
1905				while (i < 8 && words[i] == 0)
1906					++i;
1907				--i; /* to compensate for loop increment. */
1908			} else {
1909				evutil_snprintf(cp,
1910								sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1911				cp += strlen(cp);
1912				if (i != 7)
1913					*cp++ = ':';
1914			}
1915		}
1916		*cp = '\0';
1917		if (strlen(buf) > len)
1918			return NULL;
1919		strlcpy(dst, buf, len);
1920		return dst;
1921#endif
1922	} else {
1923		return NULL;
1924	}
1925#endif
1926}
1927
1928int
1929evutil_inet_pton(int af, const char *src, void *dst)
1930{
1931#if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1932	return inet_pton(af, src, dst);
1933#else
1934	if (af == AF_INET) {
1935		unsigned a,b,c,d;
1936		char more;
1937		struct in_addr *addr = dst;
1938		if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
1939			return 0;
1940		if (a > 255) return 0;
1941		if (b > 255) return 0;
1942		if (c > 255) return 0;
1943		if (d > 255) return 0;
1944		addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1945		return 1;
1946#ifdef AF_INET6
1947	} else if (af == AF_INET6) {
1948		struct in6_addr *out = dst;
1949		ev_uint16_t words[8];
1950		int gapPos = -1, i, setWords=0;
1951		const char *dot = strchr(src, '.');
1952		const char *eow; /* end of words. */
1953		if (dot == src)
1954			return 0;
1955		else if (!dot)
1956			eow = src+strlen(src);
1957		else {
1958			unsigned byte1,byte2,byte3,byte4;
1959			char more;
1960			for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
1961				;
1962			++eow;
1963
1964			/* We use "scanf" because some platform inet_aton()s are too lax
1965			 * about IPv4 addresses of the form "1.2.3" */
1966			if (sscanf(eow, "%u.%u.%u.%u%c",
1967					   &byte1,&byte2,&byte3,&byte4,&more) != 4)
1968				return 0;
1969
1970			if (byte1 > 255 ||
1971			    byte2 > 255 ||
1972			    byte3 > 255 ||
1973			    byte4 > 255)
1974				return 0;
1975
1976			words[6] = (byte1<<8) | byte2;
1977			words[7] = (byte3<<8) | byte4;
1978			setWords += 2;
1979		}
1980
1981		i = 0;
1982		while (src < eow) {
1983			if (i > 7)
1984				return 0;
1985			if (EVUTIL_ISXDIGIT_(*src)) {
1986				char *next;
1987				long r = strtol(src, &next, 16);
1988				if (next > 4+src)
1989					return 0;
1990				if (next == src)
1991					return 0;
1992				if (r<0 || r>65536)
1993					return 0;
1994
1995				words[i++] = (ev_uint16_t)r;
1996				setWords++;
1997				src = next;
1998				if (*src != ':' && src != eow)
1999					return 0;
2000				++src;
2001			} else if (*src == ':' && i > 0 && gapPos==-1) {
2002				gapPos = i;
2003				++src;
2004			} else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
2005				gapPos = i;
2006				src += 2;
2007			} else {
2008				return 0;
2009			}
2010		}
2011
2012		if (setWords > 8 ||
2013			(setWords == 8 && gapPos != -1) ||
2014			(setWords < 8 && gapPos == -1))
2015			return 0;
2016
2017		if (gapPos >= 0) {
2018			int nToMove = setWords - (dot ? 2 : 0) - gapPos;
2019			int gapLen = 8 - setWords;
2020			/* assert(nToMove >= 0); */
2021			if (nToMove < 0)
2022				return -1; /* should be impossible */
2023			memmove(&words[gapPos+gapLen], &words[gapPos],
2024					sizeof(ev_uint16_t)*nToMove);
2025			memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
2026		}
2027		for (i = 0; i < 8; ++i) {
2028			out->s6_addr[2*i  ] = words[i] >> 8;
2029			out->s6_addr[2*i+1] = words[i] & 0xff;
2030		}
2031
2032		return 1;
2033#endif
2034	} else {
2035		return -1;
2036	}
2037#endif
2038}
2039
2040int
2041evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
2042{
2043	int port;
2044	char buf[128];
2045	const char *cp, *addr_part, *port_part;
2046	int is_ipv6;
2047	/* recognized formats are:
2048	 * [ipv6]:port
2049	 * ipv6
2050	 * [ipv6]
2051	 * ipv4:port
2052	 * ipv4
2053	 */
2054
2055	cp = strchr(ip_as_string, ':');
2056	if (*ip_as_string == '[') {
2057		int len;
2058		if (!(cp = strchr(ip_as_string, ']'))) {
2059			return -1;
2060		}
2061		len = (int) ( cp-(ip_as_string + 1) );
2062		if (len > (int)sizeof(buf)-1) {
2063			return -1;
2064		}
2065		memcpy(buf, ip_as_string+1, len);
2066		buf[len] = '\0';
2067		addr_part = buf;
2068		if (cp[1] == ':')
2069			port_part = cp+2;
2070		else
2071			port_part = NULL;
2072		is_ipv6 = 1;
2073	} else if (cp && strchr(cp+1, ':')) {
2074		is_ipv6 = 1;
2075		addr_part = ip_as_string;
2076		port_part = NULL;
2077	} else if (cp) {
2078		is_ipv6 = 0;
2079		if (cp - ip_as_string > (int)sizeof(buf)-1) {
2080			return -1;
2081		}
2082		memcpy(buf, ip_as_string, cp-ip_as_string);
2083		buf[cp-ip_as_string] = '\0';
2084		addr_part = buf;
2085		port_part = cp+1;
2086	} else {
2087		addr_part = ip_as_string;
2088		port_part = NULL;
2089		is_ipv6 = 0;
2090	}
2091
2092	if (port_part == NULL) {
2093		port = 0;
2094	} else {
2095		port = atoi(port_part);
2096		if (port <= 0 || port > 65535) {
2097			return -1;
2098		}
2099	}
2100
2101	if (!addr_part)
2102		return -1; /* Should be impossible. */
2103#ifdef AF_INET6
2104	if (is_ipv6)
2105	{
2106		struct sockaddr_in6 sin6;
2107		memset(&sin6, 0, sizeof(sin6));
2108#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2109		sin6.sin6_len = sizeof(sin6);
2110#endif
2111		sin6.sin6_family = AF_INET6;
2112		sin6.sin6_port = htons(port);
2113		if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
2114			return -1;
2115		if ((int)sizeof(sin6) > *outlen)
2116			return -1;
2117		memset(out, 0, *outlen);
2118		memcpy(out, &sin6, sizeof(sin6));
2119		*outlen = sizeof(sin6);
2120		return 0;
2121	}
2122	else
2123#endif
2124	{
2125		struct sockaddr_in sin;
2126		memset(&sin, 0, sizeof(sin));
2127#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2128		sin.sin_len = sizeof(sin);
2129#endif
2130		sin.sin_family = AF_INET;
2131		sin.sin_port = htons(port);
2132		if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
2133			return -1;
2134		if ((int)sizeof(sin) > *outlen)
2135			return -1;
2136		memset(out, 0, *outlen);
2137		memcpy(out, &sin, sizeof(sin));
2138		*outlen = sizeof(sin);
2139		return 0;
2140	}
2141}
2142
2143const char *
2144evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
2145{
2146	char b[128];
2147	const char *res=NULL;
2148	int port;
2149	if (sa->sa_family == AF_INET) {
2150		const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
2151		res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
2152		port = ntohs(sin->sin_port);
2153		if (res) {
2154			evutil_snprintf(out, outlen, "%s:%d", b, port);
2155			return out;
2156		}
2157	} else if (sa->sa_family == AF_INET6) {
2158		const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
2159		res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
2160		port = ntohs(sin6->sin6_port);
2161		if (res) {
2162			evutil_snprintf(out, outlen, "[%s]:%d", b, port);
2163			return out;
2164		}
2165	}
2166
2167	evutil_snprintf(out, outlen, "<addr with socktype %d>",
2168	    (int)sa->sa_family);
2169	return out;
2170}
2171
2172int
2173evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
2174    int include_port)
2175{
2176	int r;
2177	if (0 != (r = (sa1->sa_family - sa2->sa_family)))
2178		return r;
2179
2180	if (sa1->sa_family == AF_INET) {
2181		const struct sockaddr_in *sin1, *sin2;
2182		sin1 = (const struct sockaddr_in *)sa1;
2183		sin2 = (const struct sockaddr_in *)sa2;
2184		if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
2185			return -1;
2186		else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
2187			return 1;
2188		else if (include_port &&
2189		    (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
2190			return r;
2191		else
2192			return 0;
2193	}
2194#ifdef AF_INET6
2195	else if (sa1->sa_family == AF_INET6) {
2196		const struct sockaddr_in6 *sin1, *sin2;
2197		sin1 = (const struct sockaddr_in6 *)sa1;
2198		sin2 = (const struct sockaddr_in6 *)sa2;
2199		if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
2200			return r;
2201		else if (include_port &&
2202		    (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
2203			return r;
2204		else
2205			return 0;
2206	}
2207#endif
2208	return 1;
2209}
2210
2211/* Tables to implement ctypes-replacement EVUTIL_IS*() functions.  Each table
2212 * has 256 bits to look up whether a character is in some set or not.  This
2213 * fails on non-ASCII platforms, but so does every other place where we
2214 * take a char and write it onto the network.
2215 **/
2216static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
2217  { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2218static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
2219  { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
2220static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
2221static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
2222  { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
2223static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
2224static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
2225  { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
2226static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
2227static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
2228/* Upper-casing and lowercasing tables to map characters to upper/lowercase
2229 * equivalents. */
2230static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
2231  0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2232  16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2233  32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2234  48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2235  64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2236  80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
2237  96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
2238  80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
2239  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2240  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2241  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2242  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2243  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2244  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2245  224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2246  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2247};
2248static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
2249  0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2250  16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2251  32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2252  48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2253  64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2254  112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2255  96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2256  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2257  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2258  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2259  160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2260  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2261  192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2262  208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2263  224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2264  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2265};
2266
2267#define IMPL_CTYPE_FN(name)						\
2268	int EVUTIL_##name##_(char c) {					\
2269		ev_uint8_t u = c;					\
2270		return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
2271	}
2272IMPL_CTYPE_FN(ISALPHA)
2273IMPL_CTYPE_FN(ISALNUM)
2274IMPL_CTYPE_FN(ISSPACE)
2275IMPL_CTYPE_FN(ISDIGIT)
2276IMPL_CTYPE_FN(ISXDIGIT)
2277IMPL_CTYPE_FN(ISPRINT)
2278IMPL_CTYPE_FN(ISLOWER)
2279IMPL_CTYPE_FN(ISUPPER)
2280
2281char EVUTIL_TOLOWER_(char c)
2282{
2283	return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2284}
2285char EVUTIL_TOUPPER_(char c)
2286{
2287	return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2288}
2289int
2290evutil_ascii_strcasecmp(const char *s1, const char *s2)
2291{
2292	char c1, c2;
2293	while (1) {
2294		c1 = EVUTIL_TOLOWER_(*s1++);
2295		c2 = EVUTIL_TOLOWER_(*s2++);
2296		if (c1 < c2)
2297			return -1;
2298		else if (c1 > c2)
2299			return 1;
2300		else if (c1 == 0)
2301			return 0;
2302	}
2303}
2304int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2305{
2306	char c1, c2;
2307	while (n--) {
2308		c1 = EVUTIL_TOLOWER_(*s1++);
2309		c2 = EVUTIL_TOLOWER_(*s2++);
2310		if (c1 < c2)
2311			return -1;
2312		else if (c1 > c2)
2313			return 1;
2314		else if (c1 == 0)
2315			return 0;
2316	}
2317	return 0;
2318}
2319
2320void
2321evutil_rtrim_lws_(char *str)
2322{
2323	char *cp;
2324
2325	if (str == NULL)
2326		return;
2327
2328	if ((cp = strchr(str, '\0')) == NULL || (cp == str))
2329		return;
2330
2331	--cp;
2332
2333	while (*cp == ' ' || *cp == '\t') {
2334		*cp = '\0';
2335		if (cp == str)
2336			break;
2337		--cp;
2338	}
2339}
2340
2341static int
2342evutil_issetugid(void)
2343{
2344#ifdef EVENT__HAVE_ISSETUGID
2345	return issetugid();
2346#else
2347
2348#ifdef EVENT__HAVE_GETEUID
2349	if (getuid() != geteuid())
2350		return 1;
2351#endif
2352#ifdef EVENT__HAVE_GETEGID
2353	if (getgid() != getegid())
2354		return 1;
2355#endif
2356	return 0;
2357#endif
2358}
2359
2360const char *
2361evutil_getenv_(const char *varname)
2362{
2363	if (evutil_issetugid())
2364		return NULL;
2365
2366	return getenv(varname);
2367}
2368
2369ev_uint32_t
2370evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
2371{
2372	if (seed == 0) {
2373		struct timeval tv;
2374		evutil_gettimeofday(&tv, NULL);
2375		seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
2376#ifdef _WIN32
2377		seed += (ev_uint32_t) _getpid();
2378#else
2379		seed += (ev_uint32_t) getpid();
2380#endif
2381	}
2382	state->seed = seed;
2383	return seed;
2384}
2385
2386ev_int32_t
2387evutil_weakrand_(struct evutil_weakrand_state *state)
2388{
2389	/* This RNG implementation is a linear congruential generator, with
2390	 * modulus 2^31, multiplier 1103515245, and addend 12345.  It's also
2391	 * used by OpenBSD, and by Glibc's TYPE_0 RNG.
2392	 *
2393	 * The linear congruential generator is not an industrial-strength
2394	 * RNG!  It's fast, but it can have higher-order patterns.  Notably,
2395	 * the low bits tend to have periodicity.
2396	 */
2397	state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
2398	return (ev_int32_t)(state->seed);
2399}
2400
2401ev_int32_t
2402evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
2403{
2404	ev_int32_t divisor, result;
2405
2406	/* We can't just do weakrand() % top, since the low bits of the LCG
2407	 * are less random than the high ones.  (Specifically, since the LCG
2408	 * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
2409	 * therefore the low m bits of the LCG will have period 2^m.) */
2410	divisor = EVUTIL_WEAKRAND_MAX / top;
2411	do {
2412		result = evutil_weakrand_(state) / divisor;
2413	} while (result >= top);
2414	return result;
2415}
2416
2417/**
2418 * Volatile pointer to memset: we use this to keep the compiler from
2419 * eliminating our call to memset.
2420 */
2421void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
2422
2423void
2424evutil_memclear_(void *mem, size_t len)
2425{
2426	evutil_memset_volatile_(mem, 0, len);
2427}
2428
2429int
2430evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
2431{
2432	static const char LOOPBACK_S6[16] =
2433	    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2434	if (addr->sa_family == AF_INET) {
2435		struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2436		return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2437	} else if (addr->sa_family == AF_INET6) {
2438		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2439		return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2440	}
2441	return 0;
2442}
2443
2444int
2445evutil_hex_char_to_int_(char c)
2446{
2447	switch(c)
2448	{
2449		case '0': return 0;
2450		case '1': return 1;
2451		case '2': return 2;
2452		case '3': return 3;
2453		case '4': return 4;
2454		case '5': return 5;
2455		case '6': return 6;
2456		case '7': return 7;
2457		case '8': return 8;
2458		case '9': return 9;
2459		case 'A': case 'a': return 10;
2460		case 'B': case 'b': return 11;
2461		case 'C': case 'c': return 12;
2462		case 'D': case 'd': return 13;
2463		case 'E': case 'e': return 14;
2464		case 'F': case 'f': return 15;
2465	}
2466	return -1;
2467}
2468
2469#ifdef _WIN32
2470HMODULE
2471evutil_load_windows_system_library_(const TCHAR *library_name)
2472{
2473  TCHAR path[MAX_PATH];
2474  unsigned n;
2475  n = GetSystemDirectory(path, MAX_PATH);
2476  if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2477    return 0;
2478  _tcscat(path, TEXT("\\"));
2479  _tcscat(path, library_name);
2480  return LoadLibrary(path);
2481}
2482#endif
2483
2484/* Internal wrapper around 'socket' to provide Linux-style support for
2485 * syscall-saving methods where available.
2486 *
2487 * In addition to regular socket behavior, you can use a bitwise or to set the
2488 * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
2489 * to make the socket nonblocking or close-on-exec with as few syscalls as
2490 * possible.
2491 */
2492evutil_socket_t
2493evutil_socket_(int domain, int type, int protocol)
2494{
2495	evutil_socket_t r;
2496#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
2497	r = socket(domain, type, protocol);
2498	if (r >= 0)
2499		return r;
2500	else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
2501		return -1;
2502#endif
2503#define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
2504	r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
2505	if (r < 0)
2506		return -1;
2507	if (type & EVUTIL_SOCK_NONBLOCK) {
2508		if (evutil_fast_socket_nonblocking(r) < 0) {
2509			evutil_closesocket(r);
2510			return -1;
2511		}
2512	}
2513	if (type & EVUTIL_SOCK_CLOEXEC) {
2514		if (evutil_fast_socket_closeonexec(r) < 0) {
2515			evutil_closesocket(r);
2516			return -1;
2517		}
2518	}
2519	return r;
2520}
2521
2522/* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
2523 * support for syscall-saving methods where available.
2524 *
2525 * In addition to regular accept behavior, you can set one or more of flags
2526 * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
2527 * make the socket nonblocking or close-on-exec with as few syscalls as
2528 * possible.
2529 */
2530evutil_socket_t
2531evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
2532    ev_socklen_t *addrlen, int flags)
2533{
2534	evutil_socket_t result;
2535#if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
2536	result = accept4(sockfd, addr, addrlen, flags);
2537	if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
2538		/* A nonnegative result means that we succeeded, so return.
2539		 * Failing with EINVAL means that an option wasn't supported,
2540		 * and failing with ENOSYS means that the syscall wasn't
2541		 * there: in those cases we want to fall back.  Otherwise, we
2542		 * got a real error, and we should return. */
2543		return result;
2544	}
2545#endif
2546	result = accept(sockfd, addr, addrlen);
2547	if (result < 0)
2548		return result;
2549
2550	if (flags & EVUTIL_SOCK_CLOEXEC) {
2551		if (evutil_fast_socket_closeonexec(result) < 0) {
2552			evutil_closesocket(result);
2553			return -1;
2554		}
2555	}
2556	if (flags & EVUTIL_SOCK_NONBLOCK) {
2557		if (evutil_fast_socket_nonblocking(result) < 0) {
2558			evutil_closesocket(result);
2559			return -1;
2560		}
2561	}
2562	return result;
2563}
2564
2565/* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
2566 * fd[0] get read from fd[1].  Make both fds nonblocking and close-on-exec.
2567 * Return 0 on success, -1 on failure.
2568 */
2569int
2570evutil_make_internal_pipe_(evutil_socket_t fd[2])
2571{
2572	/*
2573	  Making the second socket nonblocking is a bit subtle, given that we
2574	  ignore any EAGAIN returns when writing to it, and you don't usally
2575	  do that for a nonblocking socket. But if the kernel gives us EAGAIN,
2576	  then there's no need to add any more data to the buffer, since
2577	  the main thread is already either about to wake up and drain it,
2578	  or woken up and in the process of draining it.
2579	*/
2580
2581#if defined(EVENT__HAVE_PIPE2)
2582	if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
2583		return 0;
2584#endif
2585#if defined(EVENT__HAVE_PIPE)
2586	if (pipe(fd) == 0) {
2587		if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2588		    evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2589		    evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2590		    evutil_fast_socket_closeonexec(fd[1]) < 0) {
2591			close(fd[0]);
2592			close(fd[1]);
2593			fd[0] = fd[1] = -1;
2594			return -1;
2595		}
2596		return 0;
2597	} else {
2598		event_warn("%s: pipe", __func__);
2599	}
2600#endif
2601
2602#ifdef _WIN32
2603#define LOCAL_SOCKETPAIR_AF AF_INET
2604#else
2605#define LOCAL_SOCKETPAIR_AF AF_UNIX
2606#endif
2607	if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
2608		if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
2609		    evutil_fast_socket_nonblocking(fd[1]) < 0 ||
2610		    evutil_fast_socket_closeonexec(fd[0]) < 0 ||
2611		    evutil_fast_socket_closeonexec(fd[1]) < 0) {
2612			evutil_closesocket(fd[0]);
2613			evutil_closesocket(fd[1]);
2614			fd[0] = fd[1] = -1;
2615			return -1;
2616		}
2617		return 0;
2618	}
2619	fd[0] = fd[1] = -1;
2620	return -1;
2621}
2622
2623/* Wrapper around eventfd on systems that provide it.  Unlike the system
2624 * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
2625 * flags.  Returns -1 on error or if eventfd is not supported.
2626 */
2627evutil_socket_t
2628evutil_eventfd_(unsigned initval, int flags)
2629{
2630#if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
2631	int r;
2632#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
2633	r = eventfd(initval, flags);
2634	if (r >= 0 || flags == 0)
2635		return r;
2636#endif
2637	r = eventfd(initval, 0);
2638	if (r < 0)
2639		return r;
2640	if (flags & EVUTIL_EFD_CLOEXEC) {
2641		if (evutil_fast_socket_closeonexec(r) < 0) {
2642			evutil_closesocket(r);
2643			return -1;
2644		}
2645	}
2646	if (flags & EVUTIL_EFD_NONBLOCK) {
2647		if (evutil_fast_socket_nonblocking(r) < 0) {
2648			evutil_closesocket(r);
2649			return -1;
2650		}
2651	}
2652	return r;
2653#else
2654	return -1;
2655#endif
2656}
2657
2658void
2659evutil_free_globals_(void)
2660{
2661	evutil_free_secure_rng_globals_();
2662	evutil_free_sock_err_globals();
2663}
2664