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