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