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