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