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