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