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