Home | History | Annotate | Line # | Download | only in dist
evutil.c revision 1.4.8.1
      1 /*	$NetBSD: evutil.c,v 1.4.8.1 2015/02/03 08:23:39 bouyer Exp $	*/
      2 /*
      3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. The name of the author may not be used to endorse or promote products
     14  *    derived from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #include "event2/event-config.h"
     29 #include <sys/cdefs.h>
     30 __RCSID("$NetBSD: evutil.c,v 1.4.8.1 2015/02/03 08:23:39 bouyer Exp $");
     31 
     32 #define _GNU_SOURCE
     33 
     34 #ifdef WIN32
     35 #include <winsock2.h>
     36 #include <ws2tcpip.h>
     37 #define WIN32_LEAN_AND_MEAN
     38 #include <windows.h>
     39 #undef WIN32_LEAN_AND_MEAN
     40 #include <io.h>
     41 #include <tchar.h>
     42 #endif
     43 
     44 #include <sys/types.h>
     45 #ifdef _EVENT_HAVE_SYS_SOCKET_H
     46 #include <sys/socket.h>
     47 #endif
     48 #ifdef _EVENT_HAVE_UNISTD_H
     49 #include <unistd.h>
     50 #endif
     51 #ifdef _EVENT_HAVE_FCNTL_H
     52 #include <fcntl.h>
     53 #endif
     54 #ifdef _EVENT_HAVE_STDLIB_H
     55 #include <stdlib.h>
     56 #endif
     57 #include <errno.h>
     58 #include <limits.h>
     59 #include <stdio.h>
     60 #include <string.h>
     61 #ifdef _EVENT_HAVE_NETINET_IN_H
     62 #include <netinet/in.h>
     63 #endif
     64 #ifdef _EVENT_HAVE_NETINET_IN6_H
     65 #include <netinet/in6.h>
     66 #endif
     67 #ifdef _EVENT_HAVE_ARPA_INET_H
     68 #include <arpa/inet.h>
     69 #endif
     70 
     71 #ifndef _EVENT_HAVE_GETTIMEOFDAY
     72 #include <sys/timeb.h>
     73 #include <time.h>
     74 #endif
     75 #include <sys/stat.h>
     76 
     77 #include "event2/util.h"
     78 #include "util-internal.h"
     79 #include "log-internal.h"
     80 #include "mm-internal.h"
     81 
     82 #include "strlcpy-internal.h"
     83 #include "ipv6-internal.h"
     84 
     85 #ifdef WIN32
     86 #define open _open
     87 #define read _read
     88 #define close _close
     89 #define fstat _fstati64
     90 #define stat _stati64
     91 #define mode_t int
     92 #endif
     93 
     94 int
     95 evutil_open_closeonexec(const char *pathname, int flags, unsigned mode)
     96 {
     97 	int fd;
     98 
     99 #ifdef O_CLOEXEC
    100 	flags |= O_CLOEXEC;
    101 #endif
    102 
    103 	if (flags & O_CREAT)
    104 		fd = open(pathname, flags, (mode_t)mode);
    105 	else
    106 		fd = open(pathname, flags);
    107 	if (fd < 0)
    108 		return -1;
    109 
    110 #if !defined(O_CLOEXEC) && defined(FD_CLOEXEC)
    111 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
    112 		return -1;
    113 #endif
    114 
    115 	return fd;
    116 }
    117 
    118 /**
    119    Read the contents of 'filename' into a newly allocated NUL-terminated
    120    string.  Set *content_out to hold this string, and *len_out to hold its
    121    length (not including the appended NUL).  If 'is_binary', open the file in
    122    binary mode.
    123 
    124    Returns 0 on success, -1 if the open fails, and -2 for all other failures.
    125 
    126    Used internally only; may go away in a future version.
    127  */
    128 int
    129 evutil_read_file(const char *filename, char **content_out, size_t *len_out,
    130     int is_binary)
    131 {
    132 	int fd, r;
    133 	struct stat st;
    134 	char *mem;
    135 	size_t read_so_far=0;
    136 	int mode = O_RDONLY;
    137 
    138 	EVUTIL_ASSERT(content_out);
    139 	EVUTIL_ASSERT(len_out);
    140 	*content_out = NULL;
    141 	*len_out = 0;
    142 
    143 #ifdef O_BINARY
    144 	if (is_binary)
    145 		mode |= O_BINARY;
    146 #endif
    147 
    148 	fd = evutil_open_closeonexec(filename, mode, 0);
    149 	if (fd < 0)
    150 		return -1;
    151 	if (fstat(fd, &st) || st.st_size < 0 ||
    152 	    st.st_size > EV_SSIZE_MAX-1 ) {
    153 		close(fd);
    154 		return -2;
    155 	}
    156 	mem = mm_malloc((size_t)st.st_size + 1);
    157 	if (!mem) {
    158 		close(fd);
    159 		return -2;
    160 	}
    161 	read_so_far = 0;
    162 #ifdef WIN32
    163 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
    164 #else
    165 #define N_TO_READ(x) (x)
    166 #endif
    167 	while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
    168 		read_so_far += r;
    169 		if (read_so_far >= (size_t)st.st_size)
    170 			break;
    171 		EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
    172 	}
    173 	close(fd);
    174 	if (r < 0) {
    175 		mm_free(mem);
    176 		return -2;
    177 	}
    178 	mem[read_so_far] = 0;
    179 
    180 	*len_out = read_so_far;
    181 	*content_out = mem;
    182 	return 0;
    183 }
    184 
    185 int
    186 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
    187 {
    188 #ifndef WIN32
    189 	return socketpair(family, type, protocol, fd);
    190 #else
    191 	return evutil_ersatz_socketpair(family, type, protocol, fd);
    192 #endif
    193 }
    194 
    195 int
    196 evutil_ersatz_socketpair(int family, int type, int protocol,
    197     evutil_socket_t fd[2])
    198 {
    199 	/* This code is originally from Tor.  Used with permission. */
    200 
    201 	/* This socketpair does not work when localhost is down. So
    202 	 * it's really not the same thing at all. But it's close enough
    203 	 * for now, and really, when localhost is down sometimes, we
    204 	 * have other problems too.
    205 	 */
    206 #ifdef WIN32
    207 #define ERR(e) WSA##e
    208 #else
    209 #define ERR(e) e
    210 #endif
    211 	evutil_socket_t listener = -1;
    212 	evutil_socket_t connector = -1;
    213 	evutil_socket_t acceptor = -1;
    214 	struct sockaddr_in listen_addr;
    215 	struct sockaddr_in connect_addr;
    216 	ev_socklen_t size;
    217 	int saved_errno = -1;
    218 
    219 	if (protocol
    220 		|| (family != AF_INET
    221 #ifdef AF_UNIX
    222 		    && family != AF_UNIX
    223 #endif
    224 		)) {
    225 		EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
    226 		return -1;
    227 	}
    228 	if (!fd) {
    229 		EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
    230 		return -1;
    231 	}
    232 
    233 	listener = socket(AF_INET, type, 0);
    234 	if (listener < 0)
    235 		return -1;
    236 	memset(&listen_addr, 0, sizeof(listen_addr));
    237 	listen_addr.sin_family = AF_INET;
    238 	listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    239 	listen_addr.sin_port = 0;	/* kernel chooses port.	 */
    240 	if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
    241 		== -1)
    242 		goto tidy_up_and_fail;
    243 	if (listen(listener, 1) == -1)
    244 		goto tidy_up_and_fail;
    245 
    246 	connector = socket(AF_INET, type, 0);
    247 	if (connector < 0)
    248 		goto tidy_up_and_fail;
    249 	/* We want to find out the port number to connect to.  */
    250 	size = sizeof(connect_addr);
    251 	if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
    252 		goto tidy_up_and_fail;
    253 	if (size != sizeof (connect_addr))
    254 		goto abort_tidy_up_and_fail;
    255 	if (connect(connector, (struct sockaddr *) &connect_addr,
    256 				sizeof(connect_addr)) == -1)
    257 		goto tidy_up_and_fail;
    258 
    259 	size = sizeof(listen_addr);
    260 	acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
    261 	if (acceptor < 0)
    262 		goto tidy_up_and_fail;
    263 	if (size != sizeof(listen_addr))
    264 		goto abort_tidy_up_and_fail;
    265 	/* Now check we are talking to ourself by matching port and host on the
    266 	   two sockets.	 */
    267 	if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
    268 		goto tidy_up_and_fail;
    269 	if (size != sizeof (connect_addr)
    270 		|| listen_addr.sin_family != connect_addr.sin_family
    271 		|| listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
    272 		|| listen_addr.sin_port != connect_addr.sin_port)
    273 		goto abort_tidy_up_and_fail;
    274 	evutil_closesocket(listener);
    275 	fd[0] = connector;
    276 	fd[1] = acceptor;
    277 
    278 	return 0;
    279 
    280  abort_tidy_up_and_fail:
    281 	saved_errno = ERR(ECONNABORTED);
    282  tidy_up_and_fail:
    283 	if (saved_errno < 0)
    284 		saved_errno = EVUTIL_SOCKET_ERROR();
    285 	if (listener != -1)
    286 		evutil_closesocket(listener);
    287 	if (connector != -1)
    288 		evutil_closesocket(connector);
    289 	if (acceptor != -1)
    290 		evutil_closesocket(acceptor);
    291 
    292 	EVUTIL_SET_SOCKET_ERROR(saved_errno);
    293 	return -1;
    294 #undef ERR
    295 }
    296 
    297 int
    298 evutil_make_socket_nonblocking(evutil_socket_t fd)
    299 {
    300 #ifdef WIN32
    301 	{
    302 		u_long nonblocking = 1;
    303 		if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
    304 			event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
    305 			return -1;
    306 		}
    307 	}
    308 #else
    309 	{
    310 		int flags;
    311 		if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
    312 			event_warn("fcntl(%d, F_GETFL)", fd);
    313 			return -1;
    314 		}
    315 		if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
    316 			event_warn("fcntl(%d, F_SETFL)", fd);
    317 			return -1;
    318 		}
    319 	}
    320 #endif
    321 	return 0;
    322 }
    323 
    324 int
    325 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
    326 {
    327 #ifndef WIN32
    328 	int one = 1;
    329 	/* REUSEADDR on Unix means, "don't hang on to this address after the
    330 	 * listener is closed."  On Windows, though, it means "don't keep other
    331 	 * processes from binding to this address while we're using it. */
    332 	return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
    333 	    (ev_socklen_t)sizeof(one));
    334 #else
    335 	return 0;
    336 #endif
    337 }
    338 
    339 int
    340 evutil_make_socket_closeonexec(evutil_socket_t fd)
    341 {
    342 #if !defined(WIN32) && defined(_EVENT_HAVE_SETFD)
    343 	int flags;
    344 	if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
    345 		event_warn("fcntl(%d, F_GETFD)", fd);
    346 		return -1;
    347 	}
    348 	if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
    349 		event_warn("fcntl(%d, F_SETFD)", fd);
    350 		return -1;
    351 	}
    352 #endif
    353 	return 0;
    354 }
    355 
    356 int
    357 evutil_closesocket(evutil_socket_t sock)
    358 {
    359 #ifndef WIN32
    360 	return close(sock);
    361 #else
    362 	return closesocket(sock);
    363 #endif
    364 }
    365 
    366 ev_int64_t
    367 evutil_strtoll(const char *s, char **endptr, int base)
    368 {
    369 #ifdef _EVENT_HAVE_STRTOLL
    370 	return (ev_int64_t)strtoll(s, endptr, base);
    371 #elif _EVENT_SIZEOF_LONG == 8
    372 	return (ev_int64_t)strtol(s, endptr, base);
    373 #elif defined(WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
    374 	/* XXXX on old versions of MS APIs, we only support base
    375 	 * 10. */
    376 	ev_int64_t r;
    377 	if (base != 10)
    378 		return 0;
    379 	r = (ev_int64_t) _atoi64(s);
    380 	while (isspace(*s))
    381 		++s;
    382 	if (*s == '-')
    383 		++s;
    384 	while (isdigit(*s))
    385 		++s;
    386 	if (endptr)
    387 		*endptr = (char*) s;
    388 	return r;
    389 #elif defined(WIN32)
    390 	return (ev_int64_t) _strtoi64(s, endptr, base);
    391 #elif defined(_EVENT_SIZEOF_LONG_LONG) && _EVENT_SIZEOF_LONG_LONG == 8
    392 	long long r;
    393 	int n;
    394 	if (base != 10 && base != 16)
    395 		return 0;
    396 	if (base == 10) {
    397 		n = sscanf(s, "%lld", &r);
    398 	} else {
    399 		unsigned long long ru=0;
    400 		n = sscanf(s, "%llx", &ru);
    401 		if (ru > EV_INT64_MAX)
    402 			return 0;
    403 		r = (long long) ru;
    404 	}
    405 	if (n != 1)
    406 		return 0;
    407 	while (EVUTIL_ISSPACE(*s))
    408 		++s;
    409 	if (*s == '-')
    410 		++s;
    411 	if (base == 10) {
    412 		while (EVUTIL_ISDIGIT(*s))
    413 			++s;
    414 	} else {
    415 		while (EVUTIL_ISXDIGIT(*s))
    416 			++s;
    417 	}
    418 	if (endptr)
    419 		*endptr = (char*) s;
    420 	return r;
    421 #else
    422 #error "I don't know how to parse 64-bit integers."
    423 #endif
    424 }
    425 
    426 #ifndef _EVENT_HAVE_GETTIMEOFDAY
    427 /* No gettimeofday; this muse be windows. */
    428 int
    429 evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
    430 {
    431 	struct _timeb tb;
    432 
    433 	if (tv == NULL)
    434 		return -1;
    435 
    436 	/* XXXX
    437 	 * _ftime is not the greatest interface here; GetSystemTimeAsFileTime
    438 	 * would give us better resolution, whereas something cobbled together
    439 	 * with GetTickCount could maybe give us monotonic behavior.
    440 	 *
    441 	 * Either way, I think this value might be skewed to ignore the
    442 	 * timezone, and just return local time.  That's not so good.
    443 	 */
    444 	_ftime(&tb);
    445 	tv->tv_sec = (long) tb.time;
    446 	tv->tv_usec = ((int) tb.millitm) * 1000;
    447 	return 0;
    448 }
    449 #endif
    450 
    451 #ifdef WIN32
    452 int
    453 evutil_socket_geterror(evutil_socket_t sock)
    454 {
    455 	int optval, optvallen=sizeof(optval);
    456 	int err = WSAGetLastError();
    457 	if (err == WSAEWOULDBLOCK && sock >= 0) {
    458 		if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
    459 					   &optvallen))
    460 			return err;
    461 		if (optval)
    462 			return optval;
    463 	}
    464 	return err;
    465 }
    466 #endif
    467 
    468 /* XXX we should use an enum here. */
    469 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
    470 int
    471 evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
    472 {
    473 	int made_fd = 0;
    474 
    475 	if (*fd_ptr < 0) {
    476 		if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
    477 			goto err;
    478 		made_fd = 1;
    479 		if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
    480 			goto err;
    481 		}
    482 	}
    483 
    484 	if (connect(*fd_ptr, sa, socklen) < 0) {
    485 		int e = evutil_socket_geterror(*fd_ptr);
    486 		if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
    487 			return 0;
    488 		if (EVUTIL_ERR_CONNECT_REFUSED(e))
    489 			return 2;
    490 		goto err;
    491 	} else {
    492 		return 1;
    493 	}
    494 
    495 err:
    496 	if (made_fd) {
    497 		evutil_closesocket(*fd_ptr);
    498 		*fd_ptr = -1;
    499 	}
    500 	return -1;
    501 }
    502 
    503 /* Check whether a socket on which we called connect() is done
    504    connecting. Return 1 for connected, 0 for not yet, -1 for error.  In the
    505    error case, set the current socket errno to the error that happened during
    506    the connect operation. */
    507 int
    508 evutil_socket_finished_connecting(evutil_socket_t fd)
    509 {
    510 	int e;
    511 	ev_socklen_t elen = sizeof(e);
    512 
    513 	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
    514 		return -1;
    515 
    516 	if (e) {
    517 		if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
    518 			return 0;
    519 		EVUTIL_SET_SOCKET_ERROR(e);
    520 		return -1;
    521 	}
    522 
    523 	return 1;
    524 }
    525 
    526 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
    527      EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
    528      EVUTIL_AI_ADDRCONFIG) != \
    529     (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
    530      EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
    531      EVUTIL_AI_ADDRCONFIG)
    532 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
    533 #endif
    534 
    535 /* We sometimes need to know whether we have an ipv4 address and whether we
    536    have an ipv6 address. If 'have_checked_interfaces', then we've already done
    537    the test.  If 'had_ipv4_address', then it turns out we had an ipv4 address.
    538    If 'had_ipv6_address', then it turns out we had an ipv6 address.   These are
    539    set by evutil_check_interfaces. */
    540 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
    541 
    542 /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
    543  */
    544 #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
    545 
    546 /* Macro: True iff the IPv4 address 'addr', in host order, is a class D
    547  * (multiclass) address.
    548  */
    549 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
    550 
    551 /* Test whether we have an ipv4 interface and an ipv6 interface.  Return 0 if
    552  * the test seemed successful. */
    553 static int
    554 evutil_check_interfaces(int force_recheck)
    555 {
    556 	const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
    557 	    "\x00\x00\x00\x00\x00\x00\x00\x00";
    558 	evutil_socket_t fd = -1;
    559 	struct sockaddr_in sin, sin_out;
    560 	struct sockaddr_in6 sin6, sin6_out;
    561 	ev_socklen_t sin_out_len = sizeof(sin_out);
    562 	ev_socklen_t sin6_out_len = sizeof(sin6_out);
    563 	int r;
    564 	char buf[128];
    565 	if (have_checked_interfaces && !force_recheck)
    566 		return 0;
    567 
    568 	/* To check whether we have an interface open for a given protocol, we
    569 	 * try to make a UDP 'connection' to a remote host on the internet.
    570 	 * We don't actually use it, so the address doesn't matter, but we
    571 	 * want to pick one that keep us from using a host- or link-local
    572 	 * interface. */
    573 	memset(&sin, 0, sizeof(sin));
    574 	sin.sin_family = AF_INET;
    575 	sin.sin_port = htons(53);
    576 	r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
    577 	EVUTIL_ASSERT(r);
    578 
    579 	memset(&sin6, 0, sizeof(sin6));
    580 	sin6.sin6_family = AF_INET6;
    581 	sin6.sin6_port = htons(53);
    582 	r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
    583 	EVUTIL_ASSERT(r);
    584 
    585 	memset(&sin_out, 0, sizeof(sin_out));
    586 	memset(&sin6_out, 0, sizeof(sin6_out));
    587 
    588 	/* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
    589 	if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
    590 	    connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
    591 	    getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
    592 		/* We might have an IPv4 interface. */
    593 		ev_uint32_t addr = ntohl(sin_out.sin_addr.s_addr);
    594 		if (addr == 0 ||
    595 		    EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
    596 		    EVUTIL_V4ADDR_IS_CLASSD(addr)) {
    597 			evutil_inet_ntop(AF_INET, &sin_out.sin_addr,
    598 			    buf, sizeof(buf));
    599 			/* This is a reserved, ipv4compat, ipv4map, loopback,
    600 			 * link-local or unspecified address.  The host should
    601 			 * never have given it to us; it could never connect
    602 			 * to sin. */
    603 			event_warnx("Got a strange local ipv4 address %s",buf);
    604 		} else {
    605 			event_debug(("Detected an IPv4 interface"));
    606 			had_ipv4_address = 1;
    607 		}
    608 	}
    609 	if (fd >= 0)
    610 		evutil_closesocket(fd);
    611 
    612 	if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
    613 	    connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
    614 	    getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
    615 		/* We might have an IPv6 interface. */
    616 		const unsigned char *addr =
    617 		    (unsigned char*)sin6_out.sin6_addr.s6_addr;
    618 		if (!memcmp(addr, ZEROES, 8) ||
    619 		    (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80)) {
    620 			/* This is a reserved, ipv4compat, ipv4map, loopback,
    621 			 * link-local or unspecified address.  The host should
    622 			 * never have given it to us; it could never connect
    623 			 * to sin6. */
    624 			evutil_inet_ntop(AF_INET6, &sin6_out.sin6_addr,
    625 			    buf, sizeof(buf));
    626 			event_warnx("Got a strange local ipv6 address %s",buf);
    627 		} else {
    628 			event_debug(("Detected an IPv4 interface"));
    629 			had_ipv6_address = 1;
    630 		}
    631 	}
    632 
    633 	if (fd >= 0)
    634 		evutil_closesocket(fd);
    635 
    636 	return 0;
    637 }
    638 
    639 /* Internal addrinfo flag.  This one is set when we allocate the addrinfo from
    640  * inside libevent.  Otherwise, the built-in getaddrinfo() function allocated
    641  * it, and we should trust what they said.
    642  **/
    643 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
    644 
    645 /* Helper: construct a new addrinfo containing the socket address in
    646  * 'sa', which must be a sockaddr_in or a sockaddr_in6.  Take the
    647  * socktype and protocol info from hints.  If they weren't set, then
    648  * allocate both a TCP and a UDP addrinfo.
    649  */
    650 struct evutil_addrinfo *
    651 evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
    652     const struct evutil_addrinfo *hints)
    653 {
    654 	struct evutil_addrinfo *res;
    655 	EVUTIL_ASSERT(hints);
    656 
    657 	if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
    658 		/* Indecisive user! Give them a UDP and a TCP. */
    659 		struct evutil_addrinfo *r1, *r2;
    660 		struct evutil_addrinfo tmp;
    661 		memcpy(&tmp, hints, sizeof(tmp));
    662 		tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
    663 		r1 = evutil_new_addrinfo(sa, socklen, &tmp);
    664 		if (!r1)
    665 			return NULL;
    666 		tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
    667 		r2 = evutil_new_addrinfo(sa, socklen, &tmp);
    668 		if (!r2) {
    669 			evutil_freeaddrinfo(r1);
    670 			return NULL;
    671 		}
    672 		r1->ai_next = r2;
    673 		return r1;
    674 	}
    675 
    676 	/* We're going to allocate extra space to hold the sockaddr. */
    677 	res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
    678 	if (!res)
    679 		return NULL;
    680 	res->ai_addr = (struct sockaddr*)
    681 	    (((char*)res) + sizeof(struct evutil_addrinfo));
    682 	memcpy(res->ai_addr, sa, socklen);
    683 	res->ai_addrlen = socklen;
    684 	res->ai_family = sa->sa_family; /* Same or not? XXX */
    685 	res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
    686 	res->ai_socktype = hints->ai_socktype;
    687 	res->ai_protocol = hints->ai_protocol;
    688 
    689 	return res;
    690 }
    691 
    692 /* Append the addrinfo 'append' to the end of 'first', and return the start of
    693  * the list.  Either element can be NULL, in which case we return the element
    694  * that is not NULL. */
    695 struct evutil_addrinfo *
    696 evutil_addrinfo_append(struct evutil_addrinfo *first,
    697     struct evutil_addrinfo *append)
    698 {
    699 	struct evutil_addrinfo *ai = first;
    700 	if (!ai)
    701 		return append;
    702 	while (ai->ai_next)
    703 		ai = ai->ai_next;
    704 	ai->ai_next = append;
    705 
    706 	return first;
    707 }
    708 
    709 static int
    710 parse_numeric_servname(const char *servname)
    711 {
    712 	int n;
    713 	char *endptr=NULL;
    714 	n = (int) strtol(servname, &endptr, 10);
    715 	if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
    716 		return n;
    717 	else
    718 		return -1;
    719 }
    720 
    721 /** Parse a service name in 'servname', which can be a decimal port.
    722  * Return the port number, or -1 on error.
    723  */
    724 static int
    725 evutil_parse_servname(const char *servname, const char *protocol,
    726     const struct evutil_addrinfo *hints)
    727 {
    728 	int n = parse_numeric_servname(servname);
    729 	if (n>=0)
    730 		return n;
    731 #if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(WIN32)
    732 	if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
    733 		struct servent *ent = getservbyname(servname, protocol);
    734 		if (ent) {
    735 			return ntohs(ent->s_port);
    736 		}
    737 	}
    738 #endif
    739 	return -1;
    740 }
    741 
    742 /* Return a string corresponding to a protocol number that we can pass to
    743  * getservyname.  */
    744 static const char *
    745 evutil_unparse_protoname(int proto)
    746 {
    747 	switch (proto) {
    748 	case 0:
    749 		return NULL;
    750 	case IPPROTO_TCP:
    751 		return "tcp";
    752 	case IPPROTO_UDP:
    753 		return "udp";
    754 #ifdef IPPROTO_SCTP
    755 	case IPPROTO_SCTP:
    756 		return "sctp";
    757 #endif
    758 	default:
    759 #ifdef _EVENT_HAVE_GETPROTOBYNUMBER
    760 		{
    761 			struct protoent *ent = getprotobynumber(proto);
    762 			if (ent)
    763 				return ent->p_name;
    764 		}
    765 #endif
    766 		return NULL;
    767 	}
    768 }
    769 
    770 static void
    771 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
    772 {
    773 	/* If we can guess the protocol from the socktype, do so. */
    774 	if (!hints->ai_protocol && hints->ai_socktype) {
    775 		if (hints->ai_socktype == SOCK_DGRAM)
    776 			hints->ai_protocol = IPPROTO_UDP;
    777 		else if (hints->ai_socktype == SOCK_STREAM)
    778 			hints->ai_protocol = IPPROTO_TCP;
    779 	}
    780 
    781 	/* Set the socktype if it isn't set. */
    782 	if (!hints->ai_socktype && hints->ai_protocol) {
    783 		if (hints->ai_protocol == IPPROTO_UDP)
    784 			hints->ai_socktype = SOCK_DGRAM;
    785 		else if (hints->ai_protocol == IPPROTO_TCP)
    786 			hints->ai_socktype = SOCK_STREAM;
    787 #ifdef IPPROTO_SCTP
    788 		else if (hints->ai_protocol == IPPROTO_SCTP)
    789 			hints->ai_socktype = SOCK_STREAM;
    790 #endif
    791 	}
    792 }
    793 
    794 #if AF_UNSPEC != PF_UNSPEC
    795 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
    796 #endif
    797 
    798 /** Implements the part of looking up hosts by name that's common to both
    799  * the blocking and nonblocking resolver:
    800  *   - Adjust 'hints' to have a reasonable socktype and protocol.
    801  *   - Look up the port based on 'servname', and store it in *portnum,
    802  *   - Handle the nodename==NULL case
    803  *   - Handle some invalid arguments cases.
    804  *   - Handle the cases where nodename is an IPv4 or IPv6 address.
    805  *
    806  * If we need the resolver to look up the hostname, we return
    807  * EVUTIL_EAI_NEED_RESOLVE.  Otherwise, we can completely implement
    808  * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
    809  * set *res as getaddrinfo would.
    810  */
    811 int
    812 evutil_getaddrinfo_common(const char *nodename, const char *servname,
    813     struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
    814 {
    815 	int port = 0;
    816 	const char *pname;
    817 
    818 	if (nodename == NULL && servname == NULL)
    819 		return EVUTIL_EAI_NONAME;
    820 
    821 	/* We only understand 3 families */
    822 	if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
    823 	    hints->ai_family != PF_INET6)
    824 		return EVUTIL_EAI_FAMILY;
    825 
    826 	evutil_getaddrinfo_infer_protocols(hints);
    827 
    828 	/* Look up the port number and protocol, if possible. */
    829 	pname = evutil_unparse_protoname(hints->ai_protocol);
    830 	if (servname) {
    831 		/* XXXX We could look at the protocol we got back from
    832 		 * getservbyname, but it doesn't seem too useful. */
    833 		port = evutil_parse_servname(servname, pname, hints);
    834 		if (port < 0) {
    835 			return EVUTIL_EAI_NONAME;
    836 		}
    837 	}
    838 
    839 	/* If we have no node name, then we're supposed to bind to 'any' and
    840 	 * connect to localhost. */
    841 	if (nodename == NULL) {
    842 		struct evutil_addrinfo *res4=NULL, *res6=NULL;
    843 		if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
    844 			struct sockaddr_in6 sin6;
    845 			memset(&sin6, 0, sizeof(sin6));
    846 			sin6.sin6_family = AF_INET6;
    847 			sin6.sin6_port = htons(port);
    848 			if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
    849 				/* Bind to :: */
    850 			} else {
    851 				/* connect to ::1 */
    852 				sin6.sin6_addr.s6_addr[15] = 1;
    853 			}
    854 			res6 = evutil_new_addrinfo((struct sockaddr*)&sin6,
    855 			    sizeof(sin6), hints);
    856 			if (!res6)
    857 				return EVUTIL_EAI_MEMORY;
    858 		}
    859 
    860 		if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
    861 			struct sockaddr_in sin;
    862 			memset(&sin, 0, sizeof(sin));
    863 			sin.sin_family = AF_INET;
    864 			sin.sin_port = htons(port);
    865 			if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
    866 				/* Bind to 0.0.0.0 */
    867 			} else {
    868 				/* connect to 127.0.0.1 */
    869 				sin.sin_addr.s_addr = htonl(0x7f000001);
    870 			}
    871 			res4 = evutil_new_addrinfo((struct sockaddr*)&sin,
    872 			    sizeof(sin), hints);
    873 			if (!res4) {
    874 				if (res6)
    875 					evutil_freeaddrinfo(res6);
    876 				return EVUTIL_EAI_MEMORY;
    877 			}
    878 		}
    879 		*res = evutil_addrinfo_append(res4, res6);
    880 		return 0;
    881 	}
    882 
    883 	/* If we can, we should try to parse the hostname without resolving
    884 	 * it. */
    885 	/* Try ipv6. */
    886 	if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
    887 		struct sockaddr_in6 sin6;
    888 		memset(&sin6, 0, sizeof(sin6));
    889 		if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
    890 			/* Got an ipv6 address. */
    891 			sin6.sin6_family = AF_INET6;
    892 			sin6.sin6_port = htons(port);
    893 			*res = evutil_new_addrinfo((struct sockaddr*)&sin6,
    894 			    sizeof(sin6), hints);
    895 			if (!*res)
    896 				return EVUTIL_EAI_MEMORY;
    897 			return 0;
    898 		}
    899 	}
    900 
    901 	/* Try ipv4. */
    902 	if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
    903 		struct sockaddr_in sin;
    904 		memset(&sin, 0, sizeof(sin));
    905 		if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
    906 			/* Got an ipv6 address. */
    907 			sin.sin_family = AF_INET;
    908 			sin.sin_port = htons(port);
    909 			*res = evutil_new_addrinfo((struct sockaddr*)&sin,
    910 			    sizeof(sin), hints);
    911 			if (!*res)
    912 				return EVUTIL_EAI_MEMORY;
    913 			return 0;
    914 		}
    915 	}
    916 
    917 
    918 	/* If we have reached this point, we definitely need to do a DNS
    919 	 * lookup. */
    920 	if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
    921 		/* If we're not allowed to do one, then say so. */
    922 		return EVUTIL_EAI_NONAME;
    923 	}
    924 	*portnum = port;
    925 	return EVUTIL_EAI_NEED_RESOLVE;
    926 }
    927 
    928 #ifdef _EVENT_HAVE_GETADDRINFO
    929 #define USE_NATIVE_GETADDRINFO
    930 #endif
    931 
    932 #ifdef USE_NATIVE_GETADDRINFO
    933 /* A mask of all the flags that we declare, so we can clear them before calling
    934  * the native getaddrinfo */
    935 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
    936 #ifndef AI_PASSIVE
    937     EVUTIL_AI_PASSIVE |
    938 #endif
    939 #ifndef AI_CANONNAME
    940     EVUTIL_AI_CANONNAME |
    941 #endif
    942 #ifndef AI_NUMERICHOST
    943     EVUTIL_AI_NUMERICHOST |
    944 #endif
    945 #ifndef AI_NUMERICSERV
    946     EVUTIL_AI_NUMERICSERV |
    947 #endif
    948 #ifndef AI_ADDRCONFIG
    949     EVUTIL_AI_ADDRCONFIG |
    950 #endif
    951 #ifndef AI_ALL
    952     EVUTIL_AI_ALL |
    953 #endif
    954 #ifndef AI_V4MAPPED
    955     EVUTIL_AI_V4MAPPED |
    956 #endif
    957     EVUTIL_AI_LIBEVENT_ALLOCATED;
    958 
    959 static const unsigned int ALL_NATIVE_AI_FLAGS =
    960 #ifdef AI_PASSIVE
    961     AI_PASSIVE |
    962 #endif
    963 #ifdef AI_CANONNAME
    964     AI_CANONNAME |
    965 #endif
    966 #ifdef AI_NUMERICHOST
    967     AI_NUMERICHOST |
    968 #endif
    969 #ifdef AI_NUMERICSERV
    970     AI_NUMERICSERV |
    971 #endif
    972 #ifdef AI_ADDRCONFIG
    973     AI_ADDRCONFIG |
    974 #endif
    975 #ifdef AI_ALL
    976     AI_ALL |
    977 #endif
    978 #ifdef AI_V4MAPPED
    979     AI_V4MAPPED |
    980 #endif
    981     0;
    982 #endif
    983 
    984 #ifndef USE_NATIVE_GETADDRINFO
    985 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
    986  * a struct hostent.
    987  */
    988 static struct evutil_addrinfo *
    989 addrinfo_from_hostent(const struct hostent *ent,
    990     int port, const struct evutil_addrinfo *hints)
    991 {
    992 	int i;
    993 	struct sockaddr_in sin;
    994 	struct sockaddr_in6 sin6;
    995 	struct sockaddr *sa;
    996 	int socklen;
    997 	struct evutil_addrinfo *res=NULL, *ai;
    998 	void *addrp;
    999 
   1000 	if (ent->h_addrtype == PF_INET) {
   1001 		memset(&sin, 0, sizeof(sin));
   1002 		sin.sin_family = AF_INET;
   1003 		sin.sin_port = htons(port);
   1004 		sa = (struct sockaddr *)&sin;
   1005 		socklen = sizeof(struct sockaddr_in);
   1006 		addrp = &sin.sin_addr;
   1007 		if (ent->h_length != sizeof(sin.sin_addr)) {
   1008 			event_warnx("Weird h_length from gethostbyname");
   1009 			return NULL;
   1010 		}
   1011 	} else if (ent->h_addrtype == PF_INET6) {
   1012 		memset(&sin6, 0, sizeof(sin6));
   1013 		sin6.sin6_family = AF_INET6;
   1014 		sin6.sin6_port = htons(port);
   1015 		sa = (struct sockaddr *)&sin6;
   1016 		socklen = sizeof(struct sockaddr_in);
   1017 		addrp = &sin6.sin6_addr;
   1018 		if (ent->h_length != sizeof(sin6.sin6_addr)) {
   1019 			event_warnx("Weird h_length from gethostbyname");
   1020 			return NULL;
   1021 		}
   1022 	} else
   1023 		return NULL;
   1024 
   1025 	for (i = 0; ent->h_addr_list[i]; ++i) {
   1026 		memcpy(addrp, ent->h_addr_list[i], ent->h_length);
   1027 		ai = evutil_new_addrinfo(sa, socklen, hints);
   1028 		if (!ai) {
   1029 			evutil_freeaddrinfo(res);
   1030 			return NULL;
   1031 		}
   1032 		res = evutil_addrinfo_append(res, ai);
   1033 	}
   1034 
   1035 	if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
   1036 		res->ai_canonname = mm_strdup(ent->h_name);
   1037 		if (res->ai_canonname == NULL) {
   1038 			evutil_freeaddrinfo(res);
   1039 			return NULL;
   1040 		}
   1041 	}
   1042 
   1043 	return res;
   1044 }
   1045 #endif
   1046 
   1047 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
   1048  * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
   1049  * that we'll only get addresses we could maybe connect to.
   1050  */
   1051 void
   1052 evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints)
   1053 {
   1054 	if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
   1055 		return;
   1056 	if (hints->ai_family != PF_UNSPEC)
   1057 		return;
   1058 	if (!have_checked_interfaces)
   1059 		evutil_check_interfaces(0);
   1060 	if (had_ipv4_address && !had_ipv6_address) {
   1061 		hints->ai_family = PF_INET;
   1062 	} else if (!had_ipv4_address && had_ipv6_address) {
   1063 		hints->ai_family = PF_INET6;
   1064 	}
   1065 }
   1066 
   1067 #ifdef USE_NATIVE_GETADDRINFO
   1068 static int need_numeric_port_hack_=0;
   1069 static int need_socktype_protocol_hack_=0;
   1070 static int tested_for_getaddrinfo_hacks=0;
   1071 
   1072 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
   1073    giving a numeric port without giving an ai_socktype was verboten.
   1074    We test for this so we can apply an appropriate workaround.  If it
   1075    turns out that the bug is present, then:
   1076 
   1077     - If nodename==NULL and servname is numeric, we build an answer
   1078       ourselves using evutil_getaddrinfo_common().
   1079 
   1080     - If nodename!=NULL and servname is numeric, then we set
   1081       servname=NULL when calling getaddrinfo, and post-process the
   1082       result to set the ports on it.
   1083 
   1084    We test for this bug at runtime, since otherwise we can't have the
   1085    same binary run on multiple BSD versions.
   1086 
   1087    - Some versions of Solaris believe that it's nice to leave to protocol
   1088      field set to 0.  We test for this so we can apply an appropriate
   1089      workaround.
   1090 */
   1091 static void
   1092 test_for_getaddrinfo_hacks(void)
   1093 {
   1094 	int r, r2;
   1095 	struct evutil_addrinfo *ai=NULL, *ai2=NULL;
   1096 	struct evutil_addrinfo hints;
   1097 
   1098 	memset(&hints,0,sizeof(hints));
   1099 	hints.ai_family = PF_UNSPEC;
   1100 	hints.ai_flags =
   1101 #ifdef AI_NUMERICHOST
   1102 	    AI_NUMERICHOST |
   1103 #endif
   1104 #ifdef AI_NUMERICSERV
   1105 	    AI_NUMERICSERV |
   1106 #endif
   1107 	    0;
   1108 	r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
   1109 	hints.ai_socktype = SOCK_STREAM;
   1110 	r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
   1111 	if (r2 == 0 && r != 0) {
   1112 		need_numeric_port_hack_=1;
   1113 	}
   1114 	if (ai2 && ai2->ai_protocol == 0) {
   1115 		need_socktype_protocol_hack_=1;
   1116 	}
   1117 
   1118 	if (ai)
   1119 		freeaddrinfo(ai);
   1120 	if (ai2)
   1121 		freeaddrinfo(ai2);
   1122 	tested_for_getaddrinfo_hacks=1;
   1123 }
   1124 
   1125 static inline int
   1126 need_numeric_port_hack(void)
   1127 {
   1128 	if (!tested_for_getaddrinfo_hacks)
   1129 		test_for_getaddrinfo_hacks();
   1130 	return need_numeric_port_hack_;
   1131 }
   1132 
   1133 static inline int
   1134 need_socktype_protocol_hack(void)
   1135 {
   1136 	if (!tested_for_getaddrinfo_hacks)
   1137 		test_for_getaddrinfo_hacks();
   1138 	return need_socktype_protocol_hack_;
   1139 }
   1140 
   1141 static void
   1142 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
   1143 {
   1144 	/* Now we run through the list and set the ports on all of the
   1145 	 * results where ports would make sense. */
   1146 	for ( ; *ai; ai = &(*ai)->ai_next) {
   1147 		struct sockaddr *sa = (*ai)->ai_addr;
   1148 		if (sa && sa->sa_family == AF_INET) {
   1149 			struct sockaddr_in *sin = (struct sockaddr_in*)sa;
   1150 			sin->sin_port = htons(port);
   1151 		} else if (sa && sa->sa_family == AF_INET6) {
   1152 			struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
   1153 			sin6->sin6_port = htons(port);
   1154 		} else {
   1155 			/* A numeric port makes no sense here; remove this one
   1156 			 * from the list. */
   1157 			struct evutil_addrinfo *victim = *ai;
   1158 			*ai = victim->ai_next;
   1159 			victim->ai_next = NULL;
   1160 			freeaddrinfo(victim);
   1161 		}
   1162 	}
   1163 }
   1164 
   1165 static int
   1166 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
   1167 {
   1168 	struct evutil_addrinfo *ai_new;
   1169 	for (; ai; ai = ai->ai_next) {
   1170 		evutil_getaddrinfo_infer_protocols(ai);
   1171 		if (ai->ai_socktype || ai->ai_protocol)
   1172 			continue;
   1173 		ai_new = mm_malloc(sizeof(*ai_new));
   1174 		if (!ai_new)
   1175 			return -1;
   1176 		memcpy(ai_new, ai, sizeof(*ai_new));
   1177 		ai->ai_socktype = SOCK_STREAM;
   1178 		ai->ai_protocol = IPPROTO_TCP;
   1179 		ai_new->ai_socktype = SOCK_DGRAM;
   1180 		ai_new->ai_protocol = IPPROTO_UDP;
   1181 
   1182 		ai_new->ai_next = ai->ai_next;
   1183 		ai->ai_next = ai_new;
   1184 	}
   1185 	return 0;
   1186 }
   1187 #endif
   1188 
   1189 int
   1190 evutil_getaddrinfo(const char *nodename, const char *servname,
   1191     const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
   1192 {
   1193 #ifdef USE_NATIVE_GETADDRINFO
   1194 	struct evutil_addrinfo hints;
   1195 	int portnum=-1, need_np_hack, err;
   1196 
   1197 	if (hints_in) {
   1198 		memcpy(&hints, hints_in, sizeof(hints));
   1199 	} else {
   1200 		memset(&hints, 0, sizeof(hints));
   1201 		hints.ai_family = PF_UNSPEC;
   1202 	}
   1203 
   1204 #ifndef AI_ADDRCONFIG
   1205 	/* Not every system has AI_ADDRCONFIG, so fake it. */
   1206 	if (hints.ai_family == PF_UNSPEC &&
   1207 	    (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
   1208 		evutil_adjust_hints_for_addrconfig(&hints);
   1209 	}
   1210 #endif
   1211 
   1212 #ifndef AI_NUMERICSERV
   1213 	/* Not every system has AI_NUMERICSERV, so fake it. */
   1214 	if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
   1215 		if (servname && parse_numeric_servname(servname)<0)
   1216 			return EVUTIL_EAI_NONAME;
   1217 	}
   1218 #endif
   1219 
   1220 	/* Enough operating systems handle enough common non-resolve
   1221 	 * cases here weirdly enough that we are better off just
   1222 	 * overriding them.  For example:
   1223 	 *
   1224 	 * - Windows doesn't like to infer the protocol from the
   1225 	 *   socket type, or fill in socket or protocol types much at
   1226 	 *   all.  It also seems to do its own broken implicit
   1227 	 *   always-on version of AI_ADDRCONFIG that keeps it from
   1228 	 *   ever resolving even a literal IPv6 address when
   1229 	 *   ai_addrtype is PF_UNSPEC.
   1230 	 */
   1231 #ifdef WIN32
   1232 	{
   1233 		int tmp_port;
   1234 		err = evutil_getaddrinfo_common(nodename,servname,&hints,
   1235 		    res, &tmp_port);
   1236 		if (err == 0 ||
   1237 		    err == EVUTIL_EAI_MEMORY ||
   1238 		    err == EVUTIL_EAI_NONAME)
   1239 			return err;
   1240 		/* If we make it here, the system getaddrinfo can
   1241 		 * have a crack at it. */
   1242 	}
   1243 #endif
   1244 
   1245 	/* See documentation for need_numeric_port_hack above.*/
   1246 	need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
   1247 	    && ((portnum=parse_numeric_servname(servname)) >= 0);
   1248 	if (need_np_hack) {
   1249 		if (!nodename)
   1250 			return evutil_getaddrinfo_common(
   1251 				NULL,servname,&hints, res, &portnum);
   1252 		servname = NULL;
   1253 	}
   1254 
   1255 	if (need_socktype_protocol_hack()) {
   1256 		evutil_getaddrinfo_infer_protocols(&hints);
   1257 	}
   1258 
   1259 	/* Make sure that we didn't actually steal any AI_FLAGS values that
   1260 	 * the system is using.  (This is a constant expression, and should ge
   1261 	 * optimized out.)
   1262 	 *
   1263 	 * XXXX Turn this into a compile-time failure rather than a run-time
   1264 	 * failure.
   1265 	 */
   1266 	EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
   1267 
   1268 	/* Clear any flags that only libevent understands. */
   1269 	hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
   1270 
   1271 	err = getaddrinfo(nodename, servname, &hints, res);
   1272 	if (need_np_hack)
   1273 		apply_numeric_port_hack(portnum, res);
   1274 
   1275 	if (need_socktype_protocol_hack()) {
   1276 		if (apply_socktype_protocol_hack(*res) < 0) {
   1277 			evutil_freeaddrinfo(*res);
   1278 			*res = NULL;
   1279 			return EVUTIL_EAI_MEMORY;
   1280 		}
   1281 	}
   1282 	return err;
   1283 #else
   1284 	int port=0, err;
   1285 	struct hostent *ent = NULL;
   1286 	struct evutil_addrinfo hints;
   1287 
   1288 	if (hints_in) {
   1289 		memcpy(&hints, hints_in, sizeof(hints));
   1290 	} else {
   1291 		memset(&hints, 0, sizeof(hints));
   1292 		hints.ai_family = PF_UNSPEC;
   1293 	}
   1294 
   1295 	evutil_adjust_hints_for_addrconfig(&hints);
   1296 
   1297 	err = evutil_getaddrinfo_common(nodename, servname, &hints, res, &port);
   1298 	if (err != EVUTIL_EAI_NEED_RESOLVE) {
   1299 		/* We either succeeded or failed.  No need to continue */
   1300 		return err;
   1301 	}
   1302 
   1303 	err = 0;
   1304 	/* Use any of the various gethostbyname_r variants as available. */
   1305 	{
   1306 #ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
   1307 		/* This one is what glibc provides. */
   1308 		char buf[2048];
   1309 		struct hostent hostent;
   1310 		int r;
   1311 		r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
   1312 		    &err);
   1313 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
   1314 		char buf[2048];
   1315 		struct hostent hostent;
   1316 		ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
   1317 		    &err);
   1318 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_3_ARG)
   1319 		struct hostent_data data;
   1320 		struct hostent hostent;
   1321 		memset(&data, 0, sizeof(data));
   1322 		err = gethostbyname_r(nodename, &hostent, &data);
   1323 		ent = err ? NULL : &hostent;
   1324 #else
   1325 		/* fall back to gethostbyname. */
   1326 		/* XXXX This needs a lock everywhere but Windows. */
   1327 		ent = gethostbyname(nodename);
   1328 #ifdef WIN32
   1329 		err = WSAGetLastError();
   1330 #else
   1331 		err = h_errno;
   1332 #endif
   1333 #endif
   1334 
   1335 		/* Now we have either ent or err set. */
   1336 		if (!ent) {
   1337 			/* XXX is this right for windows ? */
   1338 			switch (err) {
   1339 			case TRY_AGAIN:
   1340 				return EVUTIL_EAI_AGAIN;
   1341 			case NO_RECOVERY:
   1342 			default:
   1343 				return EVUTIL_EAI_FAIL;
   1344 			case HOST_NOT_FOUND:
   1345 				return EVUTIL_EAI_NONAME;
   1346 			case NO_ADDRESS:
   1347 #if NO_DATA != NO_ADDRESS
   1348 			case NO_DATA:
   1349 #endif
   1350 				return EVUTIL_EAI_NODATA;
   1351 			}
   1352 		}
   1353 
   1354 		if (ent->h_addrtype != hints.ai_family &&
   1355 		    hints.ai_family != PF_UNSPEC) {
   1356 			/* This wasn't the type we were hoping for.  Too bad
   1357 			 * we never had a chance to ask gethostbyname for what
   1358 			 * we wanted. */
   1359 			return EVUTIL_EAI_NONAME;
   1360 		}
   1361 
   1362 		/* Make sure we got _some_ answers. */
   1363 		if (ent->h_length == 0)
   1364 			return EVUTIL_EAI_NODATA;
   1365 
   1366 		/* If we got an address type we don't know how to make a
   1367 		   sockaddr for, give up. */
   1368 		if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
   1369 			return EVUTIL_EAI_FAMILY;
   1370 
   1371 		*res = addrinfo_from_hostent(ent, port, &hints);
   1372 		if (! *res)
   1373 			return EVUTIL_EAI_MEMORY;
   1374 	}
   1375 
   1376 	return 0;
   1377 #endif
   1378 }
   1379 
   1380 void
   1381 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
   1382 {
   1383 #ifdef _EVENT_HAVE_GETADDRINFO
   1384 	if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
   1385 		freeaddrinfo(ai);
   1386 		return;
   1387 	}
   1388 #endif
   1389 	while (ai) {
   1390 		struct evutil_addrinfo *next = ai->ai_next;
   1391 		if (ai->ai_canonname)
   1392 			mm_free(ai->ai_canonname);
   1393 		mm_free(ai);
   1394 		ai = next;
   1395 	}
   1396 }
   1397 
   1398 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
   1399 
   1400 void
   1401 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
   1402 {
   1403 	if (!evdns_getaddrinfo_impl)
   1404 		evdns_getaddrinfo_impl = fn;
   1405 }
   1406 
   1407 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
   1408  * otherwise do a blocking resolve and pass the result to the callback in the
   1409  * way that evdns_getaddrinfo would.
   1410  */
   1411 int
   1412 evutil_getaddrinfo_async(struct evdns_base *dns_base,
   1413     const char *nodename, const char *servname,
   1414     const struct evutil_addrinfo *hints_in,
   1415     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
   1416 {
   1417 	if (dns_base && evdns_getaddrinfo_impl) {
   1418 		evdns_getaddrinfo_impl(
   1419 			dns_base, nodename, servname, hints_in, cb, arg);
   1420 	} else {
   1421 		struct evutil_addrinfo *ai=NULL;
   1422 		int err;
   1423 		err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
   1424 		cb(err, ai, arg);
   1425 	}
   1426 	return 0;
   1427 }
   1428 
   1429 const char *
   1430 evutil_gai_strerror(int err)
   1431 {
   1432 	/* As a sneaky side-benefit, this case statement will get most
   1433 	 * compilers to tell us if any of the error codes we defined
   1434 	 * conflict with the platform's native error codes. */
   1435 	switch (err) {
   1436 	case EVUTIL_EAI_CANCEL:
   1437 		return "Request canceled";
   1438 	case 0:
   1439 		return "No error";
   1440 
   1441 	case EVUTIL_EAI_ADDRFAMILY:
   1442 		return "address family for nodename not supported";
   1443 	case EVUTIL_EAI_AGAIN:
   1444 		return "temporary failure in name resolution";
   1445 	case EVUTIL_EAI_BADFLAGS:
   1446 		return "invalid value for ai_flags";
   1447 	case EVUTIL_EAI_FAIL:
   1448 		return "non-recoverable failure in name resolution";
   1449 	case EVUTIL_EAI_FAMILY:
   1450 		return "ai_family not supported";
   1451 	case EVUTIL_EAI_MEMORY:
   1452 		return "memory allocation failure";
   1453 	case EVUTIL_EAI_NODATA:
   1454 		return "no address associated with nodename";
   1455 	case EVUTIL_EAI_NONAME:
   1456 		return "nodename nor servname provided, or not known";
   1457 	case EVUTIL_EAI_SERVICE:
   1458 		return "servname not supported for ai_socktype";
   1459 	case EVUTIL_EAI_SOCKTYPE:
   1460 		return "ai_socktype not supported";
   1461 	case EVUTIL_EAI_SYSTEM:
   1462 		return "system error";
   1463 	default:
   1464 #if defined(USE_NATIVE_GETADDRINFO) && defined(WIN32)
   1465 		return gai_strerrorA(err);
   1466 #elif defined(USE_NATIVE_GETADDRINFO)
   1467 		return gai_strerror(err);
   1468 #else
   1469 		return "Unknown error code";
   1470 #endif
   1471 	}
   1472 }
   1473 
   1474 #ifdef WIN32
   1475 #define E(code, s) { code, (s " [" #code " ]") }
   1476 static struct { int code; const char *msg; } windows_socket_errors[] = {
   1477   E(WSAEINTR, "Interrupted function call"),
   1478   E(WSAEACCES, "Permission denied"),
   1479   E(WSAEFAULT, "Bad address"),
   1480   E(WSAEINVAL, "Invalid argument"),
   1481   E(WSAEMFILE, "Too many open files"),
   1482   E(WSAEWOULDBLOCK,  "Resource temporarily unavailable"),
   1483   E(WSAEINPROGRESS, "Operation now in progress"),
   1484   E(WSAEALREADY, "Operation already in progress"),
   1485   E(WSAENOTSOCK, "Socket operation on nonsocket"),
   1486   E(WSAEDESTADDRREQ, "Destination address required"),
   1487   E(WSAEMSGSIZE, "Message too long"),
   1488   E(WSAEPROTOTYPE, "Protocol wrong for socket"),
   1489   E(WSAENOPROTOOPT, "Bad protocol option"),
   1490   E(WSAEPROTONOSUPPORT, "Protocol not supported"),
   1491   E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
   1492   /* What's the difference between NOTSUPP and NOSUPPORT? :) */
   1493   E(WSAEOPNOTSUPP, "Operation not supported"),
   1494   E(WSAEPFNOSUPPORT,  "Protocol family not supported"),
   1495   E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
   1496   E(WSAEADDRINUSE, "Address already in use"),
   1497   E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
   1498   E(WSAENETDOWN, "Network is down"),
   1499   E(WSAENETUNREACH, "Network is unreachable"),
   1500   E(WSAENETRESET, "Network dropped connection on reset"),
   1501   E(WSAECONNABORTED, "Software caused connection abort"),
   1502   E(WSAECONNRESET, "Connection reset by peer"),
   1503   E(WSAENOBUFS, "No buffer space available"),
   1504   E(WSAEISCONN, "Socket is already connected"),
   1505   E(WSAENOTCONN, "Socket is not connected"),
   1506   E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
   1507   E(WSAETIMEDOUT, "Connection timed out"),
   1508   E(WSAECONNREFUSED, "Connection refused"),
   1509   E(WSAEHOSTDOWN, "Host is down"),
   1510   E(WSAEHOSTUNREACH, "No route to host"),
   1511   E(WSAEPROCLIM, "Too many processes"),
   1512 
   1513   /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
   1514   E(WSASYSNOTREADY, "Network subsystem is unavailable"),
   1515   E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
   1516   E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
   1517   E(WSAEDISCON, "Graceful shutdown now in progress"),
   1518 #ifdef WSATYPE_NOT_FOUND
   1519   E(WSATYPE_NOT_FOUND, "Class type not found"),
   1520 #endif
   1521   E(WSAHOST_NOT_FOUND, "Host not found"),
   1522   E(WSATRY_AGAIN, "Nonauthoritative host not found"),
   1523   E(WSANO_RECOVERY, "This is a nonrecoverable error"),
   1524   E(WSANO_DATA, "Valid name, no data record of requested type)"),
   1525 
   1526   /* There are some more error codes whose numeric values are marked
   1527    * <b>OS dependent</b>. They start with WSA_, apparently for the same
   1528    * reason that practitioners of some craft traditions deliberately
   1529    * introduce imperfections into their baskets and rugs "to allow the
   1530    * evil spirits to escape."  If we catch them, then our binaries
   1531    * might not report consistent results across versions of Windows.
   1532    * Thus, I'm going to let them all fall through.
   1533    */
   1534   { -1, NULL },
   1535 };
   1536 #undef E
   1537 /** Equivalent to strerror, but for windows socket errors. */
   1538 const char *
   1539 evutil_socket_error_to_string(int errcode)
   1540 {
   1541   /* XXXX Is there really no built-in function to do this? */
   1542   int i;
   1543   for (i=0; windows_socket_errors[i].code >= 0; ++i) {
   1544     if (errcode == windows_socket_errors[i].code)
   1545       return windows_socket_errors[i].msg;
   1546   }
   1547   return strerror(errcode);
   1548 }
   1549 #endif
   1550 
   1551 int
   1552 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
   1553 {
   1554 	int r;
   1555 	va_list ap;
   1556 	va_start(ap, format);
   1557 	r = evutil_vsnprintf(buf, buflen, format, ap);
   1558 	va_end(ap);
   1559 	return r;
   1560 }
   1561 
   1562 int
   1563 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
   1564 {
   1565 	int r;
   1566 	if (!buflen)
   1567 		return 0;
   1568 #if defined(_MSC_VER) || defined(WIN32)
   1569 	r = _vsnprintf(buf, buflen, format, ap);
   1570 	if (r < 0)
   1571 		r = _vscprintf(format, ap);
   1572 #elif defined(sgi)
   1573 	/* Make sure we always use the correct vsnprintf on IRIX */
   1574 	extern int      _xpg5_vsnprintf(char * __restrict,
   1575 		__SGI_LIBC_NAMESPACE_QUALIFIER size_t,
   1576 		const char * __restrict, /* va_list */ char *);
   1577 
   1578 	r = _xpg5_vsnprintf(buf, buflen, format, ap);
   1579 #else
   1580 	r = vsnprintf(buf, buflen, format, ap);
   1581 #endif
   1582 	buf[buflen-1] = '\0';
   1583 	return r;
   1584 }
   1585 
   1586 #define USE_INTERNAL_NTOP
   1587 #define USE_INTERNAL_PTON
   1588 
   1589 const char *
   1590 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
   1591 {
   1592 #if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
   1593 	return inet_ntop(af, src, dst, len);
   1594 #else
   1595 	if (af == AF_INET) {
   1596 		const struct in_addr *in = src;
   1597 		const ev_uint32_t a = ntohl(in->s_addr);
   1598 		int r;
   1599 		r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
   1600 		    (int)(ev_uint8_t)((a>>24)&0xff),
   1601 		    (int)(ev_uint8_t)((a>>16)&0xff),
   1602 		    (int)(ev_uint8_t)((a>>8 )&0xff),
   1603 		    (int)(ev_uint8_t)((a    )&0xff));
   1604 		if (r<0||(size_t)r>=len)
   1605 			return NULL;
   1606 		else
   1607 			return dst;
   1608 #ifdef AF_INET6
   1609 	} else if (af == AF_INET6) {
   1610 		const struct in6_addr *addr = src;
   1611 		char buf[64], *cp;
   1612 		int longestGapLen = 0, longestGapPos = -1, i,
   1613 			curGapPos = -1, curGapLen = 0;
   1614 		ev_uint16_t words[8];
   1615 		for (i = 0; i < 8; ++i) {
   1616 			words[i] =
   1617 			    (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
   1618 		}
   1619 		if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
   1620 		    words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
   1621 			(words[5] == 0xffff))) {
   1622 			/* This is an IPv4 address. */
   1623 			if (words[5] == 0) {
   1624 				evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
   1625 				    addr->s6_addr[12], addr->s6_addr[13],
   1626 				    addr->s6_addr[14], addr->s6_addr[15]);
   1627 			} else {
   1628 				evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
   1629 				    addr->s6_addr[12], addr->s6_addr[13],
   1630 				    addr->s6_addr[14], addr->s6_addr[15]);
   1631 			}
   1632 			if (strlen(buf) > len)
   1633 				return NULL;
   1634 			strlcpy(dst, buf, len);
   1635 			return dst;
   1636 		}
   1637 		i = 0;
   1638 		while (i < 8) {
   1639 			if (words[i] == 0) {
   1640 				curGapPos = i++;
   1641 				curGapLen = 1;
   1642 				while (i<8 && words[i] == 0) {
   1643 					++i; ++curGapLen;
   1644 				}
   1645 				if (curGapLen > longestGapLen) {
   1646 					longestGapPos = curGapPos;
   1647 					longestGapLen = curGapLen;
   1648 				}
   1649 			} else {
   1650 				++i;
   1651 			}
   1652 		}
   1653 		if (longestGapLen<=1)
   1654 			longestGapPos = -1;
   1655 
   1656 		cp = buf;
   1657 		for (i = 0; i < 8; ++i) {
   1658 			if (words[i] == 0 && longestGapPos == i) {
   1659 				if (i == 0)
   1660 					*cp++ = ':';
   1661 				*cp++ = ':';
   1662 				while (i < 8 && words[i] == 0)
   1663 					++i;
   1664 				--i; /* to compensate for loop increment. */
   1665 			} else {
   1666 				evutil_snprintf(cp,
   1667 								sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
   1668 				cp += strlen(cp);
   1669 				if (i != 7)
   1670 					*cp++ = ':';
   1671 			}
   1672 		}
   1673 		*cp = '\0';
   1674 		if (strlen(buf) > len)
   1675 			return NULL;
   1676 		strlcpy(dst, buf, len);
   1677 		return dst;
   1678 #endif
   1679 	} else {
   1680 		return NULL;
   1681 	}
   1682 #endif
   1683 }
   1684 
   1685 int
   1686 evutil_inet_pton(int af, const char *src, void *dst)
   1687 {
   1688 #if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
   1689 	return inet_pton(af, src, dst);
   1690 #else
   1691 	if (af == AF_INET) {
   1692 		int a,b,c,d;
   1693 		char more;
   1694 		struct in_addr *addr = dst;
   1695 		if (sscanf(src, "%d.%d.%d.%d%c", &a,&b,&c,&d,&more) != 4)
   1696 			return 0;
   1697 		if (a < 0 || a > 255) return 0;
   1698 		if (b < 0 || b > 255) return 0;
   1699 		if (c < 0 || c > 255) return 0;
   1700 		if (d < 0 || d > 255) return 0;
   1701 		addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
   1702 		return 1;
   1703 #ifdef AF_INET6
   1704 	} else if (af == AF_INET6) {
   1705 		struct in6_addr *out = dst;
   1706 		ev_uint16_t words[8];
   1707 		int gapPos = -1, i, setWords=0;
   1708 		const char *dot = strchr(src, '.');
   1709 		const char *eow; /* end of words. */
   1710 		if (dot == src)
   1711 			return 0;
   1712 		else if (!dot)
   1713 			eow = src+strlen(src);
   1714 		else {
   1715 			int byte1,byte2,byte3,byte4;
   1716 			char more;
   1717 			for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT(*eow); --eow)
   1718 				;
   1719 			++eow;
   1720 
   1721 			/* We use "scanf" because some platform inet_aton()s are too lax
   1722 			 * about IPv4 addresses of the form "1.2.3" */
   1723 			if (sscanf(eow, "%d.%d.%d.%d%c",
   1724 					   &byte1,&byte2,&byte3,&byte4,&more) != 4)
   1725 				return 0;
   1726 
   1727 			if (byte1 > 255 || byte1 < 0 ||
   1728 				byte2 > 255 || byte2 < 0 ||
   1729 				byte3 > 255 || byte3 < 0 ||
   1730 				byte4 > 255 || byte4 < 0)
   1731 				return 0;
   1732 
   1733 			words[6] = (byte1<<8) | byte2;
   1734 			words[7] = (byte3<<8) | byte4;
   1735 			setWords += 2;
   1736 		}
   1737 
   1738 		i = 0;
   1739 		while (src < eow) {
   1740 			if (i > 7)
   1741 				return 0;
   1742 			if (EVUTIL_ISXDIGIT(*src)) {
   1743 				char *next;
   1744 				long r = strtol(src, &next, 16);
   1745 				if (next > 4+src)
   1746 					return 0;
   1747 				if (next == src)
   1748 					return 0;
   1749 				if (r<0 || r>65536)
   1750 					return 0;
   1751 
   1752 				words[i++] = (ev_uint16_t)r;
   1753 				setWords++;
   1754 				src = next;
   1755 				if (*src != ':' && src != eow)
   1756 					return 0;
   1757 				++src;
   1758 			} else if (*src == ':' && i > 0 && gapPos==-1) {
   1759 				gapPos = i;
   1760 				++src;
   1761 			} else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
   1762 				gapPos = i;
   1763 				src += 2;
   1764 			} else {
   1765 				return 0;
   1766 			}
   1767 		}
   1768 
   1769 		if (setWords > 8 ||
   1770 			(setWords == 8 && gapPos != -1) ||
   1771 			(setWords < 8 && gapPos == -1))
   1772 			return 0;
   1773 
   1774 		if (gapPos >= 0) {
   1775 			int nToMove = setWords - (dot ? 2 : 0) - gapPos;
   1776 			int gapLen = 8 - setWords;
   1777 			/* assert(nToMove >= 0); */
   1778 			if (nToMove < 0)
   1779 				return -1; /* should be impossible */
   1780 			memmove(&words[gapPos+gapLen], &words[gapPos],
   1781 					sizeof(ev_uint16_t)*nToMove);
   1782 			memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
   1783 		}
   1784 		for (i = 0; i < 8; ++i) {
   1785 			out->s6_addr[2*i  ] = words[i] >> 8;
   1786 			out->s6_addr[2*i+1] = words[i] & 0xff;
   1787 		}
   1788 
   1789 		return 1;
   1790 #endif
   1791 	} else {
   1792 		return -1;
   1793 	}
   1794 #endif
   1795 }
   1796 
   1797 int
   1798 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
   1799 {
   1800 	int port;
   1801 	char buf[128];
   1802 	const char *cp, *addr_part, *port_part;
   1803 	int is_ipv6;
   1804 	/* recognized formats are:
   1805 	 * [ipv6]:port
   1806 	 * ipv6
   1807 	 * [ipv6]
   1808 	 * ipv4:port
   1809 	 * ipv4
   1810 	 */
   1811 
   1812 	cp = strchr(ip_as_string, ':');
   1813 	if (*ip_as_string == '[') {
   1814 		int len;
   1815 		if (!(cp = strchr(ip_as_string, ']'))) {
   1816 			return -1;
   1817 		}
   1818 		len = (int) ( cp-(ip_as_string + 1) );
   1819 		if (len > (int)sizeof(buf)-1) {
   1820 			return -1;
   1821 		}
   1822 		memcpy(buf, ip_as_string+1, len);
   1823 		buf[len] = '\0';
   1824 		addr_part = buf;
   1825 		if (cp[1] == ':')
   1826 			port_part = cp+2;
   1827 		else
   1828 			port_part = NULL;
   1829 		is_ipv6 = 1;
   1830 	} else if (cp && strchr(cp+1, ':')) {
   1831 		is_ipv6 = 1;
   1832 		addr_part = ip_as_string;
   1833 		port_part = NULL;
   1834 	} else if (cp) {
   1835 		is_ipv6 = 0;
   1836 		if (cp - ip_as_string > (int)sizeof(buf)-1) {
   1837 			return -1;
   1838 		}
   1839 		memcpy(buf, ip_as_string, cp-ip_as_string);
   1840 		buf[cp-ip_as_string] = '\0';
   1841 		addr_part = buf;
   1842 		port_part = cp+1;
   1843 	} else {
   1844 		addr_part = ip_as_string;
   1845 		port_part = NULL;
   1846 		is_ipv6 = 0;
   1847 	}
   1848 
   1849 	if (port_part == NULL) {
   1850 		port = 0;
   1851 	} else {
   1852 		port = atoi(port_part);
   1853 		if (port <= 0 || port > 65535) {
   1854 			return -1;
   1855 		}
   1856 	}
   1857 
   1858 	if (!addr_part)
   1859 		return -1; /* Should be impossible. */
   1860 #ifdef AF_INET6
   1861 	if (is_ipv6)
   1862 	{
   1863 		struct sockaddr_in6 sin6;
   1864 		memset(&sin6, 0, sizeof(sin6));
   1865 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
   1866 		sin6.sin6_len = sizeof(sin6);
   1867 #endif
   1868 		sin6.sin6_family = AF_INET6;
   1869 		sin6.sin6_port = htons(port);
   1870 		if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
   1871 			return -1;
   1872 		if ((int)sizeof(sin6) > *outlen)
   1873 			return -1;
   1874 		memset(out, 0, *outlen);
   1875 		memcpy(out, &sin6, sizeof(sin6));
   1876 		*outlen = sizeof(sin6);
   1877 		return 0;
   1878 	}
   1879 	else
   1880 #endif
   1881 	{
   1882 		struct sockaddr_in sin;
   1883 		memset(&sin, 0, sizeof(sin));
   1884 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
   1885 		sin.sin_len = sizeof(sin);
   1886 #endif
   1887 		sin.sin_family = AF_INET;
   1888 		sin.sin_port = htons(port);
   1889 		if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
   1890 			return -1;
   1891 		if ((int)sizeof(sin) > *outlen)
   1892 			return -1;
   1893 		memset(out, 0, *outlen);
   1894 		memcpy(out, &sin, sizeof(sin));
   1895 		*outlen = sizeof(sin);
   1896 		return 0;
   1897 	}
   1898 }
   1899 
   1900 const char *
   1901 evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen)
   1902 {
   1903 	char b[128];
   1904 	const char *res=NULL;
   1905 	int port;
   1906 	if (sa->sa_family == AF_INET) {
   1907 		const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
   1908 		res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
   1909 		port = ntohs(sin->sin_port);
   1910 		if (res) {
   1911 			evutil_snprintf(out, outlen, "%s:%d", b, port);
   1912 			return out;
   1913 		}
   1914 	} else if (sa->sa_family == AF_INET6) {
   1915 		const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
   1916 		res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
   1917 		port = ntohs(sin6->sin6_port);
   1918 		if (res) {
   1919 			evutil_snprintf(out, outlen, "[%s]:%d", b, port);
   1920 			return out;
   1921 		}
   1922 	}
   1923 
   1924 	evutil_snprintf(out, outlen, "<addr with socktype %d>",
   1925 	    (int)sa->sa_family);
   1926 	return out;
   1927 }
   1928 
   1929 int
   1930 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
   1931     int include_port)
   1932 {
   1933 	int r;
   1934 	if (0 != (r = (sa1->sa_family - sa2->sa_family)))
   1935 		return r;
   1936 
   1937 	if (sa1->sa_family == AF_INET) {
   1938 		const struct sockaddr_in *sin1, *sin2;
   1939 		sin1 = (const struct sockaddr_in *)sa1;
   1940 		sin2 = (const struct sockaddr_in *)sa2;
   1941 		if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
   1942 			return -1;
   1943 		else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
   1944 			return 1;
   1945 		else if (include_port &&
   1946 		    (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
   1947 			return r;
   1948 		else
   1949 			return 0;
   1950 	}
   1951 #ifdef AF_INET6
   1952 	else if (sa1->sa_family == AF_INET6) {
   1953 		const struct sockaddr_in6 *sin1, *sin2;
   1954 		sin1 = (const struct sockaddr_in6 *)sa1;
   1955 		sin2 = (const struct sockaddr_in6 *)sa2;
   1956 		if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
   1957 			return r;
   1958 		else if (include_port &&
   1959 		    (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
   1960 			return r;
   1961 		else
   1962 			return 0;
   1963 	}
   1964 #endif
   1965 	return 1;
   1966 }
   1967 
   1968 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions.  Each table
   1969  * has 256 bits to look up whether a character is in some set or not.  This
   1970  * fails on non-ASCII platforms, but so does every other place where we
   1971  * take a char and write it onto the network.
   1972  **/
   1973 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
   1974   { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
   1975 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
   1976   { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
   1977 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
   1978 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
   1979   { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
   1980 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
   1981 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
   1982   { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
   1983 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
   1984 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
   1985 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
   1986  * equivalents. */
   1987 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
   1988   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
   1989   16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
   1990   32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
   1991   48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
   1992   64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
   1993   80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
   1994   96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
   1995   80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
   1996   128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   1997   144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
   1998   160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
   1999   176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
   2000   192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
   2001   208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
   2002   224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
   2003   240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
   2004 };
   2005 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
   2006   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
   2007   16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
   2008   32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
   2009   48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
   2010   64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
   2011   112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
   2012   96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
   2013   112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
   2014   128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   2015   144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
   2016   160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
   2017   176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
   2018   192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
   2019   208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
   2020   224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
   2021   240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
   2022 };
   2023 
   2024 #define IMPL_CTYPE_FN(name)						\
   2025 	int EVUTIL_##name(char c) {					\
   2026 		ev_uint8_t u = c;					\
   2027 		return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
   2028 	}
   2029 IMPL_CTYPE_FN(ISALPHA)
   2030 IMPL_CTYPE_FN(ISALNUM)
   2031 IMPL_CTYPE_FN(ISSPACE)
   2032 IMPL_CTYPE_FN(ISDIGIT)
   2033 IMPL_CTYPE_FN(ISXDIGIT)
   2034 IMPL_CTYPE_FN(ISPRINT)
   2035 IMPL_CTYPE_FN(ISLOWER)
   2036 IMPL_CTYPE_FN(ISUPPER)
   2037 
   2038 char EVUTIL_TOLOWER(char c)
   2039 {
   2040 	return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
   2041 }
   2042 char EVUTIL_TOUPPER(char c)
   2043 {
   2044 	return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
   2045 }
   2046 int
   2047 evutil_ascii_strcasecmp(const char *s1, const char *s2)
   2048 {
   2049 	char c1, c2;
   2050 	while (1) {
   2051 		c1 = EVUTIL_TOLOWER(*s1++);
   2052 		c2 = EVUTIL_TOLOWER(*s2++);
   2053 		if (c1 < c2)
   2054 			return -1;
   2055 		else if (c1 > c2)
   2056 			return 1;
   2057 		else if (c1 == 0)
   2058 			return 0;
   2059 	}
   2060 }
   2061 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
   2062 {
   2063 	char c1, c2;
   2064 	while (n--) {
   2065 		c1 = EVUTIL_TOLOWER(*s1++);
   2066 		c2 = EVUTIL_TOLOWER(*s2++);
   2067 		if (c1 < c2)
   2068 			return -1;
   2069 		else if (c1 > c2)
   2070 			return 1;
   2071 		else if (c1 == 0)
   2072 			return 0;
   2073 	}
   2074 	return 0;
   2075 }
   2076 
   2077 static int
   2078 evutil_issetugid(void)
   2079 {
   2080 #ifdef _EVENT_HAVE_ISSETUGID
   2081 	return issetugid();
   2082 #else
   2083 
   2084 #ifdef _EVENT_HAVE_GETEUID
   2085 	if (getuid() != geteuid())
   2086 		return 1;
   2087 #endif
   2088 #ifdef _EVENT_HAVE_GETEGID
   2089 	if (getgid() != getegid())
   2090 		return 1;
   2091 #endif
   2092 	return 0;
   2093 #endif
   2094 }
   2095 
   2096 const char *
   2097 evutil_getenv(const char *varname)
   2098 {
   2099 	if (evutil_issetugid())
   2100 		return NULL;
   2101 
   2102 	return getenv(varname);
   2103 }
   2104 
   2105 long
   2106 _evutil_weakrand(void)
   2107 {
   2108 #ifdef WIN32
   2109 	return rand();
   2110 #else
   2111 	return random();
   2112 #endif
   2113 }
   2114 
   2115 /**
   2116  * Volatile pointer to memset: we use this to keep the compiler from
   2117  * eliminating our call to memset.
   2118  */
   2119 void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
   2120 
   2121 void
   2122 evutil_memclear_(void *mem, size_t len)
   2123 {
   2124 	evutil_memset_volatile_(mem, 0, len);
   2125 }
   2126 
   2127 int
   2128 evutil_sockaddr_is_loopback(const struct sockaddr *addr)
   2129 {
   2130 	static const char LOOPBACK_S6[16] =
   2131 	    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
   2132 	if (addr->sa_family == AF_INET) {
   2133 		const struct sockaddr_in *sin = (const struct sockaddr_in *)addr;
   2134 		return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
   2135 	} else if (addr->sa_family == AF_INET6) {
   2136 		const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)addr;
   2137 		return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
   2138 	}
   2139 	return 0;
   2140 }
   2141 
   2142 #define MAX_SECONDS_IN_MSEC_LONG \
   2143 	(((LONG_MAX) - 999) / 1000)
   2144 
   2145 long
   2146 evutil_tv_to_msec(const struct timeval *tv)
   2147 {
   2148 	if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
   2149 		return -1;
   2150 
   2151 	return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
   2152 }
   2153 
   2154 int
   2155 evutil_hex_char_to_int(char c)
   2156 {
   2157 	switch(c)
   2158 	{
   2159 		case '0': return 0;
   2160 		case '1': return 1;
   2161 		case '2': return 2;
   2162 		case '3': return 3;
   2163 		case '4': return 4;
   2164 		case '5': return 5;
   2165 		case '6': return 6;
   2166 		case '7': return 7;
   2167 		case '8': return 8;
   2168 		case '9': return 9;
   2169 		case 'A': case 'a': return 10;
   2170 		case 'B': case 'b': return 11;
   2171 		case 'C': case 'c': return 12;
   2172 		case 'D': case 'd': return 13;
   2173 		case 'E': case 'e': return 14;
   2174 		case 'F': case 'f': return 15;
   2175 	}
   2176 	return -1;
   2177 }
   2178 
   2179 #ifdef WIN32
   2180 HANDLE
   2181 evutil_load_windows_system_library(const TCHAR *library_name)
   2182 {
   2183   TCHAR path[MAX_PATH];
   2184   unsigned n;
   2185   n = GetSystemDirectory(path, MAX_PATH);
   2186   if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
   2187     return 0;
   2188   _tcscat(path, TEXT("\\"));
   2189   _tcscat(path, library_name);
   2190   return LoadLibrary(path);
   2191 }
   2192 #endif
   2193 
   2194