2 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "event2/event-config.h"
34 #define WIN32_LEAN_AND_MEAN
36 #undef WIN32_LEAN_AND_MEAN
41 #include <sys/types.h>
42 #ifdef _EVENT_HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
45 #ifdef _EVENT_HAVE_UNISTD_H
48 #ifdef _EVENT_HAVE_FCNTL_H
51 #ifdef _EVENT_HAVE_STDLIB_H
58 #ifdef _EVENT_HAVE_NETINET_IN_H
59 #include <netinet/in.h>
61 #ifdef _EVENT_HAVE_NETINET_IN6_H
62 #include <netinet/in6.h>
64 #ifdef _EVENT_HAVE_ARPA_INET_H
65 #include <arpa/inet.h>
68 #ifndef _EVENT_HAVE_GETTIMEOFDAY
69 #include <sys/timeb.h>
74 #include "event2/util.h"
75 #include "util-internal.h"
76 #include "log-internal.h"
77 #include "mm-internal.h"
79 #include "strlcpy-internal.h"
80 #include "ipv6-internal.h"
86 #define fstat _fstati64
91 evutil_open_closeonexec(const char *pathname, int flags, unsigned mode)
100 fd = open(pathname, flags, (mode_t)mode);
102 fd = open(pathname, flags);
106 #if !defined(O_CLOEXEC) && defined(FD_CLOEXEC)
107 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
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
120 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
122 Used internally only; may go away in a future version.
125 evutil_read_file(const char *filename, char **content_out, size_t *len_out,
131 size_t read_so_far=0;
134 EVUTIL_ASSERT(content_out);
135 EVUTIL_ASSERT(len_out);
144 fd = evutil_open_closeonexec(filename, mode, 0);
147 if (fstat(fd, &st) || st.st_size < 0 ||
148 st.st_size > EV_SSIZE_MAX-1 ) {
152 mem = mm_malloc((size_t)st.st_size + 1);
159 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
161 #define N_TO_READ(x) (x)
163 while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
165 if (read_so_far >= (size_t)st.st_size)
167 EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
174 mem[read_so_far] = 0;
176 *len_out = read_so_far;
182 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
185 return socketpair(family, type, protocol, fd);
187 return evutil_ersatz_socketpair(family, type, protocol, fd);
192 evutil_ersatz_socketpair(int family, int type, int protocol,
193 evutil_socket_t fd[2])
195 /* This code is originally from Tor. Used with permission. */
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.
203 #define ERR(e) WSA##e
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;
213 int saved_errno = -1;
216 || (family != AF_INET
221 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
225 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
229 listener = socket(AF_INET, type, 0);
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))
238 goto tidy_up_and_fail;
239 if (listen(listener, 1) == -1)
240 goto tidy_up_and_fail;
242 connector = socket(AF_INET, type, 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;
255 size = sizeof(listen_addr);
256 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
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
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;
276 abort_tidy_up_and_fail:
277 saved_errno = ERR(ECONNABORTED);
280 saved_errno = EVUTIL_SOCKET_ERROR();
282 evutil_closesocket(listener);
284 evutil_closesocket(connector);
286 evutil_closesocket(acceptor);
288 EVUTIL_SET_SOCKET_ERROR(saved_errno);
294 evutil_make_socket_nonblocking(evutil_socket_t fd)
298 u_long nonblocking = 1;
299 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
300 event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
307 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
308 event_warn("fcntl(%d, F_GETFL)", fd);
311 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
312 event_warn("fcntl(%d, F_SETFL)", fd);
321 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
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));
336 evutil_make_socket_closeonexec(evutil_socket_t fd)
338 #if !defined(WIN32) && defined(_EVENT_HAVE_SETFD)
340 if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
341 event_warn("fcntl(%d, F_GETFD)", fd);
344 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
345 event_warn("fcntl(%d, F_SETFD)", fd);
353 evutil_closesocket(evutil_socket_t sock)
358 return closesocket(sock);
363 evutil_strtoll(const char *s, char **endptr, int base)
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
375 r = (ev_int64_t) _atoi64(s);
386 return (ev_int64_t) _strtoi64(s, endptr, base);
387 #elif defined(_EVENT_SIZEOF_LONG_LONG) && _EVENT_SIZEOF_LONG_LONG == 8
390 if (base != 10 && base != 16)
393 n = sscanf(s, "%lld", &r);
395 unsigned long long ru=0;
396 n = sscanf(s, "%llx", &ru);
397 if (ru > EV_INT64_MAX)
403 while (EVUTIL_ISSPACE(*s))
408 while (EVUTIL_ISDIGIT(*s))
411 while (EVUTIL_ISXDIGIT(*s))
418 #error "I don't know how to parse 64-bit integers."
422 #ifndef _EVENT_HAVE_GETTIMEOFDAY
423 /* No gettimeofday; this muse be windows. */
425 evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
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.
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.
441 tv->tv_sec = (long) tb.time;
442 tv->tv_usec = ((int) tb.millitm) * 1000;
449 evutil_socket_geterror(evutil_socket_t sock)
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,
464 /* XXX we should use an enum here. */
465 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
467 evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
472 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
475 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
480 if (connect(*fd_ptr, sa, socklen) < 0) {
481 int e = evutil_socket_geterror(*fd_ptr);
482 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
484 if (EVUTIL_ERR_CONNECT_REFUSED(e))
493 evutil_closesocket(*fd_ptr);
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. */
504 evutil_socket_finished_connecting(evutil_socket_t fd)
507 ev_socklen_t elen = sizeof(e);
509 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
513 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
515 EVUTIL_SET_SOCKET_ERROR(e);
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"
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;
538 /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
540 #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
542 /* Macro: True iff the IPv4 address 'addr', in host order, is a class D
543 * (multiclass) address.
545 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
547 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
548 * the test seemed successful. */
550 evutil_check_interfaces(int force_recheck)
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);
561 if (have_checked_interfaces && !force_recheck)
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
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);
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);
581 memset(&sin_out, 0, sizeof(sin_out));
582 memset(&sin6_out, 0, sizeof(sin6_out));
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);
591 EVUTIL_V4ADDR_IS_LOCALHOST(addr) ||
592 EVUTIL_V4ADDR_IS_CLASSD(addr)) {
593 evutil_inet_ntop(AF_INET, &sin_out.sin_addr,
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
599 event_warnx("Got a strange local ipv4 address %s",buf);
601 event_debug(("Detected an IPv4 interface"));
602 had_ipv4_address = 1;
606 evutil_closesocket(fd);
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
620 evutil_inet_ntop(AF_INET6, &sin6_out.sin6_addr,
622 event_warnx("Got a strange local ipv6 address %s",buf);
624 event_debug(("Detected an IPv4 interface"));
625 had_ipv6_address = 1;
630 evutil_closesocket(fd);
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.
639 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
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.
646 struct evutil_addrinfo *
647 evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
648 const struct evutil_addrinfo *hints)
650 struct evutil_addrinfo *res;
651 EVUTIL_ASSERT(hints);
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);
662 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
663 r2 = evutil_new_addrinfo(sa, socklen, &tmp);
665 evutil_freeaddrinfo(r1);
672 /* We're going to allocate extra space to hold the sockaddr. */
673 res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
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;
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)
695 struct evutil_addrinfo *ai = first;
700 ai->ai_next = append;
706 parse_numeric_servname(const char *servname)
710 n = (int) strtol(servname, &endptr, 10);
711 if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
717 /** Parse a service name in 'servname', which can be a decimal port.
718 * Return the port number, or -1 on error.
721 evutil_parse_servname(const char *servname, const char *protocol,
722 const struct evutil_addrinfo *hints)
724 int n = parse_numeric_servname(servname);
727 #if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(WIN32)
728 if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
729 struct servent *ent = getservbyname(servname, protocol);
731 return ntohs(ent->s_port);
738 /* Return a string corresponding to a protocol number that we can pass to
741 evutil_unparse_protoname(int proto)
755 #ifdef _EVENT_HAVE_GETPROTOBYNUMBER
757 struct protoent *ent = getprotobynumber(proto);
767 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
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;
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;
784 else if (hints->ai_protocol == IPPROTO_SCTP)
785 hints->ai_socktype = SOCK_STREAM;
790 #if AF_UNSPEC != PF_UNSPEC
791 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
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.
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.
808 evutil_getaddrinfo_common(const char *nodename, const char *servname,
809 struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
814 if (nodename == NULL && servname == NULL)
815 return EVUTIL_EAI_NONAME;
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;
822 evutil_getaddrinfo_infer_protocols(hints);
824 /* Look up the port number and protocol, if possible. */
825 pname = evutil_unparse_protoname(hints->ai_protocol);
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);
831 return EVUTIL_EAI_NONAME;
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) {
848 sin6.sin6_addr.s6_addr[15] = 1;
850 res6 = evutil_new_addrinfo((struct sockaddr*)&sin6,
851 sizeof(sin6), hints);
853 return EVUTIL_EAI_MEMORY;
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 */
864 /* connect to 127.0.0.1 */
865 sin.sin_addr.s_addr = htonl(0x7f000001);
867 res4 = evutil_new_addrinfo((struct sockaddr*)&sin,
871 evutil_freeaddrinfo(res6);
872 return EVUTIL_EAI_MEMORY;
875 *res = evutil_addrinfo_append(res4, res6);
879 /* If we can, we should try to parse the hostname without resolving
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);
892 return EVUTIL_EAI_MEMORY;
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,
908 return EVUTIL_EAI_MEMORY;
914 /* If we have reached this point, we definitely need to do a DNS
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;
921 return EVUTIL_EAI_NEED_RESOLVE;
924 #ifdef _EVENT_HAVE_GETADDRINFO
925 #define USE_NATIVE_GETADDRINFO
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 =
936 EVUTIL_AI_CANONNAME |
938 #ifndef AI_NUMERICHOST
939 EVUTIL_AI_NUMERICHOST |
941 #ifndef AI_NUMERICSERV
942 EVUTIL_AI_NUMERICSERV |
944 #ifndef AI_ADDRCONFIG
945 EVUTIL_AI_ADDRCONFIG |
953 EVUTIL_AI_LIBEVENT_ALLOCATED;
955 static const unsigned int ALL_NATIVE_AI_FLAGS =
962 #ifdef AI_NUMERICHOST
965 #ifdef AI_NUMERICSERV
980 #ifndef USE_NATIVE_GETADDRINFO
981 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
984 static struct evutil_addrinfo *
985 addrinfo_from_hostent(const struct hostent *ent,
986 int port, const struct evutil_addrinfo *hints)
989 struct sockaddr_in sin;
990 struct sockaddr_in6 sin6;
993 struct evutil_addrinfo *res=NULL, *ai;
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");
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");
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);
1025 evutil_freeaddrinfo(res);
1028 res = evutil_addrinfo_append(res, ai);
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);
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.
1048 evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints)
1050 if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
1052 if (hints->ai_family != PF_UNSPEC)
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;
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;
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:
1073 - If nodename==NULL and servname is numeric, we build an answer
1074 ourselves using evutil_getaddrinfo_common().
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.
1080 We test for this bug at runtime, since otherwise we can't have the
1081 same binary run on multiple BSD versions.
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
1088 test_for_getaddrinfo_hacks(void)
1091 struct evutil_addrinfo *ai=NULL, *ai2=NULL;
1092 struct evutil_addrinfo hints;
1094 memset(&hints,0,sizeof(hints));
1095 hints.ai_family = PF_UNSPEC;
1097 #ifdef AI_NUMERICHOST
1100 #ifdef AI_NUMERICSERV
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;
1110 if (ai2 && ai2->ai_protocol == 0) {
1111 need_socktype_protocol_hack_=1;
1118 tested_for_getaddrinfo_hacks=1;
1122 need_numeric_port_hack(void)
1124 if (!tested_for_getaddrinfo_hacks)
1125 test_for_getaddrinfo_hacks();
1126 return need_numeric_port_hack_;
1130 need_socktype_protocol_hack(void)
1132 if (!tested_for_getaddrinfo_hacks)
1133 test_for_getaddrinfo_hacks();
1134 return need_socktype_protocol_hack_;
1138 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
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);
1151 /* A numeric port makes no sense here; remove this one
1153 struct evutil_addrinfo *victim = *ai;
1154 *ai = victim->ai_next;
1155 victim->ai_next = NULL;
1156 freeaddrinfo(victim);
1162 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
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)
1169 ai_new = mm_malloc(sizeof(*ai_new));
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;
1178 ai_new->ai_next = ai->ai_next;
1179 ai->ai_next = ai_new;
1186 evutil_getaddrinfo(const char *nodename, const char *servname,
1187 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1189 #ifdef USE_NATIVE_GETADDRINFO
1190 struct evutil_addrinfo hints;
1191 int portnum=-1, need_np_hack, err;
1194 memcpy(&hints, hints_in, sizeof(hints));
1196 memset(&hints, 0, sizeof(hints));
1197 hints.ai_family = PF_UNSPEC;
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);
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;
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:
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.
1230 err = evutil_getaddrinfo_common(nodename,servname,&hints,
1233 err == EVUTIL_EAI_MEMORY ||
1234 err == EVUTIL_EAI_NONAME)
1236 /* If we make it here, the system getaddrinfo can
1237 * have a crack at it. */
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);
1246 return evutil_getaddrinfo_common(
1247 NULL,servname,&hints, res, &portnum);
1251 if (need_socktype_protocol_hack()) {
1252 evutil_getaddrinfo_infer_protocols(&hints);
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
1259 * XXXX Turn this into a compile-time failure rather than a run-time
1262 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1264 /* Clear any flags that only libevent understands. */
1265 hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1267 err = getaddrinfo(nodename, servname, &hints, res);
1269 apply_numeric_port_hack(portnum, res);
1271 if (need_socktype_protocol_hack()) {
1272 if (apply_socktype_protocol_hack(*res) < 0) {
1273 evutil_freeaddrinfo(*res);
1275 return EVUTIL_EAI_MEMORY;
1281 struct hostent *ent = NULL;
1282 struct evutil_addrinfo hints;
1285 memcpy(&hints, hints_in, sizeof(hints));
1287 memset(&hints, 0, sizeof(hints));
1288 hints.ai_family = PF_UNSPEC;
1291 evutil_adjust_hints_for_addrconfig(&hints);
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 */
1300 /* Use any of the various gethostbyname_r variants as available. */
1302 #ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
1303 /* This one is what glibc provides. */
1305 struct hostent hostent;
1307 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1309 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
1311 struct hostent hostent;
1312 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
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;
1321 /* fall back to gethostbyname. */
1322 /* XXXX This needs a lock everywhere but Windows. */
1323 ent = gethostbyname(nodename);
1325 err = WSAGetLastError();
1331 /* Now we have either ent or err set. */
1333 /* XXX is this right for windows ? */
1336 return EVUTIL_EAI_AGAIN;
1339 return EVUTIL_EAI_FAIL;
1340 case HOST_NOT_FOUND:
1341 return EVUTIL_EAI_NONAME;
1343 #if NO_DATA != NO_ADDRESS
1346 return EVUTIL_EAI_NODATA;
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
1355 return EVUTIL_EAI_NONAME;
1358 /* Make sure we got _some_ answers. */
1359 if (ent->h_length == 0)
1360 return EVUTIL_EAI_NODATA;
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;
1367 *res = addrinfo_from_hostent(ent, port, &hints);
1369 return EVUTIL_EAI_MEMORY;
1377 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1379 #ifdef _EVENT_HAVE_GETADDRINFO
1380 if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
1386 struct evutil_addrinfo *next = ai->ai_next;
1387 if (ai->ai_canonname)
1388 mm_free(ai->ai_canonname);
1394 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1397 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
1399 if (!evdns_getaddrinfo_impl)
1400 evdns_getaddrinfo_impl = fn;
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.
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)
1413 if (dns_base && evdns_getaddrinfo_impl) {
1414 evdns_getaddrinfo_impl(
1415 dns_base, nodename, servname, hints_in, cb, arg);
1417 struct evutil_addrinfo *ai=NULL;
1419 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1426 evutil_gai_strerror(int err)
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. */
1432 case EVUTIL_EAI_CANCEL:
1433 return "Request canceled";
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";
1460 #if defined(USE_NATIVE_GETADDRINFO) && defined(WIN32)
1461 return gai_strerrorA(err);
1462 #elif defined(USE_NATIVE_GETADDRINFO)
1463 return gai_strerror(err);
1465 return "Unknown error code";
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"),
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"),
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)"),
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.
1533 /** Equivalent to strerror, but for windows socket errors. */
1535 evutil_socket_error_to_string(int errcode)
1537 /* XXXX Is there really no built-in function to do this? */
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;
1543 return strerror(errcode);
1548 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
1552 va_start(ap, format);
1553 r = evutil_vsnprintf(buf, buflen, format, ap);
1559 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
1565 r = _vsnprintf(buf, buflen, format, ap);
1567 r = _vscprintf(format, ap);
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 *);
1574 r = _xpg5_vsnprintf(buf, buflen, format, ap);
1576 r = vsnprintf(buf, buflen, format, ap);
1578 buf[buflen-1] = '\0';
1582 #define USE_INTERNAL_NTOP
1583 #define USE_INTERNAL_PTON
1586 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
1588 #if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1589 return inet_ntop(af, src, dst, len);
1591 if (af == AF_INET) {
1592 const struct in_addr *in = src;
1593 const ev_uint32_t a = ntohl(in->s_addr);
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)
1605 } else if (af == AF_INET6) {
1606 const struct in6_addr *addr = src;
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) {
1613 (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
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]);
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]);
1628 if (strlen(buf) > len)
1630 strlcpy(dst, buf, len);
1635 if (words[i] == 0) {
1638 while (i<8 && words[i] == 0) {
1641 if (curGapLen > longestGapLen) {
1642 longestGapPos = curGapPos;
1643 longestGapLen = curGapLen;
1649 if (longestGapLen<=1)
1653 for (i = 0; i < 8; ++i) {
1654 if (words[i] == 0 && longestGapPos == i) {
1658 while (i < 8 && words[i] == 0)
1660 --i; /* to compensate for loop increment. */
1663 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1670 if (strlen(buf) > len)
1672 strlcpy(dst, buf, len);
1682 evutil_inet_pton(int af, const char *src, void *dst)
1684 #if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1685 return inet_pton(af, src, dst);
1687 if (af == AF_INET) {
1690 struct in_addr *addr = dst;
1691 if (sscanf(src, "%d.%d.%d.%d%c", &a,&b,&c,&d,&more) != 4)
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);
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. */
1709 eow = src+strlen(src);
1711 int byte1,byte2,byte3,byte4;
1713 for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT(*eow); --eow)
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)
1723 if (byte1 > 255 || byte1 < 0 ||
1724 byte2 > 255 || byte2 < 0 ||
1725 byte3 > 255 || byte3 < 0 ||
1726 byte4 > 255 || byte4 < 0)
1729 words[6] = (byte1<<8) | byte2;
1730 words[7] = (byte3<<8) | byte4;
1738 if (EVUTIL_ISXDIGIT(*src)) {
1740 long r = strtol(src, &next, 16);
1748 words[i++] = (ev_uint16_t)r;
1751 if (*src != ':' && src != eow)
1754 } else if (*src == ':' && i > 0 && gapPos==-1) {
1757 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1766 (setWords == 8 && gapPos != -1) ||
1767 (setWords < 8 && gapPos == -1))
1771 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1772 int gapLen = 8 - setWords;
1773 /* assert(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);
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;
1794 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
1798 const char *cp, *addr_part, *port_part;
1800 /* recognized formats are:
1808 cp = strchr(ip_as_string, ':');
1809 if (*ip_as_string == '[') {
1811 if (!(cp = strchr(ip_as_string, ']'))) {
1814 len = (int) ( cp-(ip_as_string + 1) );
1815 if (len > (int)sizeof(buf)-1) {
1818 memcpy(buf, ip_as_string+1, len);
1826 } else if (cp && strchr(cp+1, ':')) {
1828 addr_part = ip_as_string;
1832 if (cp - ip_as_string > (int)sizeof(buf)-1) {
1835 memcpy(buf, ip_as_string, cp-ip_as_string);
1836 buf[cp-ip_as_string] = '\0';
1840 addr_part = ip_as_string;
1845 if (port_part == NULL) {
1848 port = atoi(port_part);
1849 if (port <= 0 || port > 65535) {
1855 return -1; /* Should be impossible. */
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);
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))
1868 if ((int)sizeof(sin6) > *outlen)
1870 memset(out, 0, *outlen);
1871 memcpy(out, &sin6, sizeof(sin6));
1872 *outlen = sizeof(sin6);
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);
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))
1887 if ((int)sizeof(sin) > *outlen)
1889 memset(out, 0, *outlen);
1890 memcpy(out, &sin, sizeof(sin));
1891 *outlen = sizeof(sin);
1897 evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen)
1900 const char *res=NULL;
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);
1907 evutil_snprintf(out, outlen, "%s:%d", b, port);
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);
1915 evutil_snprintf(out, outlen, "[%s]:%d", b, port);
1920 evutil_snprintf(out, outlen, "<addr with socktype %d>",
1921 (int)sa->sa_family);
1926 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
1930 if (0 != (r = (sa1->sa_family - sa2->sa_family)))
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)
1939 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
1941 else if (include_port &&
1942 (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
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)))
1954 else if (include_port &&
1955 (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
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.
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
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,
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,
2020 #define IMPL_CTYPE_FN(name) \
2021 int EVUTIL_##name(char c) { \
2023 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
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)
2034 char EVUTIL_TOLOWER(char c)
2036 return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
2038 char EVUTIL_TOUPPER(char c)
2040 return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
2043 evutil_ascii_strcasecmp(const char *s1, const char *s2)
2047 c1 = EVUTIL_TOLOWER(*s1++);
2048 c2 = EVUTIL_TOLOWER(*s2++);
2057 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
2061 c1 = EVUTIL_TOLOWER(*s1++);
2062 c2 = EVUTIL_TOLOWER(*s2++);
2074 evutil_issetugid(void)
2076 #ifdef _EVENT_HAVE_ISSETUGID
2080 #ifdef _EVENT_HAVE_GETEUID
2081 if (getuid() != geteuid())
2084 #ifdef _EVENT_HAVE_GETEGID
2085 if (getgid() != getegid())
2093 evutil_getenv(const char *varname)
2095 if (evutil_issetugid())
2098 return getenv(varname);
2102 _evutil_weakrand(void)
2112 evutil_sockaddr_is_loopback(const struct sockaddr *addr)
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);
2126 #define MAX_SECONDS_IN_MSEC_LONG \
2127 (((LONG_MAX) - 999) / 1000)
2130 evutil_tv_to_msec(const struct timeval *tv)
2132 if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
2135 return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
2139 evutil_hex_char_to_int(char c)
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;
2165 evutil_load_windows_system_library(const TCHAR *library_name)
2167 TCHAR path[MAX_PATH];
2169 n = GetSystemDirectory(path, MAX_PATH);
2170 if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2172 _tcscat(path, TEXT("\\"));
2173 _tcscat(path, library_name);
2174 return LoadLibrary(path);