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