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