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