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