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