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