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