2 * Copyright (c) 2007-2010 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_ARPA_INET_H
59 #include <arpa/inet.h>
61 #ifdef _EVENT_HAVE_NETINET_IN_H
62 #include <netinet/in.h>
64 #ifdef _EVENT_HAVE_NETINET_IN6_H
65 #include <netinet/in6.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 Read the contents of 'filename' into a newly allocated NUL-terminated
92 string. Set *content_out to hold this string, and *len_out to hold its
93 length (not including the appended NUL). If 'is_binary', open the file in
96 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
98 Used internally only; may go away in a future version.
101 evutil_read_file(const char *filename, char **content_out, size_t *len_out,
107 size_t read_so_far=0;
110 EVUTIL_ASSERT(content_out);
111 EVUTIL_ASSERT(len_out);
120 fd = open(filename, mode);
123 if (fstat(fd, &st) || st.st_size < 0 ||
124 st.st_size > EV_SSIZE_MAX-1 ) {
128 mem = mm_malloc((size_t)st.st_size + 1);
135 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
137 #define N_TO_READ(x) (x)
139 while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
141 if (read_so_far >= (size_t)st.st_size)
143 EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
150 mem[read_so_far] = 0;
152 *len_out = read_so_far;
158 evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
161 return socketpair(family, type, protocol, fd);
163 return evutil_ersatz_socketpair(family, type, protocol, fd);
168 evutil_ersatz_socketpair(int family, int type, int protocol,
169 evutil_socket_t fd[2])
171 /* This code is originally from Tor. Used with permission. */
173 /* This socketpair does not work when localhost is down. So
174 * it's really not the same thing at all. But it's close enough
175 * for now, and really, when localhost is down sometimes, we
176 * have other problems too.
179 #define ERR(e) WSA##e
183 evutil_socket_t listener = -1;
184 evutil_socket_t connector = -1;
185 evutil_socket_t acceptor = -1;
186 struct sockaddr_in listen_addr;
187 struct sockaddr_in connect_addr;
189 int saved_errno = -1;
192 || (family != AF_INET
197 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
201 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
205 listener = socket(AF_INET, type, 0);
208 memset(&listen_addr, 0, sizeof(listen_addr));
209 listen_addr.sin_family = AF_INET;
210 listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
211 listen_addr.sin_port = 0; /* kernel chooses port. */
212 if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
214 goto tidy_up_and_fail;
215 if (listen(listener, 1) == -1)
216 goto tidy_up_and_fail;
218 connector = socket(AF_INET, type, 0);
220 goto tidy_up_and_fail;
221 /* We want to find out the port number to connect to. */
222 size = sizeof(connect_addr);
223 if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
224 goto tidy_up_and_fail;
225 if (size != sizeof (connect_addr))
226 goto abort_tidy_up_and_fail;
227 if (connect(connector, (struct sockaddr *) &connect_addr,
228 sizeof(connect_addr)) == -1)
229 goto tidy_up_and_fail;
231 size = sizeof(listen_addr);
232 acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
234 goto tidy_up_and_fail;
235 if (size != sizeof(listen_addr))
236 goto abort_tidy_up_and_fail;
237 evutil_closesocket(listener);
238 /* Now check we are talking to ourself by matching port and host on the
240 if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
241 goto tidy_up_and_fail;
242 if (size != sizeof (connect_addr)
243 || listen_addr.sin_family != connect_addr.sin_family
244 || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
245 || listen_addr.sin_port != connect_addr.sin_port)
246 goto abort_tidy_up_and_fail;
252 abort_tidy_up_and_fail:
253 saved_errno = ERR(ECONNABORTED);
256 saved_errno = EVUTIL_SOCKET_ERROR();
258 evutil_closesocket(listener);
260 evutil_closesocket(connector);
262 evutil_closesocket(acceptor);
264 EVUTIL_SET_SOCKET_ERROR(saved_errno);
270 evutil_make_socket_nonblocking(evutil_socket_t fd)
274 u_long nonblocking = 1;
275 if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
276 event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
283 if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
284 event_warn("fcntl(%d, F_GETFL)", fd);
287 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
288 event_warn("fcntl(%d, F_SETFL)", fd);
297 evutil_make_listen_socket_reuseable(evutil_socket_t sock)
301 /* REUSEADDR on Unix means, "don't hang on to this address after the
302 * listener is closed." On Windows, though, it means "don't keep other
303 * processes from binding to this address while we're using it. */
304 return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
305 (ev_socklen_t)sizeof(one));
312 evutil_make_socket_closeonexec(evutil_socket_t fd)
314 #if !defined(WIN32) && defined(_EVENT_HAVE_SETFD)
316 if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
317 event_warn("fcntl(%d, F_GETFD)", fd);
320 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
321 event_warn("fcntl(%d, F_SETFD)", fd);
329 evutil_closesocket(evutil_socket_t sock)
334 return closesocket(sock);
339 evutil_strtoll(const char *s, char **endptr, int base)
341 #ifdef _EVENT_HAVE_STRTOLL
342 return (ev_int64_t)strtoll(s, endptr, base);
343 #elif _EVENT_SIZEOF_LONG == 8
344 return (ev_int64_t)strtol(s, endptr, base);
345 #elif defined(WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
346 /* XXXX on old versions of MS APIs, we only support base
351 r = (ev_int64_t) _atoi64(s);
360 return (ev_int64_t) _strtoi64(s, endptr, base);
362 #error "I don't know how to parse 64-bit integers."
366 #ifndef _EVENT_HAVE_GETTIMEOFDAY
367 /* No gettimeofday; this muse be windows. */
369 evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
377 * _ftime is not the greatest interface here; GetSystemTimeAsFileTime
378 * would give us better resolution, whereas something cobbled together
379 * with GetTickCount could maybe give us monotonic behavior.
381 * Either way, I think this value might be skewed to ignore the
382 * timezone, and just return local time. That's not so good.
385 tv->tv_sec = (long) tb.time;
386 tv->tv_usec = ((int) tb.millitm) * 1000;
393 evutil_socket_geterror(evutil_socket_t sock)
395 int optval, optvallen=sizeof(optval);
396 int err = WSAGetLastError();
397 if (err == WSAEWOULDBLOCK && sock >= 0) {
398 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
408 /* XXX we should use an enum here. */
409 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
411 evutil_socket_connect(evutil_socket_t *fd_ptr, struct sockaddr *sa, int socklen)
417 if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
419 if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
424 if (connect(*fd_ptr, sa, socklen) < 0) {
425 int e = evutil_socket_geterror(*fd_ptr);
426 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
428 if (EVUTIL_ERR_CONNECT_REFUSED(e))
437 evutil_closesocket(*fd_ptr);
443 /* Check whether a socket on which we called connect() is done
444 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
445 error case, set the current socket errno to the error that happened during
446 the connect operation. */
448 evutil_socket_finished_connecting(evutil_socket_t fd)
451 ev_socklen_t elen = sizeof(e);
453 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
457 if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
459 EVUTIL_SET_SOCKET_ERROR(e);
466 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
467 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
468 EVUTIL_AI_ADDRCONFIG) != \
469 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
470 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
471 EVUTIL_AI_ADDRCONFIG)
472 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
475 /* We sometimes need to know whether we have an ipv4 address and whether we
476 have an ipv6 address. If 'have_checked_interfaces', then we've already done
477 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
478 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
479 set by evutil_check_interfaces. */
480 static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
482 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
483 * the test seemed successful. */
485 evutil_check_interfaces(int force_recheck)
487 const char ZEROES[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
488 "\x00\x00\x00\x00\x00\x00\x00\x00";
489 evutil_socket_t fd = -1;
490 struct sockaddr_in sin, sin_out;
491 struct sockaddr_in6 sin6, sin6_out;
492 ev_socklen_t sin_out_len = sizeof(sin_out);
493 ev_socklen_t sin6_out_len = sizeof(sin6_out);
496 if (have_checked_interfaces && !force_recheck)
499 /* To check whether we have an interface open for a given protocol, we
500 * try to make a UDP 'connection' to a remote host on the internet.
501 * We don't actually use it, so the address doesn't matter, but we
502 * want to pick one that keep us from using a host- or link-local
504 memset(&sin, 0, sizeof(sin));
505 sin.sin_family = AF_INET;
506 sin.sin_port = htons(53);
507 r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
510 memset(&sin6, 0, sizeof(sin6));
511 sin6.sin6_family = AF_INET6;
512 sin6.sin6_port = htons(53);
513 r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
516 memset(&sin_out, 0, sizeof(sin_out));
517 memset(&sin6_out, 0, sizeof(sin6_out));
519 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
520 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
521 connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
522 getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
523 /* We might have an IPv4 interface. */
524 ev_uint32_t addr = ntohl(sin_out.sin_addr.s_addr);
525 if (addr == 0 || (addr&0xff000000) == 127 ||
526 (addr & 0xff) == 255 || (addr & 0xf0) == 14) {
527 evutil_inet_ntop(AF_INET, &sin_out.sin_addr,
529 /* This is a reserved, ipv4compat, ipv4map, loopback,
530 * link-local or unspecified address. The host should
531 * never have given it to us; it could never connect
533 event_warnx("Got a strange local ipv4 address %s",buf);
535 event_debug(("Detected an IPv4 interface"));
536 had_ipv4_address = 1;
540 evutil_closesocket(fd);
542 if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
543 connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
544 getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
545 /* We might have an IPv6 interface. */
546 const unsigned char *addr =
547 (unsigned char*)sin6_out.sin6_addr.s6_addr;
548 if (!memcmp(addr, ZEROES, 8) ||
549 (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80)) {
550 /* This is a reserved, ipv4compat, ipv4map, loopback,
551 * link-local or unspecified address. The host should
552 * never have given it to us; it could never connect
554 evutil_inet_ntop(AF_INET6, &sin6_out.sin6_addr,
556 event_warnx("Got a strange local ipv6 address %s",buf);
558 event_debug(("Detected an IPv4 interface"));
559 had_ipv6_address = 1;
564 evutil_closesocket(fd);
569 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
570 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
571 * it, and we should trust what they said.
573 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
575 /* Helper: construct a new addrinfo containing the socket address in
576 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
577 * socktype and protocol info from hints. If they weren't set, then
578 * allocate both a TCP and a UDP addrinfo.
580 struct evutil_addrinfo *
581 evutil_new_addrinfo(struct sockaddr *sa, ev_socklen_t socklen,
582 const struct evutil_addrinfo *hints)
584 struct evutil_addrinfo *res;
585 EVUTIL_ASSERT(hints);
587 if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
588 /* Indecisive user! Give them a UDP and a TCP. */
589 struct evutil_addrinfo *r1, *r2;
590 struct evutil_addrinfo tmp;
591 memcpy(&tmp, hints, sizeof(tmp));
592 tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
593 r1 = evutil_new_addrinfo(sa, socklen, &tmp);
596 tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
597 r2 = evutil_new_addrinfo(sa, socklen, &tmp);
599 evutil_freeaddrinfo(r1);
606 /* We're going to allocate extra space to hold the sockaddr. */
607 res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
610 res->ai_addr = (struct sockaddr*)
611 (((char*)res) + sizeof(struct evutil_addrinfo));
612 memcpy(res->ai_addr, sa, socklen);
613 res->ai_addrlen = socklen;
614 res->ai_family = sa->sa_family; /* Same or not? XXX */
615 res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
616 res->ai_socktype = hints->ai_socktype;
617 res->ai_protocol = hints->ai_protocol;
622 /* Append the addrinfo 'append' to the end of 'first', and return the start of
623 * the list. Either element can be NULL, in which case we return the element
624 * that is not NULL. */
625 struct evutil_addrinfo *
626 evutil_addrinfo_append(struct evutil_addrinfo *first,
627 struct evutil_addrinfo *append)
629 struct evutil_addrinfo *ai = first;
634 ai->ai_next = append;
640 parse_numeric_servname(const char *servname)
644 n = (int) strtol(servname, &endptr, 10);
645 if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
651 /** Parse a service name in 'servname', which can be a decimal port.
652 * Return the port number, or -1 on error.
655 evutil_parse_servname(const char *servname, const char *protocol,
656 const struct evutil_addrinfo *hints)
658 int n = parse_numeric_servname(servname);
661 #if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(WIN32)
662 if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
663 struct servent *ent = getservbyname(servname, protocol);
665 return ntohs(ent->s_port);
672 /* Return a string corresponding to a protocol number that we can pass to
675 evutil_unparse_protoname(int proto)
689 #ifdef _EVENT_HAVE_GETPROTOBYNUMBER
691 struct protoent *ent = getprotobynumber(proto);
701 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
703 /* If we can guess the protocol from the socktype, do so. */
704 if (!hints->ai_protocol && hints->ai_socktype) {
705 if (hints->ai_socktype == SOCK_DGRAM)
706 hints->ai_protocol = IPPROTO_UDP;
707 else if (hints->ai_socktype == SOCK_STREAM)
708 hints->ai_protocol = IPPROTO_TCP;
711 /* Set the socktype if it isn't set. */
712 if (!hints->ai_socktype && hints->ai_protocol) {
713 if (hints->ai_protocol == IPPROTO_UDP)
714 hints->ai_socktype = SOCK_DGRAM;
715 else if (hints->ai_protocol == IPPROTO_TCP)
716 hints->ai_socktype = SOCK_STREAM;
718 else if (hints->ai_protocol == IPPROTO_SCTP)
719 hints->ai_socktype = SOCK_STREAM;
724 /** Implements the part of looking up hosts by name that's common to both
725 * the blocking and nonblocking resolver:
726 * - Adjust 'hints' to have a reasonable socktype and protocol.
727 * - Look up the port based on 'servname', and store it in *portnum,
728 * - Handle the nodename==NULL case
729 * - Handle some invalid arguments cases.
730 * - Handle the cases where nodename is an IPv4 or IPv6 address.
732 * If we need the resolver to look up the hostname, we return
733 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
734 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
735 * set *res as getaddrinfo would.
738 evutil_getaddrinfo_common(const char *nodename, const char *servname,
739 struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
744 if (nodename == NULL && servname == NULL)
745 return EVUTIL_EAI_NONAME;
747 /* We only understand 3 families */
748 if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
749 hints->ai_family != PF_INET6)
750 return EVUTIL_EAI_FAMILY;
752 evutil_getaddrinfo_infer_protocols(hints);
754 /* Look up the port number and protocol, if possible. */
755 pname = evutil_unparse_protoname(hints->ai_protocol);
757 /* XXXX We could look at the protocol we got back from
758 * getservbyname, but it doesn't seem too useful. */
759 port = evutil_parse_servname(servname, pname, hints);
761 return EVUTIL_EAI_NONAME;
765 /* If we have no node name, then we're supposed to bind to 'any' and
766 * connect to localhost. */
767 if (nodename == NULL) {
768 struct evutil_addrinfo *res4=NULL, *res6=NULL;
769 if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
770 struct sockaddr_in6 sin6;
771 memset(&sin6, 0, sizeof(sin6));
772 sin6.sin6_family = AF_INET6;
773 sin6.sin6_port = htons(port);
774 if (hints->ai_flags & AI_PASSIVE) {
778 sin6.sin6_addr.s6_addr[15] = 1;
780 res6 = evutil_new_addrinfo((struct sockaddr*)&sin6,
781 sizeof(sin6), hints);
783 return EVUTIL_EAI_MEMORY;
786 if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
787 struct sockaddr_in sin;
788 memset(&sin, 0, sizeof(sin));
789 sin.sin_family = AF_INET;
790 sin.sin_port = htons(port);
791 if (hints->ai_flags & AI_PASSIVE) {
792 /* Bind to 0.0.0.0 */
794 /* connect to 127.0.0.1 */
795 sin.sin_addr.s_addr = htonl(0x7f000001);
797 res4 = evutil_new_addrinfo((struct sockaddr*)&sin,
801 evutil_freeaddrinfo(res6);
802 return EVUTIL_EAI_MEMORY;
805 *res = evutil_addrinfo_append(res4, res6);
809 /* If we can, we should try to parse the hostname without resolving
812 if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
813 struct sockaddr_in6 sin6;
814 memset(&sin6, 0, sizeof(sin6));
815 if (1==evutil_inet_pton(AF_INET6, nodename, &sin6.sin6_addr)) {
816 /* Got an ipv6 address. */
817 sin6.sin6_family = AF_INET6;
818 sin6.sin6_port = htons(port);
819 *res = evutil_new_addrinfo((struct sockaddr*)&sin6,
820 sizeof(sin6), hints);
822 return EVUTIL_EAI_MEMORY;
828 if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
829 struct sockaddr_in sin;
830 memset(&sin, 0, sizeof(sin));
831 if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
832 /* Got an ipv6 address. */
833 sin.sin_family = AF_INET;
834 sin.sin_port = htons(port);
835 *res = evutil_new_addrinfo((struct sockaddr*)&sin,
838 return EVUTIL_EAI_MEMORY;
844 /* If we have reached this point, we definitely need to do a DNS
846 if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
847 /* If we're not allowed to do one, then say so. */
848 return EVUTIL_EAI_NONAME;
851 return EVUTIL_EAI_NEED_RESOLVE;
854 #ifdef _EVENT_HAVE_GETADDRINFO
855 #define USE_NATIVE_GETADDRINFO
858 #ifdef USE_NATIVE_GETADDRINFO
859 /* A mask of all the flags that we declare, so we can clear them before calling
860 * the native getaddrinfo */
861 static const unsigned int ALL_NONNATIVE_AI_FLAGS =
866 EVUTIL_AI_CANONNAME |
868 #ifndef AI_NUMERICHOST
869 EVUTIL_AI_NUMERICHOST |
871 #ifndef AI_NUMERICSERV
872 EVUTIL_AI_NUMERICSERV |
874 #ifndef AI_ADDRCONFIG
875 EVUTIL_AI_ADDRCONFIG |
883 EVUTIL_AI_LIBEVENT_ALLOCATED;
885 static const unsigned int ALL_NATIVE_AI_FLAGS =
892 #ifdef AI_NUMERICHOST
895 #ifdef AI_NUMERICSERV
910 #ifndef USE_NATIVE_GETADDRINFO
911 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
914 static struct evutil_addrinfo *
915 addrinfo_from_hostent(const struct hostent *ent,
916 int port, const struct evutil_addrinfo *hints)
919 struct sockaddr_in sin;
920 struct sockaddr_in6 sin6;
923 struct evutil_addrinfo *res=NULL, *ai;
926 if (ent->h_addrtype == PF_INET) {
927 memset(&sin, 0, sizeof(sin));
928 sin.sin_family = AF_INET;
929 sin.sin_port = htons(port);
930 sa = (struct sockaddr *)&sin;
931 socklen = sizeof(struct sockaddr_in);
932 addrp = &sin.sin_addr;
933 if (ent->h_length != sizeof(sin.sin_addr)) {
934 event_warnx("Weird h_length from gethostbyname");
937 } else if (ent->h_addrtype == PF_INET6) {
938 memset(&sin6, 0, sizeof(sin6));
939 sin6.sin6_family = AF_INET6;
940 sin6.sin6_port = htons(port);
941 sa = (struct sockaddr *)&sin6;
942 socklen = sizeof(struct sockaddr_in);
943 addrp = &sin6.sin6_addr;
944 if (ent->h_length != sizeof(sin6.sin6_addr)) {
945 event_warnx("Weird h_length from gethostbyname");
951 for (i = 0; ent->h_addr_list[i]; ++i) {
952 memcpy(addrp, ent->h_addr_list[i], ent->h_length);
953 ai = evutil_new_addrinfo(sa, socklen, hints);
955 evutil_freeaddrinfo(res);
958 res = evutil_addrinfo_append(res, ai);
961 if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name))
962 res->ai_canonname = mm_strdup(ent->h_name);
968 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
969 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
970 * that we'll only get addresses we could maybe connect to.
973 evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo *hints)
975 if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
977 if (hints->ai_family != PF_UNSPEC)
979 if (!have_checked_interfaces)
980 evutil_check_interfaces(0);
981 if (had_ipv4_address && !had_ipv6_address) {
982 hints->ai_family = PF_INET;
983 } else if (!had_ipv4_address && had_ipv6_address) {
984 hints->ai_family = PF_INET6;
988 #ifdef USE_NATIVE_GETADDRINFO
989 static int need_numeric_port_hack_=0;
990 static int need_socktype_protocol_hack_=0;
991 static int tested_for_getaddrinfo_hacks=0;
993 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
994 giving a numeric port without giving an ai_socktype was verboten.
995 We test for this so we can apply an appropriate workaround. If it
996 turns out that the bug is present, then:
998 - If nodename==NULL and servname is numeric, we build an answer
999 ourselves using evutil_getaddrinfo_common().
1001 - If nodename!=NULL and servname is numeric, then we set
1002 servname=NULL when calling getaddrinfo, and post-process the
1003 result to set the ports on it.
1005 We test for this bug at runtime, since otherwise we can't have the
1006 same binary run on multiple BSD versions.
1008 - Some versions of Solaris believe that it's nice to leave to protocol
1009 field set to 0. We test for this so we can apply an appropriate
1013 test_for_getaddrinfo_hacks(void)
1016 struct evutil_addrinfo *ai=NULL, *ai2=NULL;
1017 struct evutil_addrinfo hints;
1019 memset(&hints,0,sizeof(hints));
1020 hints.ai_family = PF_UNSPEC;
1022 #ifdef AI_NUMERICHOST
1025 #ifdef AI_NUMERICSERV
1029 r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
1030 hints.ai_socktype = SOCK_STREAM;
1031 r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
1032 if (r2 == 0 && r != 0) {
1033 need_numeric_port_hack_=1;
1035 if (ai2 && ai2->ai_protocol == 0) {
1036 need_socktype_protocol_hack_=1;
1043 tested_for_getaddrinfo_hacks=1;
1047 need_numeric_port_hack(void)
1049 if (!tested_for_getaddrinfo_hacks)
1050 test_for_getaddrinfo_hacks();
1051 return need_numeric_port_hack_;
1055 need_socktype_protocol_hack(void)
1057 if (!tested_for_getaddrinfo_hacks)
1058 test_for_getaddrinfo_hacks();
1059 return need_socktype_protocol_hack_;
1063 apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
1065 /* Now we run through the list and set the ports on all of the
1066 * results where ports would make sense. */
1067 for ( ; *ai; ai = &(*ai)->ai_next) {
1068 struct sockaddr *sa = (*ai)->ai_addr;
1069 if (sa && sa->sa_family == AF_INET) {
1070 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1071 sin->sin_port = htons(port);
1072 } else if (sa && sa->sa_family == AF_INET6) {
1073 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1074 sin6->sin6_port = htons(port);
1076 /* A numeric port makes no sense here; remove this one
1078 struct evutil_addrinfo *victim = *ai;
1079 *ai = victim->ai_next;
1080 victim->ai_next = NULL;
1081 freeaddrinfo(victim);
1087 apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
1089 struct evutil_addrinfo *ai_new;
1090 for (; ai; ai = ai->ai_next) {
1091 evutil_getaddrinfo_infer_protocols(ai);
1092 if (ai->ai_socktype || ai->ai_protocol)
1094 ai_new = mm_malloc(sizeof(*ai_new));
1095 memcpy(ai_new, ai, sizeof(*ai_new));
1096 ai->ai_socktype = SOCK_STREAM;
1097 ai->ai_protocol = IPPROTO_TCP;
1098 ai_new->ai_socktype = SOCK_DGRAM;
1099 ai_new->ai_protocol = IPPROTO_UDP;
1101 ai_new->ai_next = ai->ai_next;
1102 ai->ai_next = ai_new;
1108 evutil_getaddrinfo(const char *nodename, const char *servname,
1109 const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
1111 #ifdef USE_NATIVE_GETADDRINFO
1112 struct evutil_addrinfo hints;
1113 int portnum=-1, need_np_hack, err;
1116 memcpy(&hints, hints_in, sizeof(hints));
1118 memset(&hints, 0, sizeof(hints));
1119 hints.ai_family = PF_UNSPEC;
1122 #ifndef AI_ADDRCONFIG
1123 /* Not every system has AI_ADDRCONFIG, so fake it. */
1124 if (hints.ai_family == PF_UNSPEC &&
1125 (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
1126 evutil_adjust_hints_for_addrconfig(&hints);
1130 #ifndef AI_NUMERICSERV
1131 /* Not every system has AI_NUMERICSERV, so fake it. */
1132 if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
1133 if (servname && parse_numeric_servname(servname)<0)
1134 return EVUTIL_EAI_NONAME;
1138 /* Enough operating systems handle enough common non-resolve
1139 * cases here weirdly enough that we are better off just
1140 * overriding them. For example:
1142 * - Windows doesn't like to infer the protocol from the
1143 * socket type, or fill in socket or protocol types much at
1144 * all. It also seems to do its own broken implicit
1145 * always-on version of AI_ADDRCONFIG that keeps it from
1146 * ever resolving even a literal IPv6 address when
1147 * ai_addrtype is PF_UNSPEC.
1152 err = evutil_getaddrinfo_common(nodename,servname,&hints,
1155 err == EVUTIL_EAI_MEMORY ||
1156 err == EVUTIL_EAI_NONAME)
1158 /* If we make it here, the system getaddrinfo can
1159 * have a crack at it. */
1163 /* See documentation for need_numeric_port_hack above.*/
1164 need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
1165 && ((portnum=parse_numeric_servname(servname)) >= 0);
1168 return evutil_getaddrinfo_common(
1169 NULL,servname,&hints, res, &portnum);
1173 if (need_socktype_protocol_hack()) {
1174 evutil_getaddrinfo_infer_protocols(&hints);
1177 /* Make sure that we didn't actually steal any AI_FLAGS values that
1178 * the system is using. (This is a constant expression, and should ge
1181 * XXXX Turn this into a compile-time failure rather than a run-time
1184 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
1186 /* Clear any flags that only libevent understands. */
1187 hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
1189 err = getaddrinfo(nodename, servname, &hints, res);
1191 apply_numeric_port_hack(portnum, res);
1193 if (need_socktype_protocol_hack()) {
1194 apply_socktype_protocol_hack(*res);
1199 struct hostent *ent = NULL;
1200 struct evutil_addrinfo hints;
1203 memcpy(&hints, hints_in, sizeof(hints));
1205 memset(&hints, 0, sizeof(hints));
1206 hints.ai_family = PF_UNSPEC;
1209 evutil_adjust_hints_for_addrconfig(&hints);
1211 err = evutil_getaddrinfo_common(nodename, servname, &hints, res, &port);
1212 if (err != EVUTIL_EAI_NEED_RESOLVE) {
1213 /* We either succeeded or failed. No need to continue */
1218 /* Use any of the various gethostbyname_r variants as available. */
1220 #ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
1221 /* This one is what glibc provides. */
1223 struct hostent hostent;
1225 r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
1227 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
1229 struct hostent hostent;
1230 ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
1232 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_3_ARG)
1233 struct hostent_data data;
1234 struct hostent hostent;
1235 memset(&data, 0, sizeof(data));
1236 err = gethostbyname_r(nodename, &hostent, &data);
1237 ent = err ? NULL : &hostent;
1239 /* fall back to gethostbyname. */
1240 /* XXXX This needs a lock everywhere but Windows. */
1241 ent = gethostbyname(nodename);
1243 err = WSAGetLastError();
1249 /* Now we have either ent or err set. */
1251 /* XXX is this right for windows ? */
1254 return EVUTIL_EAI_AGAIN;
1257 return EVUTIL_EAI_FAIL;
1258 case HOST_NOT_FOUND:
1259 return EVUTIL_EAI_NONAME;
1261 #if NO_DATA != NO_ADDRESS
1264 return EVUTIL_EAI_NODATA;
1268 if (ent->h_addrtype != hints.ai_family &&
1269 hints.ai_family != PF_UNSPEC) {
1270 /* This wasn't the type we were hoping for. Too bad
1271 * we never had a chance to ask gethostbyname for what
1273 return EVUTIL_EAI_NONAME;
1276 /* Make sure we got _some_ answers. */
1277 if (ent->h_length == 0)
1278 return EVUTIL_EAI_NODATA;
1280 /* If we got an address type we don't know how to make a
1281 sockaddr for, give up. */
1282 if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
1283 return EVUTIL_EAI_FAMILY;
1285 *res = addrinfo_from_hostent(ent, port, &hints);
1287 return EVUTIL_EAI_MEMORY;
1295 evutil_freeaddrinfo(struct evutil_addrinfo *ai)
1297 #ifdef _EVENT_HAVE_GETADDRINFO
1298 if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
1304 struct evutil_addrinfo *next = ai->ai_next;
1305 if (ai->ai_canonname)
1306 mm_free(ai->ai_canonname);
1312 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
1315 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn)
1317 if (!evdns_getaddrinfo_impl)
1318 evdns_getaddrinfo_impl = fn;
1321 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1322 * otherwise do a blocking resolve and pass the result to the callback in the
1323 * way that evdns_getaddrinfo would.
1326 evutil_getaddrinfo_async(struct evdns_base *dns_base,
1327 const char *nodename, const char *servname,
1328 const struct evutil_addrinfo *hints_in,
1329 void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
1331 if (dns_base && evdns_getaddrinfo_impl) {
1332 evdns_getaddrinfo_impl(
1333 dns_base, nodename, servname, hints_in, cb, arg);
1335 struct evutil_addrinfo *ai=NULL;
1337 err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
1344 evutil_gai_strerror(int err)
1346 /* As a sneaky side-benefit, this case statement will get most
1347 * compilers to tell us if any of the error codes we defined
1348 * conflict with the platform's native error codes. */
1350 case EVUTIL_EAI_CANCEL:
1351 return "Request canceled";
1355 case EVUTIL_EAI_ADDRFAMILY:
1356 return "address family for nodename not supported";
1357 case EVUTIL_EAI_AGAIN:
1358 return "temporary failure in name resolution";
1359 case EVUTIL_EAI_BADFLAGS:
1360 return "invalid value for ai_flags";
1361 case EVUTIL_EAI_FAIL:
1362 return "non-recoverable failure in name resolution";
1363 case EVUTIL_EAI_FAMILY:
1364 return "ai_family not supported";
1365 case EVUTIL_EAI_MEMORY:
1366 return "memory allocation failure";
1367 case EVUTIL_EAI_NODATA:
1368 return "no address associated with nodename";
1369 case EVUTIL_EAI_NONAME:
1370 return "nodename nor servname provided, or not known";
1371 case EVUTIL_EAI_SERVICE:
1372 return "servname not supported for ai_socktype";
1373 case EVUTIL_EAI_SOCKTYPE:
1374 return "ai_socktype not supported";
1375 case EVUTIL_EAI_SYSTEM:
1376 return "system error";
1378 #if defined(USE_NATIVE_GETADDRINFO) && defined(WIN32)
1379 return gai_strerrorA(err);
1380 #elif defined(USE_NATIVE_GETADDRINFO)
1381 return gai_strerror(err);
1383 return "Unknown error code";
1389 #define E(code, s) { code, (s " [" #code " ]") }
1390 static struct { int code; const char *msg; } windows_socket_errors[] = {
1391 E(WSAEINTR, "Interrupted function call"),
1392 E(WSAEACCES, "Permission denied"),
1393 E(WSAEFAULT, "Bad address"),
1394 E(WSAEINVAL, "Invalid argument"),
1395 E(WSAEMFILE, "Too many open files"),
1396 E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
1397 E(WSAEINPROGRESS, "Operation now in progress"),
1398 E(WSAEALREADY, "Operation already in progress"),
1399 E(WSAENOTSOCK, "Socket operation on nonsocket"),
1400 E(WSAEDESTADDRREQ, "Destination address required"),
1401 E(WSAEMSGSIZE, "Message too long"),
1402 E(WSAEPROTOTYPE, "Protocol wrong for socket"),
1403 E(WSAENOPROTOOPT, "Bad protocol option"),
1404 E(WSAEPROTONOSUPPORT, "Protocol not supported"),
1405 E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
1406 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
1407 E(WSAEOPNOTSUPP, "Operation not supported"),
1408 E(WSAEPFNOSUPPORT, "Protocol family not supported"),
1409 E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
1410 E(WSAEADDRINUSE, "Address already in use"),
1411 E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
1412 E(WSAENETDOWN, "Network is down"),
1413 E(WSAENETUNREACH, "Network is unreachable"),
1414 E(WSAENETRESET, "Network dropped connection on reset"),
1415 E(WSAECONNABORTED, "Software caused connection abort"),
1416 E(WSAECONNRESET, "Connection reset by peer"),
1417 E(WSAENOBUFS, "No buffer space available"),
1418 E(WSAEISCONN, "Socket is already connected"),
1419 E(WSAENOTCONN, "Socket is not connected"),
1420 E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
1421 E(WSAETIMEDOUT, "Connection timed out"),
1422 E(WSAECONNREFUSED, "Connection refused"),
1423 E(WSAEHOSTDOWN, "Host is down"),
1424 E(WSAEHOSTUNREACH, "No route to host"),
1425 E(WSAEPROCLIM, "Too many processes"),
1427 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
1428 E(WSASYSNOTREADY, "Network subsystem is unavailable"),
1429 E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
1430 E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
1431 E(WSAEDISCON, "Graceful shutdown now in progress"),
1432 #ifdef WSATYPE_NOT_FOUND
1433 E(WSATYPE_NOT_FOUND, "Class type not found"),
1435 E(WSAHOST_NOT_FOUND, "Host not found"),
1436 E(WSATRY_AGAIN, "Nonauthoritative host not found"),
1437 E(WSANO_RECOVERY, "This is a nonrecoverable error"),
1438 E(WSANO_DATA, "Valid name, no data record of requested type)"),
1440 /* There are some more error codes whose numeric values are marked
1441 * <b>OS dependent</b>. They start with WSA_, apparently for the same
1442 * reason that practitioners of some craft traditions deliberately
1443 * introduce imperfections into their baskets and rugs "to allow the
1444 * evil spirits to escape." If we catch them, then our binaries
1445 * might not report consistent results across versions of Windows.
1446 * Thus, I'm going to let them all fall through.
1451 /** Equivalent to strerror, but for windows socket errors. */
1453 evutil_socket_error_to_string(int errcode)
1455 /* XXXX Is there really no built-in function to do this? */
1457 for (i=0; windows_socket_errors[i].code >= 0; ++i) {
1458 if (errcode == windows_socket_errors[i].code)
1459 return windows_socket_errors[i].msg;
1461 return strerror(errcode);
1466 evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
1470 va_start(ap, format);
1471 r = evutil_vsnprintf(buf, buflen, format, ap);
1477 evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
1483 r = _vsnprintf(buf, buflen, format, ap);
1485 r = _vscprintf(format, ap);
1487 /* Make sure we always use the correct vsnprintf on IRIX */
1488 extern int _xpg5_vsnprintf(char * __restrict,
1489 __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
1490 const char * __restrict, /* va_list */ char *);
1492 r = _xpg5_vsnprintf(buf, buflen, format, ap);
1494 r = vsnprintf(buf, buflen, format, ap);
1496 buf[buflen-1] = '\0';
1500 #define USE_INTERNAL_NTOP
1501 #define USE_INTERNAL_PTON
1504 evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
1506 #if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1507 return inet_ntop(af, src, dst, len);
1509 if (af == AF_INET) {
1510 const struct in_addr *in = src;
1511 const ev_uint32_t a = ntohl(in->s_addr);
1513 r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
1514 (int)(ev_uint8_t)((a>>24)&0xff),
1515 (int)(ev_uint8_t)((a>>16)&0xff),
1516 (int)(ev_uint8_t)((a>>8 )&0xff),
1517 (int)(ev_uint8_t)((a )&0xff));
1518 if (r<0||(size_t)r>=len)
1523 } else if (af == AF_INET6) {
1524 const struct in6_addr *addr = src;
1526 int longestGapLen = 0, longestGapPos = -1, i,
1527 curGapPos = -1, curGapLen = 0;
1528 ev_uint16_t words[8];
1529 for (i = 0; i < 8; ++i) {
1531 (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
1533 if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
1534 words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
1535 (words[5] == 0xffff))) {
1536 /* This is an IPv4 address. */
1537 if (words[5] == 0) {
1538 evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
1539 addr->s6_addr[12], addr->s6_addr[13],
1540 addr->s6_addr[14], addr->s6_addr[15]);
1542 evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
1543 addr->s6_addr[12], addr->s6_addr[13],
1544 addr->s6_addr[14], addr->s6_addr[15]);
1546 if (strlen(buf) > len)
1548 strlcpy(dst, buf, len);
1553 if (words[i] == 0) {
1556 while (i<8 && words[i] == 0) {
1559 if (curGapLen > longestGapLen) {
1560 longestGapPos = curGapPos;
1561 longestGapLen = curGapLen;
1567 if (longestGapLen<=1)
1571 for (i = 0; i < 8; ++i) {
1572 if (words[i] == 0 && longestGapPos == i) {
1576 while (i < 8 && words[i] == 0)
1578 --i; /* to compensate for loop increment. */
1581 sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
1588 if (strlen(buf) > len)
1590 strlcpy(dst, buf, len);
1600 evutil_inet_pton(int af, const char *src, void *dst)
1602 #if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1603 return inet_pton(af, src, dst);
1605 if (af == AF_INET) {
1608 struct in_addr *addr = dst;
1609 if (sscanf(src, "%d.%d.%d.%d%c", &a,&b,&c,&d,&more) != 4)
1611 if (a < 0 || a > 255) return 0;
1612 if (b < 0 || b > 255) return 0;
1613 if (c < 0 || c > 255) return 0;
1614 if (d < 0 || d > 255) return 0;
1615 addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
1618 } else if (af == AF_INET6) {
1619 struct in6_addr *out = dst;
1620 ev_uint16_t words[8];
1621 int gapPos = -1, i, setWords=0;
1622 const char *dot = strchr(src, '.');
1623 const char *eow; /* end of words. */
1627 eow = src+strlen(src);
1629 int byte1,byte2,byte3,byte4;
1631 for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT(*eow); --eow)
1635 /* We use "scanf" because some platform inet_aton()s are too lax
1636 * about IPv4 addresses of the form "1.2.3" */
1637 if (sscanf(eow, "%d.%d.%d.%d%c",
1638 &byte1,&byte2,&byte3,&byte4,&more) != 4)
1641 if (byte1 > 255 || byte1 < 0 ||
1642 byte2 > 255 || byte2 < 0 ||
1643 byte3 > 255 || byte3 < 0 ||
1644 byte4 > 255 || byte4 < 0)
1647 words[6] = (byte1<<8) | byte2;
1648 words[7] = (byte3<<8) | byte4;
1656 if (EVUTIL_ISXDIGIT(*src)) {
1658 long r = strtol(src, &next, 16);
1666 words[i++] = (ev_uint16_t)r;
1669 if (*src != ':' && src != eow)
1672 } else if (*src == ':' && i > 0 && gapPos==-1) {
1675 } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
1684 (setWords == 8 && gapPos != -1) ||
1685 (setWords < 8 && gapPos == -1))
1689 int nToMove = setWords - (dot ? 2 : 0) - gapPos;
1690 int gapLen = 8 - setWords;
1691 /* assert(nToMove >= 0); */
1693 return -1; /* should be impossible */
1694 memmove(&words[gapPos+gapLen], &words[gapPos],
1695 sizeof(ev_uint16_t)*nToMove);
1696 memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
1698 for (i = 0; i < 8; ++i) {
1699 out->s6_addr[2*i ] = words[i] >> 8;
1700 out->s6_addr[2*i+1] = words[i] & 0xff;
1712 evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
1716 const char *cp, *addr_part, *port_part;
1718 /* recognized formats are:
1726 cp = strchr(ip_as_string, ':');
1727 if (*ip_as_string == '[') {
1729 if (!(cp = strchr(ip_as_string, ']'))) {
1732 len = (int) ( cp-(ip_as_string + 1) );
1733 if (len > (int)sizeof(buf)-1) {
1736 memcpy(buf, ip_as_string+1, len);
1744 } else if (cp && strchr(cp+1, ':')) {
1746 addr_part = ip_as_string;
1750 if (cp - ip_as_string > (int)sizeof(buf)-1) {
1753 memcpy(buf, ip_as_string, cp-ip_as_string);
1754 buf[cp-ip_as_string] = '\0';
1758 addr_part = ip_as_string;
1763 if (port_part == NULL) {
1766 port = atoi(port_part);
1767 if (port <= 0 || port > 65535) {
1773 return -1; /* Should be impossible. */
1777 struct sockaddr_in6 sin6;
1778 memset(&sin6, 0, sizeof(sin6));
1779 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
1780 sin6.sin6_len = sizeof(sin6);
1782 sin6.sin6_family = AF_INET6;
1783 sin6.sin6_port = htons(port);
1784 if (1 != evutil_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr))
1786 if ((int)sizeof(sin6) > *outlen)
1788 memset(out, 0, *outlen);
1789 memcpy(out, &sin6, sizeof(sin6));
1790 *outlen = sizeof(sin6);
1796 struct sockaddr_in sin;
1797 memset(&sin, 0, sizeof(sin));
1798 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
1799 sin.sin_len = sizeof(sin);
1801 sin.sin_family = AF_INET;
1802 sin.sin_port = htons(port);
1803 if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
1805 if ((int)sizeof(sin) > *outlen)
1807 memset(out, 0, *outlen);
1808 memcpy(out, &sin, sizeof(sin));
1809 *outlen = sizeof(sin);
1815 evutil_format_sockaddr_port(const struct sockaddr *sa, char *out, size_t outlen)
1818 const char *res=NULL;
1820 if (sa->sa_family == AF_INET) {
1821 const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
1822 res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
1823 port = ntohs(sin->sin_port);
1825 evutil_snprintf(out, outlen, "%s:%d", b, port);
1828 } else if (sa->sa_family == AF_INET6) {
1829 const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
1830 res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
1831 port = ntohs(sin6->sin6_port);
1833 evutil_snprintf(out, outlen, "[%s]:%d", b, port);
1838 evutil_snprintf(out, outlen, "<addr with socktype %d>",
1839 (int)sa->sa_family);
1844 evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
1848 if (0 != (r = (sa1->sa_family - sa2->sa_family)))
1851 if (sa1->sa_family == AF_INET) {
1852 const struct sockaddr_in *sin1, *sin2;
1853 sin1 = (const struct sockaddr_in *)sa1;
1854 sin2 = (const struct sockaddr_in *)sa2;
1855 if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
1857 else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
1859 else if (include_port &&
1860 (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
1866 else if (sa1->sa_family == AF_INET6) {
1867 const struct sockaddr_in6 *sin1, *sin2;
1868 sin1 = (const struct sockaddr_in6 *)sa1;
1869 sin2 = (const struct sockaddr_in6 *)sa2;
1870 if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
1872 else if (include_port &&
1873 (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
1882 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
1883 * has 256 bits to look up whether a character is in some set or not. This
1884 * fails on non-ASCII platforms, but so does every other place where we
1885 * take a char and write it onto the network.
1887 static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
1888 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
1889 static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
1890 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
1891 static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
1892 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
1893 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
1894 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
1895 static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
1896 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
1897 static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
1898 static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
1899 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
1901 static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
1902 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1903 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1904 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
1905 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
1906 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
1907 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
1908 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
1909 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
1910 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
1911 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
1912 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
1913 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
1914 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
1915 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
1916 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
1917 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
1919 static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
1920 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1921 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1922 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
1923 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
1924 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
1925 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
1926 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
1927 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
1928 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
1929 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
1930 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
1931 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
1932 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
1933 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
1934 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
1935 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
1938 #define IMPL_CTYPE_FN(name) \
1939 int EVUTIL_##name(char c) { \
1941 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
1943 IMPL_CTYPE_FN(ISALPHA)
1944 IMPL_CTYPE_FN(ISALNUM)
1945 IMPL_CTYPE_FN(ISSPACE)
1946 IMPL_CTYPE_FN(ISDIGIT)
1947 IMPL_CTYPE_FN(ISXDIGIT)
1948 IMPL_CTYPE_FN(ISPRINT)
1949 IMPL_CTYPE_FN(ISLOWER)
1950 IMPL_CTYPE_FN(ISUPPER)
1952 char EVUTIL_TOLOWER(char c)
1954 return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
1956 char EVUTIL_TOUPPER(char c)
1958 return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
1961 evutil_ascii_strcasecmp(const char *s1, const char *s2)
1965 c1 = EVUTIL_TOLOWER(*s1++);
1966 c2 = EVUTIL_TOLOWER(*s2++);
1975 int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
1979 c1 = EVUTIL_TOLOWER(*s1++);
1980 c2 = EVUTIL_TOLOWER(*s2++);
1992 evutil_issetugid(void)
1994 #ifdef _EVENT_HAVE_ISSETUGID
1998 #ifdef _EVENT_HAVE_GETEUID
1999 if (getuid() != geteuid())
2002 #ifdef _EVENT_HAVE_GETEGID
2003 if (getgid() != getegid())
2011 evutil_getenv(const char *varname)
2013 if (evutil_issetugid())
2016 return getenv(varname);
2020 _evutil_weakrand(void)
2030 evutil_sockaddr_is_loopback(const struct sockaddr *addr)
2032 static const char LOOPBACK_S6[16] =
2033 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2034 if (addr->sa_family == AF_INET) {
2035 struct sockaddr_in *sin = (struct sockaddr_in *)addr;
2036 return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
2037 } else if (addr->sa_family == AF_INET6) {
2038 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
2039 return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
2044 #define MAX_SECONDS_IN_MSEC_LONG \
2045 (((LONG_MAX) - 999) / 1000)
2048 evutil_tv_to_msec(const struct timeval *tv)
2050 if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
2053 return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
2057 evutil_hex_char_to_int(char c)
2071 case 'A': case 'a': return 10;
2072 case 'B': case 'b': return 11;
2073 case 'C': case 'c': return 12;
2074 case 'D': case 'd': return 13;
2075 case 'E': case 'e': return 14;
2076 case 'F': case 'f': return 15;
2083 evutil_load_windows_system_library(const TCHAR *library_name)
2085 TCHAR path[MAX_PATH];
2087 n = GetSystemDirectory(path, MAX_PATH);
2088 if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
2090 _tcscat(path, TEXT("\\"));
2091 _tcscat(path, library_name);
2092 return LoadLibrary(path);