]> arthur.barton.de Git - netatalk.git/blob - libevent/evutil.c
Update libevent to 2.0.12
[netatalk.git] / libevent / evutil.c
1 /*
2  * Copyright (c) 2007-2010 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
29 #define _GNU_SOURCE
30
31 #ifdef WIN32
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 #define WIN32_LEAN_AND_MEAN
35 #include <windows.h>
36 #undef WIN32_LEAN_AND_MEAN
37 #include <io.h>
38 #include <tchar.h>
39 #endif
40
41 #include <sys/types.h>
42 #ifdef _EVENT_HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45 #ifdef _EVENT_HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #ifdef _EVENT_HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef _EVENT_HAVE_STDLIB_H
52 #include <stdlib.h>
53 #endif
54 #include <errno.h>
55 #include <limits.h>
56 #include <stdio.h>
57 #include <string.h>
58 #ifdef _EVENT_HAVE_ARPA_INET_H
59 #include <arpa/inet.h>
60 #endif
61 #ifdef _EVENT_HAVE_NETINET_IN_H
62 #include <netinet/in.h>
63 #endif
64 #ifdef _EVENT_HAVE_NETINET_IN6_H
65 #include <netinet/in6.h>
66 #endif
67
68 #ifndef _EVENT_HAVE_GETTIMEOFDAY
69 #include <sys/timeb.h>
70 #include <time.h>
71 #endif
72 #include <sys/stat.h>
73
74 #include "event2/util.h"
75 #include "util-internal.h"
76 #include "log-internal.h"
77 #include "mm-internal.h"
78
79 #include "strlcpy-internal.h"
80 #include "ipv6-internal.h"
81
82 #ifdef WIN32
83 #define open _open
84 #define read _read
85 #define close _close
86 #define fstat _fstati64
87 #define stat _stati64
88 #endif
89
90 /**
91    Read the contents of 'filename' into a newly allocated NUL-terminated
92    string.  Set *content_out to hold this string, and *len_out to hold its
93    length (not including the appended NUL).  If 'is_binary', open the file in
94    binary mode.
95
96    Returns 0 on success, -1 if the open fails, and -2 for all other failures.
97
98    Used internally only; may go away in a future version.
99  */
100 int
101 evutil_read_file(const char *filename, char **content_out, size_t *len_out,
102     int is_binary)
103 {
104         int fd, r;
105         struct stat st;
106         char *mem;
107         size_t read_so_far=0;
108         int mode = O_RDONLY;
109
110         EVUTIL_ASSERT(content_out);
111         EVUTIL_ASSERT(len_out);
112         *content_out = NULL;
113         *len_out = 0;
114
115 #ifdef O_BINARY
116         if (is_binary)
117                 mode |= O_BINARY;
118 #endif
119
120         fd = open(filename, mode);
121         if (fd < 0)
122                 return -1;
123         if (fstat(fd, &st) || st.st_size < 0 ||
124             st.st_size > EV_SSIZE_MAX-1 ) {
125                 close(fd);
126                 return -2;
127         }
128         mem = mm_malloc((size_t)st.st_size + 1);
129         if (!mem) {
130                 close(fd);
131                 return -2;
132         }
133         read_so_far = 0;
134 #ifdef WIN32
135 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
136 #else
137 #define N_TO_READ(x) (x)
138 #endif
139         while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
140                 read_so_far += r;
141                 if (read_so_far >= (size_t)st.st_size)
142                         break;
143                 EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
144         }
145         close(fd);
146         if (r < 0) {
147                 mm_free(mem);
148                 return -2;
149         }
150         mem[read_so_far] = 0;
151
152         *len_out = read_so_far;
153         *content_out = mem;
154         return 0;
155 }
156
157 int
158 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
159 {
160 #ifndef WIN32
161         return socketpair(family, type, protocol, fd);
162 #else
163         return evutil_ersatz_socketpair(family, type, protocol, fd);
164 #endif
165 }
166
167 int
168 evutil_ersatz_socketpair(int family, int type, int protocol,
169     evutil_socket_t fd[2])
170 {
171         /* This code is originally from Tor.  Used with permission. */
172
173         /* This socketpair does not work when localhost is down. So
174          * it's really not the same thing at all. But it's close enough
175          * for now, and really, when localhost is down sometimes, we
176          * have other problems too.
177          */
178 #ifdef WIN32
179 #define ERR(e) WSA##e
180 #else
181 #define ERR(e) e
182 #endif
183         evutil_socket_t listener = -1;
184         evutil_socket_t connector = -1;
185         evutil_socket_t acceptor = -1;
186         struct sockaddr_in listen_addr;
187         struct sockaddr_in connect_addr;
188         ev_socklen_t size;
189         int saved_errno = -1;
190
191         if (protocol
192                 || (family != AF_INET
193 #ifdef AF_UNIX
194                     && family != AF_UNIX
195 #endif
196                 )) {
197                 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
198                 return -1;
199         }
200         if (!fd) {
201                 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
202                 return -1;
203         }
204
205         listener = socket(AF_INET, type, 0);
206         if (listener < 0)
207                 return -1;
208         memset(&listen_addr, 0, sizeof(listen_addr));
209         listen_addr.sin_family = AF_INET;
210         listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
211         listen_addr.sin_port = 0;       /* kernel chooses port.  */
212         if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
213                 == -1)
214                 goto tidy_up_and_fail;
215         if (listen(listener, 1) == -1)
216                 goto tidy_up_and_fail;
217
218         connector = socket(AF_INET, type, 0);
219         if (connector < 0)
220                 goto tidy_up_and_fail;
221         /* We want to find out the port number to connect to.  */
222         size = sizeof(connect_addr);
223         if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
224                 goto tidy_up_and_fail;
225         if (size != sizeof (connect_addr))
226                 goto abort_tidy_up_and_fail;
227         if (connect(connector, (struct sockaddr *) &connect_addr,
228                                 sizeof(connect_addr)) == -1)
229                 goto tidy_up_and_fail;
230
231         size = sizeof(listen_addr);
232         acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
233         if (acceptor < 0)
234                 goto tidy_up_and_fail;
235         if (size != sizeof(listen_addr))
236                 goto abort_tidy_up_and_fail;
237         evutil_closesocket(listener);
238         /* Now check we are talking to ourself by matching port and host on the
239            two sockets.  */
240         if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
241                 goto tidy_up_and_fail;
242         if (size != sizeof (connect_addr)
243                 || listen_addr.sin_family != connect_addr.sin_family
244                 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
245                 || listen_addr.sin_port != connect_addr.sin_port)
246                 goto abort_tidy_up_and_fail;
247         fd[0] = connector;
248         fd[1] = acceptor;
249
250         return 0;
251
252  abort_tidy_up_and_fail:
253         saved_errno = ERR(ECONNABORTED);
254  tidy_up_and_fail:
255         if (saved_errno < 0)
256                 saved_errno = EVUTIL_SOCKET_ERROR();
257         if (listener != -1)
258                 evutil_closesocket(listener);
259         if (connector != -1)
260                 evutil_closesocket(connector);
261         if (acceptor != -1)
262                 evutil_closesocket(acceptor);
263
264         EVUTIL_SET_SOCKET_ERROR(saved_errno);
265         return -1;
266 #undef ERR
267 }
268
269 int
270 evutil_make_socket_nonblocking(evutil_socket_t fd)
271 {
272 #ifdef WIN32
273         {
274                 u_long nonblocking = 1;
275                 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
276                         event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
277                         return -1;
278                 }
279         }
280 #else
281         {
282                 int flags;
283                 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
284                         event_warn("fcntl(%d, F_GETFL)", fd);
285                         return -1;
286                 }
287                 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
288                         event_warn("fcntl(%d, F_SETFL)", fd);
289                         return -1;
290                 }
291         }
292 #endif
293         return 0;
294 }
295
296 int
297 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
298 {
299 #ifndef WIN32
300         int one = 1;
301         /* REUSEADDR on Unix means, "don't hang on to this address after the
302          * listener is closed."  On Windows, though, it means "don't keep other
303          * processes from binding to this address while we're using it. */
304         return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
305             (ev_socklen_t)sizeof(one));
306 #else
307         return 0;
308 #endif
309 }
310
311 int
312 evutil_make_socket_closeonexec(evutil_socket_t fd)
313 {
314 #if !defined(WIN32) && defined(_EVENT_HAVE_SETFD)
315         int flags;
316         if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
317                 event_warn("fcntl(%d, F_GETFD)", fd);
318                 return -1;
319         }
320         if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
321                 event_warn("fcntl(%d, F_SETFD)", fd);
322                 return -1;
323         }
324 #endif
325         return 0;
326 }
327
328 int
329 evutil_closesocket(evutil_socket_t sock)
330 {
331 #ifndef WIN32
332         return close(sock);
333 #else
334         return closesocket(sock);
335 #endif
336 }
337
338 ev_int64_t
339 evutil_strtoll(const char *s, char **endptr, int base)
340 {
341 #ifdef _EVENT_HAVE_STRTOLL
342         return (ev_int64_t)strtoll(s, endptr, base);
343 #elif _EVENT_SIZEOF_LONG == 8
344         return (ev_int64_t)strtol(s, endptr, base);
345 #elif defined(WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
346         /* XXXX on old versions of MS APIs, we only support base
347          * 10. */
348         ev_int64_t r;
349         if (base != 10)
350                 return 0;
351         r = (ev_int64_t) _atoi64(s);
352         while (isspace(*s))
353                 ++s;
354         if (*s == '-')
355                 ++s;
356         while (isdigit(*s))
357                 ++s;
358         if (endptr)
359                 *endptr = (char*) s;
360         return r;
361 #elif defined(WIN32)
362         return (ev_int64_t) _strtoi64(s, endptr, base);
363 #elif defined(_EVENT_SIZEOF_LONG_LONG) && _EVENT_SIZEOF_LONG_LONG == 8
364         long long r;
365         int n;
366         if (base != 10 && base != 16)
367                 return 0;
368         if (base == 10) {
369                 n = sscanf(s, "%lld", &r);
370         } else {
371                 unsigned long long ru=0;
372                 n = sscanf(s, "%llx", &ru);
373                 if (ru > EV_INT64_MAX)
374                         return 0;
375                 r = (long long) ru;
376         }
377         if (n != 1)
378                 return 0;
379         while (EVUTIL_ISSPACE(*s))
380                 ++s;
381         if (*s == '-')
382                 ++s;
383         if (base == 10) {
384                 while (EVUTIL_ISDIGIT(*s))
385                         ++s;
386         } else {
387                 while (EVUTIL_ISXDIGIT(*s))
388                         ++s;
389         }
390         if (endptr)
391                 *endptr = (char*) s;
392         return r;
393 #else
394 #error "I don't know how to parse 64-bit integers."
395 #endif
396 }
397
398 #ifndef _EVENT_HAVE_GETTIMEOFDAY
399 /* No gettimeofday; this muse be windows. */
400 int
401 evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
402 {
403         struct _timeb tb;
404
405         if (tv == NULL)
406                 return -1;
407
408         /* XXXX
409          * _ftime is not the greatest interface here; GetSystemTimeAsFileTime
410          * would give us better resolution, whereas something cobbled together
411          * with GetTickCount could maybe give us monotonic behavior.
412          *
413          * Either way, I think this value might be skewed to ignore the
414          * timezone, and just return local time.  That's not so good.
415          */
416         _ftime(&tb);
417         tv->tv_sec = (long) tb.time;
418         tv->tv_usec = ((int) tb.millitm) * 1000;
419         return 0;
420 }
421 #endif
422
423 #ifdef WIN32
424 int
425 evutil_socket_geterror(evutil_socket_t sock)
426 {
427         int optval, optvallen=sizeof(optval);
428         int err = WSAGetLastError();
429         if (err == WSAEWOULDBLOCK && sock >= 0) {
430                 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
431                                            &optvallen))
432                         return err;
433                 if (optval)
434                         return optval;
435         }
436         return err;
437 }
438 #endif
439
440 /* XXX we should use an enum here. */
441 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
442 int
443 evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
444 {
445         int made_fd = 0;
446
447         if (*fd_ptr < 0) {
448                 made_fd = 1;
449                 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
450                         goto err;
451                 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
452                         goto err;
453                 }
454         }
455
456         if (connect(*fd_ptr, sa, socklen) < 0) {
457                 int e = evutil_socket_geterror(*fd_ptr);
458                 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
459                         return 0;
460                 if (EVUTIL_ERR_CONNECT_REFUSED(e))
461                         return 2;
462                 goto err;
463         } else {
464                 return 1;
465         }
466
467 err:
468         if (made_fd) {
469                 evutil_closesocket(*fd_ptr);
470                 *fd_ptr = -1;
471         }
472         return -1;
473 }
474
475 /* Check whether a socket on which we called connect() is done
476    connecting. Return 1 for connected, 0 for not yet, -1 for error.  In the
477    error case, set the current socket errno to the error that happened during
478    the connect operation. */
479 int
480 evutil_socket_finished_connecting(evutil_socket_t fd)
481 {
482         int e;
483         ev_socklen_t elen = sizeof(e);
484
485         if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
486                 return -1;
487
488         if (e) {
489                 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
490                         return 0;
491                 EVUTIL_SET_SOCKET_ERROR(e);
492                 return -1;
493         }
494
495         return 1;
496 }
497
498 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
499      EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
500      EVUTIL_AI_ADDRCONFIG) != \
501     (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
502      EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
503      EVUTIL_AI_ADDRCONFIG)
504 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
505 #endif
506
507 /* We sometimes need to know whether we have an ipv4 address and whether we
508    have an ipv6 address. If 'have_checked_interfaces', then we've already done
509    the test.  If 'had_ipv4_address', then it turns out we had an ipv4 address.
510    If 'had_ipv6_address', then it turns out we had an ipv6 address.   These are
511    set by evutil_check_interfaces. */
512 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
513
514 /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
515  */
516 #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
517
518 /* Macro: True iff the IPv4 address 'addr', in host order, is a class D
519  * (multiclass) address.
520  */
521 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
522
523 /* Test whether we have an ipv4 interface and an ipv6 interface.  Return 0 if
524  * the test seemed successful. */
525 static int
526 evutil_check_interfaces(int force_recheck)
527 {
528         const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
529             "\x00\x00\x00\x00\x00\x00\x00\x00";
530         evutil_socket_t fd = -1;
531         struct sockaddr_in sin, sin_out;
532         struct sockaddr_in6 sin6, sin6_out;
533         ev_socklen_t sin_out_len = sizeof(sin_out);
534         ev_socklen_t sin6_out_len = sizeof(sin6_out);
535         int r;
536         char buf[128];
537         if (have_checked_interfaces && !force_recheck)
538                 return 0;
539
540         /* To check whether we have an interface open for a given protocol, we
541          * try to make a UDP 'connection' to a remote host on the internet.
542          * We don't actually use it, so the address doesn't matter, but we
543          * want to pick one that keep us from using a host- or link-local
544          * interface. */
545         memset(&sin, 0, sizeof(sin));
546         sin.sin_family = AF_INET;
547         sin.sin_port = htons(53);
548         r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
549         EVUTIL_ASSERT(r);
550
551         memset(&sin6, 0, sizeof(sin6));
552         sin6.sin6_family = AF_INET6;
553         sin6.sin6_port = htons(53);
554         r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
555         EVUTIL_ASSERT(r);
556
557         memset(&sin_out, 0, sizeof(sin_out));
558         memset(&sin6_out, 0, sizeof(sin6_out));
559
560         /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
561         if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
562             connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
563             getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
564                 /* We might have an IPv4 interface. */
565                 ev_uint32_t addr = ntohl(sin_out.sin_addr.s_addr);
566                 if (addr == 0 ||
567                     EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
568                     EVUTIL_V4ADDR_IS_CLASSD(addr)) {
569                         evutil_inet_ntop(AF_INET, &sin_out.sin_addr,
570                             buf, sizeof(buf));
571                         /* This is a reserved, ipv4compat, ipv4map, loopback,
572                          * link-local or unspecified address.  The host should
573                          * never have given it to us; it could never connect
574                          * to sin. */
575                         event_warnx("Got a strange local ipv4 address %s",buf);
576                 } else {
577                         event_debug(("Detected an IPv4 interface"));
578                         had_ipv4_address = 1;
579                 }
580         }
581         if (fd >= 0)
582                 evutil_closesocket(fd);
583
584         if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
585             connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
586             getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
587                 /* We might have an IPv6 interface. */
588                 const unsigned char *addr =
589                     (unsigned char*)sin6_out.sin6_addr.s6_addr;
590                 if (!memcmp(addr, ZEROES, 8) ||
591                     (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80)) {
592                         /* This is a reserved, ipv4compat, ipv4map, loopback,
593                          * link-local or unspecified address.  The host should
594                          * never have given it to us; it could never connect
595                          * to sin6. */
596                         evutil_inet_ntop(AF_INET6, &sin6_out.sin6_addr,
597                             buf, sizeof(buf));
598                         event_warnx("Got a strange local ipv6 address %s",buf);
599                 } else {
600                         event_debug(("Detected an IPv4 interface"));
601                         had_ipv6_address = 1;
602                 }
603         }
604
605         if (fd >= 0)
606                 evutil_closesocket(fd);
607
608         return 0;
609 }
610
611 /* Internal addrinfo flag.  This one is set when we allocate the addrinfo from
612  * inside libevent.  Otherwise, the built-in getaddrinfo() function allocated
613  * it, and we should trust what they said.
614  **/
615 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
616
617 /* Helper: construct a new addrinfo containing the socket address in
618  * 'sa', which must be a sockaddr_in or a sockaddr_in6.  Take the
619  * socktype and protocol info from hints.  If they weren't set, then
620  * allocate both a TCP and a UDP addrinfo.
621  */
622 struct evutil_addrinfo *
623 evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
624     const struct evutil_addrinfo *hints)
625 {
626         struct evutil_addrinfo *res;
627         EVUTIL_ASSERT(hints);
628
629         if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
630                 /* Indecisive user! Give them a UDP and a TCP. */
631                 struct evutil_addrinfo *r1, *r2;
632                 struct evutil_addrinfo tmp;
633                 memcpy(&tmp, hints, sizeof(tmp));
634                 tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
635                 r1 = evutil_new_addrinfo(sa, socklen, &tmp);
636                 if (!r1)
637                         return NULL;
638                 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
639                 r2 = evutil_new_addrinfo(sa, socklen, &tmp);
640                 if (!r2) {
641                         evutil_freeaddrinfo(r1);
642                         return NULL;
643                 }
644                 r1->ai_next = r2;
645                 return r1;
646         }
647
648         /* We're going to allocate extra space to hold the sockaddr. */
649         res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
650         if (!res)
651                 return NULL;
652         res->ai_addr = (struct sockaddr*)
653             (((char*)res) + sizeof(struct evutil_addrinfo));
654         memcpy(res->ai_addr, sa, socklen);
655         res->ai_addrlen = socklen;
656         res->ai_family = sa->sa_family; /* Same or not? XXX */
657         res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
658         res->ai_socktype = hints->ai_socktype;
659         res->ai_protocol = hints->ai_protocol;
660
661         return res;
662 }
663
664 /* Append the addrinfo 'append' to the end of 'first', and return the start of
665  * the list.  Either element can be NULL, in which case we return the element
666  * that is not NULL. */
667 struct evutil_addrinfo *
668 evutil_addrinfo_append(struct evutil_addrinfo *first,
669     struct evutil_addrinfo *append)
670 {
671         struct evutil_addrinfo *ai = first;
672         if (!ai)
673                 return append;
674         while (ai->ai_next)
675                 ai = ai->ai_next;
676         ai->ai_next = append;
677
678         return first;
679 }
680
681 static int
682 parse_numeric_servname(const char *servname)
683 {
684         int n;
685         char *endptr=NULL;
686         n = (int) strtol(servname, &endptr, 10);
687         if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
688                 return n;
689         else
690                 return -1;
691 }
692
693 /** Parse a service name in 'servname', which can be a decimal port.
694  * Return the port number, or -1 on error.
695  */
696 static int
697 evutil_parse_servname(const char *servname, const char *protocol,
698     const struct evutil_addrinfo *hints)
699 {
700         int n = parse_numeric_servname(servname);
701         if (n>=0)
702                 return n;
703 #if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(WIN32)
704         if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
705                 struct servent *ent = getservbyname(servname, protocol);
706                 if (ent) {
707                         return ntohs(ent->s_port);
708                 }
709         }
710 #endif
711         return -1;
712 }
713
714 /* Return a string corresponding to a protocol number that we can pass to
715  * getservyname.  */
716 static const char *
717 evutil_unparse_protoname(int proto)
718 {
719         switch (proto) {
720         case 0:
721                 return NULL;
722         case IPPROTO_TCP:
723                 return "tcp";
724         case IPPROTO_UDP:
725                 return "udp";
726 #ifdef IPPROTO_SCTP
727         case IPPROTO_SCTP:
728                 return "sctp";
729 #endif
730         default:
731 #ifdef _EVENT_HAVE_GETPROTOBYNUMBER
732                 {
733                         struct protoent *ent = getprotobynumber(proto);
734                         if (ent)
735                                 return ent->p_name;
736                 }
737 #endif
738                 return NULL;
739         }
740 }
741
742 static void
743 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
744 {
745         /* If we can guess the protocol from the socktype, do so. */
746         if (!hints->ai_protocol && hints->ai_socktype) {
747                 if (hints->ai_socktype == SOCK_DGRAM)
748                         hints->ai_protocol = IPPROTO_UDP;
749                 else if (hints->ai_socktype == SOCK_STREAM)
750                         hints->ai_protocol = IPPROTO_TCP;
751         }
752
753         /* Set the socktype if it isn't set. */
754         if (!hints->ai_socktype && hints->ai_protocol) {
755                 if (hints->ai_protocol == IPPROTO_UDP)
756                         hints->ai_socktype = SOCK_DGRAM;
757                 else if (hints->ai_protocol == IPPROTO_TCP)
758                         hints->ai_socktype = SOCK_STREAM;
759 #ifdef IPPROTO_SCTP
760                 else if (hints->ai_protocol == IPPROTO_SCTP)
761                         hints->ai_socktype = SOCK_STREAM;
762 #endif
763         }
764 }
765
766 #if AF_UNSPEC != PF_UNSPEC
767 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
768 #endif
769
770 /** Implements the part of looking up hosts by name that's common to both
771  * the blocking and nonblocking resolver:
772  *   - Adjust 'hints' to have a reasonable socktype and protocol.
773  *   - Look up the port based on 'servname', and store it in *portnum,
774  *   - Handle the nodename==NULL case
775  *   - Handle some invalid arguments cases.
776  *   - Handle the cases where nodename is an IPv4 or IPv6 address.
777  *
778  * If we need the resolver to look up the hostname, we return
779  * EVUTIL_EAI_NEED_RESOLVE.  Otherwise, we can completely implement
780  * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
781  * set *res as getaddrinfo would.
782  */
783 int
784 evutil_getaddrinfo_common(const char *nodename, const char *servname,
785     struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
786 {
787         int port = 0;
788         const char *pname;
789
790         if (nodename == NULL && servname == NULL)
791                 return EVUTIL_EAI_NONAME;
792
793         /* We only understand 3 families */
794         if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
795             hints->ai_family != PF_INET6)
796                 return EVUTIL_EAI_FAMILY;
797
798         evutil_getaddrinfo_infer_protocols(hints);
799
800         /* Look up the port number and protocol, if possible. */
801         pname = evutil_unparse_protoname(hints->ai_protocol);
802         if (servname) {
803                 /* XXXX We could look at the protocol we got back from
804                  * getservbyname, but it doesn't seem too useful. */
805                 port = evutil_parse_servname(servname, pname, hints);
806                 if (port < 0) {
807                         return EVUTIL_EAI_NONAME;
808                 }
809         }
810
811         /* If we have no node name, then we're supposed to bind to 'any' and
812          * connect to localhost. */
813         if (nodename == NULL) {
814                 struct evutil_addrinfo *res4=NULL, *res6=NULL;
815                 if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
816                         struct sockaddr_in6 sin6;
817                         memset(&sin6, 0, sizeof(sin6));
818                         sin6.sin6_family = AF_INET6;
819                         sin6.sin6_port = htons(port);
820                         if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
821                                 /* Bind to :: */
822                         } else {
823                                 /* connect to ::1 */
824                                 sin6.sin6_addr.s6_addr[15] = 1;
825                         }
826                         res6 = evutil_new_addrinfo((struct sockaddr*)&sin6,
827                             sizeof(sin6), hints);
828                         if (!res6)
829                                 return EVUTIL_EAI_MEMORY;
830                 }
831
832                 if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
833                         struct sockaddr_in sin;
834                         memset(&sin, 0, sizeof(sin));
835                         sin.sin_family = AF_INET;
836                         sin.sin_port = htons(port);
837                         if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
838                                 /* Bind to 0.0.0.0 */
839                         } else {
840                                 /* connect to 127.0.0.1 */
841                                 sin.sin_addr.s_addr = htonl(0x7f000001);
842                         }
843                         res4 = evutil_new_addrinfo((struct sockaddr*)&sin,
844                             sizeof(sin), hints);
845                         if (!res4) {
846                                 if (res6)
847                                         evutil_freeaddrinfo(res6);
848                                 return EVUTIL_EAI_MEMORY;
849                         }
850                 }
851                 *res = evutil_addrinfo_append(res4, res6);
852                 return 0;
853         }
854
855         /* If we can, we should try to parse the hostname without resolving
856          * it. */
857         /* Try ipv6. */
858         if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
859                 struct sockaddr_in6 sin6;
860                 memset(&sin6, 0, sizeof(sin6));
861                 if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
862                         /* Got an ipv6 address. */
863                         sin6.sin6_family = AF_INET6;
864                         sin6.sin6_port = htons(port);
865                         *res = evutil_new_addrinfo((struct sockaddr*)&sin6,
866                             sizeof(sin6), hints);
867                         if (!*res)
868                                 return EVUTIL_EAI_MEMORY;
869                         return 0;
870                 }
871         }
872
873         /* Try ipv4. */
874         if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
875                 struct sockaddr_in sin;
876                 memset(&sin, 0, sizeof(sin));
877                 if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
878                         /* Got an ipv6 address. */
879                         sin.sin_family = AF_INET;
880                         sin.sin_port = htons(port);
881                         *res = evutil_new_addrinfo((struct sockaddr*)&sin,
882                             sizeof(sin), hints);
883                         if (!*res)
884                                 return EVUTIL_EAI_MEMORY;
885                         return 0;
886                 }
887         }
888
889
890         /* If we have reached this point, we definitely need to do a DNS
891          * lookup. */
892         if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
893                 /* If we're not allowed to do one, then say so. */
894                 return EVUTIL_EAI_NONAME;
895         }
896         *portnum = port;
897         return EVUTIL_EAI_NEED_RESOLVE;
898 }
899
900 #ifdef _EVENT_HAVE_GETADDRINFO
901 #define USE_NATIVE_GETADDRINFO
902 #endif
903
904 #ifdef USE_NATIVE_GETADDRINFO
905 /* A mask of all the flags that we declare, so we can clear them before calling
906  * the native getaddrinfo */
907 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
908 #ifndef AI_PASSIVE
909     EVUTIL_AI_PASSIVE |
910 #endif
911 #ifndef AI_CANONNAME
912     EVUTIL_AI_CANONNAME |
913 #endif
914 #ifndef AI_NUMERICHOST
915     EVUTIL_AI_NUMERICHOST |
916 #endif
917 #ifndef AI_NUMERICSERV
918     EVUTIL_AI_NUMERICSERV |
919 #endif
920 #ifndef AI_ADDRCONFIG
921     EVUTIL_AI_ADDRCONFIG |
922 #endif
923 #ifndef AI_ALL
924     EVUTIL_AI_ALL |
925 #endif
926 #ifndef AI_V4MAPPED
927     EVUTIL_AI_V4MAPPED |
928 #endif
929     EVUTIL_AI_LIBEVENT_ALLOCATED;
930
931 static const unsigned int ALL_NATIVE_AI_FLAGS =
932 #ifdef AI_PASSIVE
933     AI_PASSIVE |
934 #endif
935 #ifdef AI_CANONNAME
936     AI_CANONNAME |
937 #endif
938 #ifdef AI_NUMERICHOST
939     AI_NUMERICHOST |
940 #endif
941 #ifdef AI_NUMERICSERV
942     AI_NUMERICSERV |
943 #endif
944 #ifdef AI_ADDRCONFIG
945     AI_ADDRCONFIG |
946 #endif
947 #ifdef AI_ALL
948     AI_ALL |
949 #endif
950 #ifdef AI_V4MAPPED
951     AI_V4MAPPED |
952 #endif
953     0;
954 #endif
955
956 #ifndef USE_NATIVE_GETADDRINFO
957 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
958  * a struct hostent.
959  */
960 static struct evutil_addrinfo *
961 addrinfo_from_hostent(const struct hostent *ent,
962     int port, const struct evutil_addrinfo *hints)
963 {
964         int i;
965         struct sockaddr_in sin;
966         struct sockaddr_in6 sin6;
967         struct sockaddr *sa;
968         int socklen;
969         struct evutil_addrinfo *res=NULL, *ai;
970         void *addrp;
971
972         if (ent->h_addrtype == PF_INET) {
973                 memset(&sin, 0, sizeof(sin));
974                 sin.sin_family = AF_INET;
975                 sin.sin_port = htons(port);
976                 sa = (struct sockaddr *)&sin;
977                 socklen = sizeof(struct sockaddr_in);
978                 addrp = &sin.sin_addr;
979                 if (ent->h_length != sizeof(sin.sin_addr)) {
980                         event_warnx("Weird h_length from gethostbyname");
981                         return NULL;
982                 }
983         } else if (ent->h_addrtype == PF_INET6) {
984                 memset(&sin6, 0, sizeof(sin6));
985                 sin6.sin6_family = AF_INET6;
986                 sin6.sin6_port = htons(port);
987                 sa = (struct sockaddr *)&sin6;
988                 socklen = sizeof(struct sockaddr_in);
989                 addrp = &sin6.sin6_addr;
990                 if (ent->h_length != sizeof(sin6.sin6_addr)) {
991                         event_warnx("Weird h_length from gethostbyname");
992                         return NULL;
993                 }
994         } else
995                 return NULL;
996
997         for (i = 0; ent->h_addr_list[i]; ++i) {
998                 memcpy(addrp, ent->h_addr_list[i], ent->h_length);
999                 ai = evutil_new_addrinfo(sa, socklen, hints);
1000                 if (!ai) {
1001                         evutil_freeaddrinfo(res);
1002                         return NULL;
1003                 }
1004                 res = evutil_addrinfo_append(res, ai);
1005         }
1006
1007         if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
1008                 res->ai_canonname = mm_strdup(ent->h_name);
1009                 if (res->ai_canonname == NULL) {
1010                         evutil_freeaddrinfo(res);
1011                         return NULL;
1012                 }
1013         }
1014
1015         return res;
1016 }
1017 #endif
1018
1019 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1020  * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1021  * that we'll only get addresses we could maybe connect to.
1022  */
1023 void
1024 evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints)
1025 {
1026         if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1027                 return;
1028         if (hints->ai_family != PF_UNSPEC)
1029                 return;
1030         if (!have_checked_interfaces)
1031                 evutil_check_interfaces(0);
1032         if (had_ipv4_address && !had_ipv6_address) {
1033                 hints->ai_family = PF_INET;
1034         } else if (!had_ipv4_address && had_ipv6_address) {
1035                 hints->ai_family = PF_INET6;
1036         }
1037 }
1038
1039 #ifdef USE_NATIVE_GETADDRINFO
1040 static int need_numeric_port_hack_=0;
1041 static int need_socktype_protocol_hack_=0;
1042 static int tested_for_getaddrinfo_hacks=0;
1043
1044 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1045    giving a numeric port without giving an ai_socktype was verboten.
1046    We test for this so we can apply an appropriate workaround.  If it
1047    turns out that the bug is present, then:
1048
1049     - If nodename==NULL and servname is numeric, we build an answer
1050       ourselves using evutil_getaddrinfo_common().
1051
1052     - If nodename!=NULL and servname is numeric, then we set
1053       servname=NULL when calling getaddrinfo, and post-process the
1054       result to set the ports on it.
1055
1056    We test for this bug at runtime, since otherwise we can't have the
1057    same binary run on multiple BSD versions.
1058
1059    - Some versions of Solaris believe that it's nice to leave to protocol
1060      field set to 0.  We test for this so we can apply an appropriate
1061      workaround.
1062 */
1063 static void
1064 test_for_getaddrinfo_hacks(void)
1065 {
1066         int r, r2;
1067         struct evutil_addrinfo *ai=NULL, *ai2=NULL;
1068         struct evutil_addrinfo hints;
1069
1070         memset(&hints,0,sizeof(hints));
1071         hints.ai_family = PF_UNSPEC;
1072         hints.ai_flags =
1073 #ifdef AI_NUMERICHOST
1074             AI_NUMERICHOST |
1075 #endif
1076 #ifdef AI_NUMERICSERV
1077             AI_NUMERICSERV |
1078 #endif
1079             0;
1080         r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1081         hints.ai_socktype = SOCK_STREAM;
1082         r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1083         if (r2 == 0 && r != 0) {
1084                 need_numeric_port_hack_=1;
1085         }
1086         if (ai2 && ai2->ai_protocol == 0) {
1087                 need_socktype_protocol_hack_=1;
1088         }
1089
1090         if (ai)
1091                 freeaddrinfo(ai);
1092         if (ai2)
1093                 freeaddrinfo(ai2);
1094         tested_for_getaddrinfo_hacks=1;
1095 }
1096
1097 static inline int
1098 need_numeric_port_hack(void)
1099 {
1100         if (!tested_for_getaddrinfo_hacks)
1101                 test_for_getaddrinfo_hacks();
1102         return need_numeric_port_hack_;
1103 }
1104
1105 static inline int
1106 need_socktype_protocol_hack(void)
1107 {
1108         if (!tested_for_getaddrinfo_hacks)
1109                 test_for_getaddrinfo_hacks();
1110         return need_socktype_protocol_hack_;
1111 }
1112
1113 static void
1114 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1115 {
1116         /* Now we run through the list and set the ports on all of the
1117          * results where ports would make sense. */
1118         for ( ; *ai; ai = &(*ai)->ai_next) {
1119                 struct sockaddr *sa = (*ai)->ai_addr;
1120                 if (sa && sa->sa_family == AF_INET) {
1121                         struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1122                         sin->sin_port = htons(port);
1123                 } else if (sa && sa->sa_family == AF_INET6) {
1124                         struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1125                         sin6->sin6_port = htons(port);
1126                 } else {
1127                         /* A numeric port makes no sense here; remove this one
1128                          * from the list. */
1129                         struct evutil_addrinfo *victim = *ai;
1130                         *ai = victim->ai_next;
1131                         victim->ai_next = NULL;
1132                         freeaddrinfo(victim);
1133                 }
1134         }
1135 }
1136
1137 static int
1138 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1139 {
1140         struct evutil_addrinfo *ai_new;
1141         for (; ai; ai = ai->ai_next) {
1142                 evutil_getaddrinfo_infer_protocols(ai);
1143                 if (ai->ai_socktype || ai->ai_protocol)
1144                         continue;
1145                 ai_new = mm_malloc(sizeof(*ai_new));
1146                 if (!ai_new)
1147                         return -1;
1148                 memcpy(ai_new, ai, sizeof(*ai_new));
1149                 ai->ai_socktype = SOCK_STREAM;
1150                 ai->ai_protocol = IPPROTO_TCP;
1151                 ai_new->ai_socktype = SOCK_DGRAM;
1152                 ai_new->ai_protocol = IPPROTO_UDP;
1153
1154                 ai_new->ai_next = ai->ai_next;
1155                 ai->ai_next = ai_new;
1156         }
1157         return 0;
1158 }
1159 #endif
1160
1161 int
1162 evutil_getaddrinfo(const char *nodename, const char *servname,
1163     const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1164 {
1165 #ifdef USE_NATIVE_GETADDRINFO
1166         struct evutil_addrinfo hints;
1167         int portnum=-1, need_np_hack, err;
1168
1169         if (hints_in) {
1170                 memcpy(&hints, hints_in, sizeof(hints));
1171         } else {
1172                 memset(&hints, 0, sizeof(hints));
1173                 hints.ai_family = PF_UNSPEC;
1174         }
1175
1176 #ifndef AI_ADDRCONFIG
1177         /* Not every system has AI_ADDRCONFIG, so fake it. */
1178         if (hints.ai_family == PF_UNSPEC &&
1179             (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1180                 evutil_adjust_hints_for_addrconfig(&hints);
1181         }
1182 #endif
1183
1184 #ifndef AI_NUMERICSERV
1185         /* Not every system has AI_NUMERICSERV, so fake it. */
1186         if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1187                 if (servname && parse_numeric_servname(servname)<0)
1188                         return EVUTIL_EAI_NONAME;
1189         }
1190 #endif
1191
1192         /* Enough operating systems handle enough common non-resolve
1193          * cases here weirdly enough that we are better off just
1194          * overriding them.  For example:
1195          *
1196          * - Windows doesn't like to infer the protocol from the
1197          *   socket type, or fill in socket or protocol types much at
1198          *   all.  It also seems to do its own broken implicit
1199          *   always-on version of AI_ADDRCONFIG that keeps it from
1200          *   ever resolving even a literal IPv6 address when
1201          *   ai_addrtype is PF_UNSPEC.
1202          */
1203 #ifdef WIN32
1204         {
1205                 int tmp_port;
1206                 err = evutil_getaddrinfo_common(nodename,servname,&hints,
1207                     res, &tmp_port);
1208                 if (err == 0 ||
1209                     err == EVUTIL_EAI_MEMORY ||
1210                     err == EVUTIL_EAI_NONAME)
1211                         return err;
1212                 /* If we make it here, the system getaddrinfo can
1213                  * have a crack at it. */
1214         }
1215 #endif
1216
1217         /* See documentation for need_numeric_port_hack above.*/
1218         need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1219             && ((portnum=parse_numeric_servname(servname)) >= 0);
1220         if (need_np_hack) {
1221                 if (!nodename)
1222                         return evutil_getaddrinfo_common(
1223                                 NULL,servname,&hints, res, &portnum);
1224                 servname = NULL;
1225         }
1226
1227         if (need_socktype_protocol_hack()) {
1228                 evutil_getaddrinfo_infer_protocols(&hints);
1229         }
1230
1231         /* Make sure that we didn't actually steal any AI_FLAGS values that
1232          * the system is using.  (This is a constant expression, and should ge
1233          * optimized out.)
1234          *
1235          * XXXX Turn this into a compile-time failure rather than a run-time
1236          * failure.
1237          */
1238         EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1239
1240         /* Clear any flags that only libevent understands. */
1241         hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1242
1243         err = getaddrinfo(nodename, servname, &hints, res);
1244         if (need_np_hack)
1245                 apply_numeric_port_hack(portnum, res);
1246
1247         if (need_socktype_protocol_hack()) {
1248                 if (apply_socktype_protocol_hack(*res) < 0) {
1249                         evutil_freeaddrinfo(*res);
1250                         *res = NULL;
1251                         return EVUTIL_EAI_MEMORY;
1252                 }
1253         }
1254         return err;
1255 #else
1256         int port=0, err;
1257         struct hostent *ent = NULL;
1258         struct evutil_addrinfo hints;
1259
1260         if (hints_in) {
1261                 memcpy(&hints, hints_in, sizeof(hints));
1262         } else {
1263                 memset(&hints, 0, sizeof(hints));
1264                 hints.ai_family = PF_UNSPEC;
1265         }
1266
1267         evutil_adjust_hints_for_addrconfig(&hints);
1268
1269         err = evutil_getaddrinfo_common(nodename, servname, &hints, res, &port);
1270         if (err != EVUTIL_EAI_NEED_RESOLVE) {
1271                 /* We either succeeded or failed.  No need to continue */
1272                 return err;
1273         }
1274
1275         err = 0;
1276         /* Use any of the various gethostbyname_r variants as available. */
1277         {
1278 #ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
1279                 /* This one is what glibc provides. */
1280                 char buf[2048];
1281                 struct hostent hostent;
1282                 int r;
1283                 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1284                     &err);
1285 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
1286                 char buf[2048];
1287                 struct hostent hostent;
1288                 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1289                     &err);
1290 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_3_ARG)
1291                 struct hostent_data data;
1292                 struct hostent hostent;
1293                 memset(&data, 0, sizeof(data));
1294                 err = gethostbyname_r(nodename, &hostent, &data);
1295                 ent = err ? NULL : &hostent;
1296 #else
1297                 /* fall back to gethostbyname. */
1298                 /* XXXX This needs a lock everywhere but Windows. */
1299                 ent = gethostbyname(nodename);
1300 #ifdef WIN32
1301                 err = WSAGetLastError();
1302 #else
1303                 err = h_errno;
1304 #endif
1305 #endif
1306
1307                 /* Now we have either ent or err set. */
1308                 if (!ent) {
1309                         /* XXX is this right for windows ? */
1310                         switch (err) {
1311                         case TRY_AGAIN:
1312                                 return EVUTIL_EAI_AGAIN;
1313                         case NO_RECOVERY:
1314                         default:
1315                                 return EVUTIL_EAI_FAIL;
1316                         case HOST_NOT_FOUND:
1317                                 return EVUTIL_EAI_NONAME;
1318                         case NO_ADDRESS:
1319 #if NO_DATA != NO_ADDRESS
1320                         case NO_DATA:
1321 #endif
1322                                 return EVUTIL_EAI_NODATA;
1323                         }
1324                 }
1325
1326                 if (ent->h_addrtype != hints.ai_family &&
1327                     hints.ai_family != PF_UNSPEC) {
1328                         /* This wasn't the type we were hoping for.  Too bad
1329                          * we never had a chance to ask gethostbyname for what
1330                          * we wanted. */
1331                         return EVUTIL_EAI_NONAME;
1332                 }
1333
1334                 /* Make sure we got _some_ answers. */
1335                 if (ent->h_length == 0)
1336                         return EVUTIL_EAI_NODATA;
1337
1338                 /* If we got an address type we don't know how to make a
1339                    sockaddr for, give up. */
1340                 if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1341                         return EVUTIL_EAI_FAMILY;
1342
1343                 *res = addrinfo_from_hostent(ent, port, &hints);
1344                 if (! *res)
1345                         return EVUTIL_EAI_MEMORY;
1346         }
1347
1348         return 0;
1349 #endif
1350 }
1351
1352 void
1353 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1354 {
1355 #ifdef _EVENT_HAVE_GETADDRINFO
1356         if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
1357                 freeaddrinfo(ai);
1358                 return;
1359         }
1360 #endif
1361         while (ai) {
1362                 struct evutil_addrinfo *next = ai->ai_next;
1363                 if (ai->ai_canonname)
1364                         mm_free(ai->ai_canonname);
1365                 mm_free(ai);
1366                 ai = next;
1367         }
1368 }
1369
1370 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1371
1372 void
1373 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
1374 {
1375         if (!evdns_getaddrinfo_impl)
1376                 evdns_getaddrinfo_impl = fn;
1377 }
1378
1379 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1380  * otherwise do a blocking resolve and pass the result to the callback in the
1381  * way that evdns_getaddrinfo would.
1382  */
1383 int
1384 evutil_getaddrinfo_async(struct evdns_base *dns_base,
1385     const char *nodename, const char *servname,
1386     const struct evutil_addrinfo *hints_in,
1387     void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1388 {
1389         if (dns_base && evdns_getaddrinfo_impl) {
1390                 evdns_getaddrinfo_impl(
1391                         dns_base, nodename, servname, hints_in, cb, arg);
1392         } else {
1393                 struct evutil_addrinfo *ai=NULL;
1394                 int err;
1395                 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1396                 cb(err, ai, arg);
1397         }
1398         return 0;
1399 }
1400
1401 const char *
1402 evutil_gai_strerror(int err)
1403 {
1404         /* As a sneaky side-benefit, this case statement will get most
1405          * compilers to tell us if any of the error codes we defined
1406          * conflict with the platform's native error codes. */
1407         switch (err) {
1408         case EVUTIL_EAI_CANCEL:
1409                 return "Request canceled";
1410         case 0:
1411                 return "No error";
1412
1413         case EVUTIL_EAI_ADDRFAMILY:
1414                 return "address family for nodename not supported";
1415         case EVUTIL_EAI_AGAIN:
1416                 return "temporary failure in name resolution";
1417         case EVUTIL_EAI_BADFLAGS:
1418                 return "invalid value for ai_flags";
1419         case EVUTIL_EAI_FAIL:
1420                 return "non-recoverable failure in name resolution";
1421         case EVUTIL_EAI_FAMILY:
1422                 return "ai_family not supported";
1423         case EVUTIL_EAI_MEMORY:
1424                 return "memory allocation failure";
1425         case EVUTIL_EAI_NODATA:
1426                 return "no address associated with nodename";
1427         case EVUTIL_EAI_NONAME:
1428                 return "nodename nor servname provided, or not known";
1429         case EVUTIL_EAI_SERVICE:
1430                 return "servname not supported for ai_socktype";
1431         case EVUTIL_EAI_SOCKTYPE:
1432                 return "ai_socktype not supported";
1433         case EVUTIL_EAI_SYSTEM:
1434                 return "system error";
1435         default:
1436 #if defined(USE_NATIVE_GETADDRINFO) && defined(WIN32)
1437                 return gai_strerrorA(err);
1438 #elif defined(USE_NATIVE_GETADDRINFO)
1439                 return gai_strerror(err);
1440 #else
1441                 return "Unknown error code";
1442 #endif
1443         }
1444 }
1445
1446 #ifdef WIN32
1447 #define E(code, s) { code, (s " [" #code " ]") }
1448 static struct { int code; const char *msg; } windows_socket_errors[] = {
1449   E(WSAEINTR, "Interrupted function call"),
1450   E(WSAEACCES, "Permission denied"),
1451   E(WSAEFAULT, "Bad address"),
1452   E(WSAEINVAL, "Invalid argument"),
1453   E(WSAEMFILE, "Too many open files"),
1454   E(WSAEWOULDBLOCK,  "Resource temporarily unavailable"),
1455   E(WSAEINPROGRESS, "Operation now in progress"),
1456   E(WSAEALREADY, "Operation already in progress"),
1457   E(WSAENOTSOCK, "Socket operation on nonsocket"),
1458   E(WSAEDESTADDRREQ, "Destination address required"),
1459   E(WSAEMSGSIZE, "Message too long"),
1460   E(WSAEPROTOTYPE, "Protocol wrong for socket"),
1461   E(WSAENOPROTOOPT, "Bad protocol option"),
1462   E(WSAEPROTONOSUPPORT, "Protocol not supported"),
1463   E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
1464   /* What's the difference between NOTSUPP and NOSUPPORT? :) */
1465   E(WSAEOPNOTSUPP, "Operation not supported"),
1466   E(WSAEPFNOSUPPORT,  "Protocol family not supported"),
1467   E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
1468   E(WSAEADDRINUSE, "Address already in use"),
1469   E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
1470   E(WSAENETDOWN, "Network is down"),
1471   E(WSAENETUNREACH, "Network is unreachable"),
1472   E(WSAENETRESET, "Network dropped connection on reset"),
1473   E(WSAECONNABORTED, "Software caused connection abort"),
1474   E(WSAECONNRESET, "Connection reset by peer"),
1475   E(WSAENOBUFS, "No buffer space available"),
1476   E(WSAEISCONN, "Socket is already connected"),
1477   E(WSAENOTCONN, "Socket is not connected"),
1478   E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
1479   E(WSAETIMEDOUT, "Connection timed out"),
1480   E(WSAECONNREFUSED, "Connection refused"),
1481   E(WSAEHOSTDOWN, "Host is down"),
1482   E(WSAEHOSTUNREACH, "No route to host"),
1483   E(WSAEPROCLIM, "Too many processes"),
1484
1485   /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
1486   E(WSASYSNOTREADY, "Network subsystem is unavailable"),
1487   E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
1488   E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
1489   E(WSAEDISCON, "Graceful shutdown now in progress"),
1490 #ifdef WSATYPE_NOT_FOUND
1491   E(WSATYPE_NOT_FOUND, "Class type not found"),
1492 #endif
1493   E(WSAHOST_NOT_FOUND, "Host not found"),
1494   E(WSATRY_AGAIN, "Nonauthoritative host not found"),
1495   E(WSANO_RECOVERY, "This is a nonrecoverable error"),
1496   E(WSANO_DATA, "Valid name, no data record of requested type)"),
1497
1498   /* There are some more error codes whose numeric values are marked
1499    * <b>OS dependent</b>. They start with WSA_, apparently for the same
1500    * reason that practitioners of some craft traditions deliberately
1501    * introduce imperfections into their baskets and rugs "to allow the
1502    * evil spirits to escape."  If we catch them, then our binaries
1503    * might not report consistent results across versions of Windows.
1504    * Thus, I'm going to let them all fall through.
1505    */
1506   { -1, NULL },
1507 };
1508 #undef E
1509 /** Equivalent to strerror, but for windows socket errors. */
1510 const char *
1511 evutil_socket_error_to_string(int errcode)
1512 {
1513   /* XXXX Is there really no built-in function to do this? */
1514   int i;
1515   for (i=0; windows_socket_errors[i].code >= 0; ++i) {
1516     if (errcode == windows_socket_errors[i].code)
1517       return windows_socket_errors[i].msg;
1518   }
1519   return strerror(errcode);
1520 }
1521 #endif
1522
1523 int
1524 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
1525 {
1526         int r;
1527         va_list ap;
1528         va_start(ap, format);
1529         r = evutil_vsnprintf(buf, buflen, format, ap);
1530         va_end(ap);
1531         return r;
1532 }
1533
1534 int
1535 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
1536 {
1537         int r;
1538         if (!buflen)
1539                 return 0;
1540 #ifdef _MSC_VER
1541         r = _vsnprintf(buf, buflen, format, ap);
1542         if (r < 0)
1543                 r = _vscprintf(format, ap);
1544 #elif defined(sgi)
1545         /* Make sure we always use the correct vsnprintf on IRIX */
1546         extern int      _xpg5_vsnprintf(char * __restrict,
1547                 __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
1548                 const char * __restrict, /* va_list */ char *);
1549
1550         r = _xpg5_vsnprintf(buf, buflen, format, ap);
1551 #else
1552         r = vsnprintf(buf, buflen, format, ap);
1553 #endif
1554         buf[buflen-1] = '\0';
1555         return r;
1556 }
1557
1558 #define USE_INTERNAL_NTOP
1559 #define USE_INTERNAL_PTON
1560
1561 const char *
1562 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
1563 {
1564 #if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1565         return inet_ntop(af, src, dst, len);
1566 #else
1567         if (af == AF_INET) {
1568                 const struct in_addr *in = src;
1569                 const ev_uint32_t a = ntohl(in->s_addr);
1570                 int r;
1571                 r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
1572                     (int)(ev_uint8_t)((a>>24)&0xff),
1573                     (int)(ev_uint8_t)((a>>16)&0xff),
1574                     (int)(ev_uint8_t)((a>>8 )&0xff),
1575                     (int)(ev_uint8_t)((a    )&0xff));
1576                 if (r<0||(size_t)r>=len)
1577                         return NULL;
1578                 else
1579                         return dst;
1580 #ifdef AF_INET6
1581         } else if (af == AF_INET6) {
1582                 const struct in6_addr *addr = src;
1583                 char buf[64], *cp;
1584                 int longestGapLen = 0, longestGapPos = -1, i,
1585                         curGapPos = -1, curGapLen = 0;
1586                 ev_uint16_t words[8];
1587                 for (i = 0; i < 8; ++i) {
1588                         words[i] =
1589                             (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1590                 }
1591                 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1592                     words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1593                         (words[5] == 0xffff))) {
1594                         /* This is an IPv4 address. */
1595                         if (words[5] == 0) {
1596                                 evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1597                                     addr->s6_addr[12], addr->s6_addr[13],
1598                                     addr->s6_addr[14], addr->s6_addr[15]);
1599                         } else {
1600                                 evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1601                                     addr->s6_addr[12], addr->s6_addr[13],
1602                                     addr->s6_addr[14], addr->s6_addr[15]);
1603                         }
1604                         if (strlen(buf) > len)
1605                                 return NULL;
1606                         strlcpy(dst, buf, len);
1607                         return dst;
1608                 }
1609                 i = 0;
1610                 while (i < 8) {
1611                         if (words[i] == 0) {
1612                                 curGapPos = i++;
1613                                 curGapLen = 1;
1614                                 while (i<8 && words[i] == 0) {
1615                                         ++i; ++curGapLen;
1616                                 }
1617                                 if (curGapLen > longestGapLen) {
1618                                         longestGapPos = curGapPos;
1619                                         longestGapLen = curGapLen;
1620                                 }
1621                         } else {
1622                                 ++i;
1623                         }
1624                 }
1625                 if (longestGapLen<=1)
1626                         longestGapPos = -1;
1627
1628                 cp = buf;
1629                 for (i = 0; i < 8; ++i) {
1630                         if (words[i] == 0 && longestGapPos == i) {
1631                                 if (i == 0)
1632                                         *cp++ = ':';
1633                                 *cp++ = ':';
1634                                 while (i < 8 && words[i] == 0)
1635                                         ++i;
1636                                 --i; /* to compensate for loop increment. */
1637                         } else {
1638                                 evutil_snprintf(cp,
1639                                                                 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1640                                 cp += strlen(cp);
1641                                 if (i != 7)
1642                                         *cp++ = ':';
1643                         }
1644                 }
1645                 *cp = '\0';
1646                 if (strlen(buf) > len)
1647                         return NULL;
1648                 strlcpy(dst, buf, len);
1649                 return dst;
1650 #endif
1651         } else {
1652                 return NULL;
1653         }
1654 #endif
1655 }
1656
1657 int
1658 evutil_inet_pton(int af, const char *src, void *dst)
1659 {
1660 #if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1661         return inet_pton(af, src, dst);
1662 #else
1663         if (af == AF_INET) {
1664                 int a,b,c,d;
1665                 char more;
1666                 struct in_addr *addr = dst;
1667                 if (sscanf(src, "%d.%d.%d.%d%c", &a,&b,&c,&d,&more) != 4)
1668                         return 0;
1669                 if (a < 0 || a > 255) return 0;
1670                 if (b < 0 || b > 255) return 0;
1671                 if (c < 0 || c > 255) return 0;
1672                 if (d < 0 || d > 255) return 0;
1673                 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1674                 return 1;
1675 #ifdef AF_INET6
1676         } else if (af == AF_INET6) {
1677                 struct in6_addr *out = dst;
1678                 ev_uint16_t words[8];
1679                 int gapPos = -1, i, setWords=0;
1680                 const char *dot = strchr(src, '.');
1681                 const char *eow; /* end of words. */
1682                 if (dot == src)
1683                         return 0;
1684                 else if (!dot)
1685                         eow = src+strlen(src);
1686                 else {
1687                         int byte1,byte2,byte3,byte4;
1688                         char more;
1689                         for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT(*eow); --eow)
1690                                 ;
1691                         ++eow;
1692
1693                         /* We use "scanf" because some platform inet_aton()s are too lax
1694                          * about IPv4 addresses of the form "1.2.3" */
1695                         if (sscanf(eow, "%d.%d.%d.%d%c",
1696                                            &byte1,&byte2,&byte3,&byte4,&more) != 4)
1697                                 return 0;
1698
1699                         if (byte1 > 255 || byte1 < 0 ||
1700                                 byte2 > 255 || byte2 < 0 ||
1701                                 byte3 > 255 || byte3 < 0 ||
1702                                 byte4 > 255 || byte4 < 0)
1703                                 return 0;
1704
1705                         words[6] = (byte1<<8) | byte2;
1706                         words[7] = (byte3<<8) | byte4;
1707                         setWords += 2;
1708                 }
1709
1710                 i = 0;
1711                 while (src < eow) {
1712                         if (i > 7)
1713                                 return 0;
1714                         if (EVUTIL_ISXDIGIT(*src)) {
1715                                 char *next;
1716                                 long r = strtol(src, &next, 16);
1717                                 if (next > 4+src)
1718                                         return 0;
1719                                 if (next == src)
1720                                         return 0;
1721                                 if (r<0 || r>65536)
1722                                         return 0;
1723
1724                                 words[i++] = (ev_uint16_t)r;
1725                                 setWords++;
1726                                 src = next;
1727                                 if (*src != ':' && src != eow)
1728                                         return 0;
1729                                 ++src;
1730                         } else if (*src == ':' && i > 0 && gapPos==-1) {
1731                                 gapPos = i;
1732                                 ++src;
1733                         } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1734                                 gapPos = i;
1735                                 src += 2;
1736                         } else {
1737                                 return 0;
1738                         }
1739                 }
1740
1741                 if (setWords > 8 ||
1742                         (setWords == 8 && gapPos != -1) ||
1743                         (setWords < 8 && gapPos == -1))
1744                         return 0;
1745
1746                 if (gapPos >= 0) {
1747                         int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1748                         int gapLen = 8 - setWords;
1749                         /* assert(nToMove >= 0); */
1750                         if (nToMove < 0)
1751                                 return -1; /* should be impossible */
1752                         memmove(&words[gapPos+gapLen], &words[gapPos],
1753                                         sizeof(ev_uint16_t)*nToMove);
1754                         memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
1755                 }
1756                 for (i = 0; i < 8; ++i) {
1757                         out->s6_addr[2*i  ] = words[i] >> 8;
1758                         out->s6_addr[2*i+1] = words[i] & 0xff;
1759                 }
1760
1761                 return 1;
1762 #endif
1763         } else {
1764                 return -1;
1765         }
1766 #endif
1767 }
1768
1769 int
1770 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
1771 {
1772         int port;
1773         char buf[128];
1774         const char *cp, *addr_part, *port_part;
1775         int is_ipv6;
1776         /* recognized formats are:
1777          * [ipv6]:port
1778          * ipv6
1779          * [ipv6]
1780          * ipv4:port
1781          * ipv4
1782          */
1783
1784         cp = strchr(ip_as_string, ':');
1785         if (*ip_as_string == '[') {
1786                 int len;
1787                 if (!(cp = strchr(ip_as_string, ']'))) {
1788                         return -1;
1789                 }
1790                 len = (int) ( cp-(ip_as_string + 1) );
1791                 if (len > (int)sizeof(buf)-1) {
1792                         return -1;
1793                 }
1794                 memcpy(buf, ip_as_string+1, len);
1795                 buf[len] = '\0';
1796                 addr_part = buf;
1797                 if (cp[1] == ':')
1798                         port_part = cp+2;
1799                 else
1800                         port_part = NULL;
1801                 is_ipv6 = 1;
1802         } else if (cp && strchr(cp+1, ':')) {
1803                 is_ipv6 = 1;
1804                 addr_part = ip_as_string;
1805                 port_part = NULL;
1806         } else if (cp) {
1807                 is_ipv6 = 0;
1808                 if (cp - ip_as_string > (int)sizeof(buf)-1) {
1809                         return -1;
1810                 }
1811                 memcpy(buf, ip_as_string, cp-ip_as_string);
1812                 buf[cp-ip_as_string] = '\0';
1813                 addr_part = buf;
1814                 port_part = cp+1;
1815         } else {
1816                 addr_part = ip_as_string;
1817                 port_part = NULL;
1818                 is_ipv6 = 0;
1819         }
1820
1821         if (port_part == NULL) {
1822                 port = 0;
1823         } else {
1824                 port = atoi(port_part);
1825                 if (port <= 0 || port > 65535) {
1826                         return -1;
1827                 }
1828         }
1829
1830         if (!addr_part)
1831                 return -1; /* Should be impossible. */
1832 #ifdef AF_INET6
1833         if (is_ipv6)
1834         {
1835                 struct sockaddr_in6 sin6;
1836                 memset(&sin6, 0, sizeof(sin6));
1837 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
1838                 sin6.sin6_len = sizeof(sin6);
1839 #endif
1840                 sin6.sin6_family = AF_INET6;
1841                 sin6.sin6_port = htons(port);
1842                 if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
1843                         return -1;
1844                 if ((int)sizeof(sin6) > *outlen)
1845                         return -1;
1846                 memset(out, 0, *outlen);
1847                 memcpy(out, &sin6, sizeof(sin6));
1848                 *outlen = sizeof(sin6);
1849                 return 0;
1850         }
1851         else
1852 #endif
1853         {
1854                 struct sockaddr_in sin;
1855                 memset(&sin, 0, sizeof(sin));
1856 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
1857                 sin.sin_len = sizeof(sin);
1858 #endif
1859                 sin.sin_family = AF_INET;
1860                 sin.sin_port = htons(port);
1861                 if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
1862                         return -1;
1863                 if ((int)sizeof(sin) > *outlen)
1864                         return -1;
1865                 memset(out, 0, *outlen);
1866                 memcpy(out, &sin, sizeof(sin));
1867                 *outlen = sizeof(sin);
1868                 return 0;
1869         }
1870 }
1871
1872 const char *
1873 evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen)
1874 {
1875         char b[128];
1876         const char *res=NULL;
1877         int port;
1878         if (sa->sa_family == AF_INET) {
1879                 const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
1880                 res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
1881                 port = ntohs(sin->sin_port);
1882                 if (res) {
1883                         evutil_snprintf(out, outlen, "%s:%d", b, port);
1884                         return out;
1885                 }
1886         } else if (sa->sa_family == AF_INET6) {
1887                 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
1888                 res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
1889                 port = ntohs(sin6->sin6_port);
1890                 if (res) {
1891                         evutil_snprintf(out, outlen, "[%s]:%d", b, port);
1892                         return out;
1893                 }
1894         }
1895
1896         evutil_snprintf(out, outlen, "<addr with socktype %d>",
1897             (int)sa->sa_family);
1898         return out;
1899 }
1900
1901 int
1902 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
1903     int include_port)
1904 {
1905         int r;
1906         if (0 != (r = (sa1->sa_family - sa2->sa_family)))
1907                 return r;
1908
1909         if (sa1->sa_family == AF_INET) {
1910                 const struct sockaddr_in *sin1, *sin2;
1911                 sin1 = (const struct sockaddr_in *)sa1;
1912                 sin2 = (const struct sockaddr_in *)sa2;
1913                 if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
1914                         return -1;
1915                 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
1916                         return 1;
1917                 else if (include_port &&
1918                     (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
1919                         return r;
1920                 else
1921                         return 0;
1922         }
1923 #ifdef AF_INET6
1924         else if (sa1->sa_family == AF_INET6) {
1925                 const struct sockaddr_in6 *sin1, *sin2;
1926                 sin1 = (const struct sockaddr_in6 *)sa1;
1927                 sin2 = (const struct sockaddr_in6 *)sa2;
1928                 if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
1929                         return r;
1930                 else if (include_port &&
1931                     (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
1932                         return r;
1933                 else
1934                         return 0;
1935         }
1936 #endif
1937         return 1;
1938 }
1939
1940 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions.  Each table
1941  * has 256 bits to look up whether a character is in some set or not.  This
1942  * fails on non-ASCII platforms, but so does every other place where we
1943  * take a char and write it onto the network.
1944  **/
1945 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
1946   { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
1947 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
1948   { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
1949 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
1950 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
1951   { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
1952 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
1953 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
1954   { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
1955 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
1956 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
1957 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
1958  * equivalents. */
1959 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
1960   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1961   16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1962   32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
1963   48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
1964   64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
1965   80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
1966   96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
1967   80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
1968   128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
1969   144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
1970   160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
1971   176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
1972   192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
1973   208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
1974   224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
1975   240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
1976 };
1977 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
1978   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1979   16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1980   32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
1981   48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
1982   64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
1983   112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
1984   96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
1985   112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
1986   128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
1987   144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
1988   160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
1989   176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
1990   192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
1991   208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
1992   224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
1993   240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
1994 };
1995
1996 #define IMPL_CTYPE_FN(name)                                             \
1997         int EVUTIL_##name(char c) {                                     \
1998                 ev_uint8_t u = c;                                       \
1999                 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
2000         }
2001 IMPL_CTYPE_FN(ISALPHA)
2002 IMPL_CTYPE_FN(ISALNUM)
2003 IMPL_CTYPE_FN(ISSPACE)
2004 IMPL_CTYPE_FN(ISDIGIT)
2005 IMPL_CTYPE_FN(ISXDIGIT)
2006 IMPL_CTYPE_FN(ISPRINT)
2007 IMPL_CTYPE_FN(ISLOWER)
2008 IMPL_CTYPE_FN(ISUPPER)
2009
2010 char EVUTIL_TOLOWER(char c)
2011 {
2012         return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2013 }
2014 char EVUTIL_TOUPPER(char c)
2015 {
2016         return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2017 }
2018 int
2019 evutil_ascii_strcasecmp(const char *s1, const char *s2)
2020 {
2021         char c1, c2;
2022         while (1) {
2023                 c1 = EVUTIL_TOLOWER(*s1++);
2024                 c2 = EVUTIL_TOLOWER(*s2++);
2025                 if (c1 < c2)
2026                         return -1;
2027                 else if (c1 > c2)
2028                         return 1;
2029                 else if (c1 == 0)
2030                         return 0;
2031         }
2032 }
2033 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2034 {
2035         char c1, c2;
2036         while (n--) {
2037                 c1 = EVUTIL_TOLOWER(*s1++);
2038                 c2 = EVUTIL_TOLOWER(*s2++);
2039                 if (c1 < c2)
2040                         return -1;
2041                 else if (c1 > c2)
2042                         return 1;
2043                 else if (c1 == 0)
2044                         return 0;
2045         }
2046         return 0;
2047 }
2048
2049 static int
2050 evutil_issetugid(void)
2051 {
2052 #ifdef _EVENT_HAVE_ISSETUGID
2053         return issetugid();
2054 #else
2055
2056 #ifdef _EVENT_HAVE_GETEUID
2057         if (getuid() != geteuid())
2058                 return 1;
2059 #endif
2060 #ifdef _EVENT_HAVE_GETEGID
2061         if (getgid() != getegid())
2062                 return 1;
2063 #endif
2064         return 0;
2065 #endif
2066 }
2067
2068 const char *
2069 evutil_getenv(const char *varname)
2070 {
2071         if (evutil_issetugid())
2072                 return NULL;
2073
2074         return getenv(varname);
2075 }
2076
2077 long
2078 _evutil_weakrand(void)
2079 {
2080 #ifdef WIN32
2081         return rand();
2082 #else
2083         return random();
2084 #endif
2085 }
2086
2087 int
2088 evutil_sockaddr_is_loopback(const struct sockaddr *addr)
2089 {
2090         static const char LOOPBACK_S6[16] =
2091             "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2092         if (addr->sa_family == AF_INET) {
2093                 struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2094                 return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2095         } else if (addr->sa_family == AF_INET6) {
2096                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2097                 return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2098         }
2099         return 0;
2100 }
2101
2102 #define MAX_SECONDS_IN_MSEC_LONG \
2103         (((LONG_MAX) - 999) / 1000)
2104
2105 long
2106 evutil_tv_to_msec(const struct timeval *tv)
2107 {
2108         if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
2109                 return -1;
2110
2111         return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
2112 }
2113
2114 int
2115 evutil_hex_char_to_int(char c)
2116 {
2117         switch(c)
2118         {
2119                 case '0': return 0;
2120                 case '1': return 1;
2121                 case '2': return 2;
2122                 case '3': return 3;
2123                 case '4': return 4;
2124                 case '5': return 5;
2125                 case '6': return 6;
2126                 case '7': return 7;
2127                 case '8': return 8;
2128                 case '9': return 9;
2129                 case 'A': case 'a': return 10;
2130                 case 'B': case 'b': return 11;
2131                 case 'C': case 'c': return 12;
2132                 case 'D': case 'd': return 13;
2133                 case 'E': case 'e': return 14;
2134                 case 'F': case 'f': return 15;
2135         }
2136         return -1;
2137 }
2138
2139 #ifdef WIN32
2140 HANDLE
2141 evutil_load_windows_system_library(const TCHAR *library_name)
2142 {
2143   TCHAR path[MAX_PATH];
2144   unsigned n;
2145   n = GetSystemDirectory(path, MAX_PATH);
2146   if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2147     return 0;
2148   _tcscat(path, TEXT("\\"));
2149   _tcscat(path, library_name);
2150   return LoadLibrary(path);
2151 }
2152 #endif
2153