1 /* $NetBSD: evutil.c,v 1.5 2015/01/29 07:26:02 spz Exp $ */
3 * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "event2/event-config.h"
29 #include <sys/cdefs.h>
30 __RCSID("$NetBSD: evutil.c,v 1.5 2015/01/29 07:26:02 spz Exp $");
37 #define WIN32_LEAN_AND_MEAN
39 #undef WIN32_LEAN_AND_MEAN
44 #include <sys/types.h>
45 #ifdef _EVENT_HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
48 #ifdef _EVENT_HAVE_UNISTD_H
51 #ifdef _EVENT_HAVE_FCNTL_H
54 #ifdef _EVENT_HAVE_STDLIB_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>
67 #ifdef _EVENT_HAVE_ARPA_INET_H
68 #include <arpa/inet.h>
71 #ifndef _EVENT_HAVE_GETTIMEOFDAY
72 #include <sys/timeb.h>
77 #include "event2/util.h"
78 #include "util-internal.h"
79 #include "log-internal.h"
80 #include "mm-internal.h"
82 #include "strlcpy-internal.h"
83 #include "ipv6-internal.h"
89 #define fstat _fstati64
95 evutil_open_closeonexec(const char *pathname
, int flags
, unsigned mode
)
104 fd
= open(pathname
, flags
, (mode_t
)mode
);
106 fd
= open(pathname
, flags
);
110 #if !defined(O_CLOEXEC) && defined(FD_CLOEXEC)
111 if (fcntl(fd
, F_SETFD
, FD_CLOEXEC
) < 0)
119 Read the contents of 'filename' into a newly allocated NUL-terminated
120 string. Set *content_out to hold this string, and *len_out to hold its
121 length (not including the appended NUL). If 'is_binary', open the file in
124 Returns 0 on success, -1 if the open fails, and -2 for all other failures.
126 Used internally only; may go away in a future version.
129 evutil_read_file(const char *filename
, char **content_out
, size_t *len_out
,
135 size_t read_so_far
=0;
138 EVUTIL_ASSERT(content_out
);
139 EVUTIL_ASSERT(len_out
);
148 fd
= evutil_open_closeonexec(filename
, mode
, 0);
151 if (fstat(fd
, &st
) || st
.st_size
< 0 ||
152 st
.st_size
> EV_SSIZE_MAX
-1 ) {
156 mem
= mm_malloc((size_t)st
.st_size
+ 1);
163 #define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
165 #define N_TO_READ(x) (x)
167 while ((r
= read(fd
, mem
+read_so_far
, N_TO_READ(st
.st_size
- read_so_far
))) > 0) {
169 if (read_so_far
>= (size_t)st
.st_size
)
171 EVUTIL_ASSERT(read_so_far
< (size_t)st
.st_size
);
178 mem
[read_so_far
] = 0;
180 *len_out
= read_so_far
;
186 evutil_socketpair(int family
, int type
, int protocol
, evutil_socket_t fd
[2])
189 return socketpair(family
, type
, protocol
, fd
);
191 return evutil_ersatz_socketpair(family
, type
, protocol
, fd
);
196 evutil_ersatz_socketpair(int family
, int type
, int protocol
,
197 evutil_socket_t fd
[2])
199 /* This code is originally from Tor. Used with permission. */
201 /* This socketpair does not work when localhost is down. So
202 * it's really not the same thing at all. But it's close enough
203 * for now, and really, when localhost is down sometimes, we
204 * have other problems too.
207 #define ERR(e) WSA##e
211 evutil_socket_t listener
= -1;
212 evutil_socket_t connector
= -1;
213 evutil_socket_t acceptor
= -1;
214 struct sockaddr_in listen_addr
;
215 struct sockaddr_in connect_addr
;
217 int saved_errno
= -1;
220 || (family
!= AF_INET
225 EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT
));
229 EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL
));
233 listener
= socket(AF_INET
, type
, 0);
236 memset(&listen_addr
, 0, sizeof(listen_addr
));
237 listen_addr
.sin_family
= AF_INET
;
238 listen_addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
239 listen_addr
.sin_port
= 0; /* kernel chooses port. */
240 if (bind(listener
, (struct sockaddr
*) &listen_addr
, sizeof (listen_addr
))
242 goto tidy_up_and_fail
;
243 if (listen(listener
, 1) == -1)
244 goto tidy_up_and_fail
;
246 connector
= socket(AF_INET
, type
, 0);
248 goto tidy_up_and_fail
;
249 /* We want to find out the port number to connect to. */
250 size
= sizeof(connect_addr
);
251 if (getsockname(listener
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
252 goto tidy_up_and_fail
;
253 if (size
!= sizeof (connect_addr
))
254 goto abort_tidy_up_and_fail
;
255 if (connect(connector
, (struct sockaddr
*) &connect_addr
,
256 sizeof(connect_addr
)) == -1)
257 goto tidy_up_and_fail
;
259 size
= sizeof(listen_addr
);
260 acceptor
= accept(listener
, (struct sockaddr
*) &listen_addr
, &size
);
262 goto tidy_up_and_fail
;
263 if (size
!= sizeof(listen_addr
))
264 goto abort_tidy_up_and_fail
;
265 /* Now check we are talking to ourself by matching port and host on the
267 if (getsockname(connector
, (struct sockaddr
*) &connect_addr
, &size
) == -1)
268 goto tidy_up_and_fail
;
269 if (size
!= sizeof (connect_addr
)
270 || listen_addr
.sin_family
!= connect_addr
.sin_family
271 || listen_addr
.sin_addr
.s_addr
!= connect_addr
.sin_addr
.s_addr
272 || listen_addr
.sin_port
!= connect_addr
.sin_port
)
273 goto abort_tidy_up_and_fail
;
274 evutil_closesocket(listener
);
280 abort_tidy_up_and_fail
:
281 saved_errno
= ERR(ECONNABORTED
);
284 saved_errno
= EVUTIL_SOCKET_ERROR();
286 evutil_closesocket(listener
);
288 evutil_closesocket(connector
);
290 evutil_closesocket(acceptor
);
292 EVUTIL_SET_SOCKET_ERROR(saved_errno
);
298 evutil_make_socket_nonblocking(evutil_socket_t fd
)
302 u_long nonblocking
= 1;
303 if (ioctlsocket(fd
, FIONBIO
, &nonblocking
) == SOCKET_ERROR
) {
304 event_sock_warn(fd
, "fcntl(%d, F_GETFL)", (int)fd
);
311 if ((flags
= fcntl(fd
, F_GETFL
, NULL
)) < 0) {
312 event_warn("fcntl(%d, F_GETFL)", fd
);
315 if (fcntl(fd
, F_SETFL
, flags
| O_NONBLOCK
) == -1) {
316 event_warn("fcntl(%d, F_SETFL)", fd
);
325 evutil_make_listen_socket_reuseable(evutil_socket_t sock
)
329 /* REUSEADDR on Unix means, "don't hang on to this address after the
330 * listener is closed." On Windows, though, it means "don't keep other
331 * processes from binding to this address while we're using it. */
332 return setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void*) &one
,
333 (ev_socklen_t
)sizeof(one
));
340 evutil_make_socket_closeonexec(evutil_socket_t fd
)
342 #if !defined(WIN32) && defined(_EVENT_HAVE_SETFD)
344 if ((flags
= fcntl(fd
, F_GETFD
, NULL
)) < 0) {
345 event_warn("fcntl(%d, F_GETFD)", fd
);
348 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) == -1) {
349 event_warn("fcntl(%d, F_SETFD)", fd
);
357 evutil_closesocket(evutil_socket_t sock
)
362 return closesocket(sock
);
367 evutil_strtoll(const char *s
, char **endptr
, int base
)
369 #ifdef _EVENT_HAVE_STRTOLL
370 return (ev_int64_t
)strtoll(s
, endptr
, base
);
371 #elif _EVENT_SIZEOF_LONG == 8
372 return (ev_int64_t
)strtol(s
, endptr
, base
);
373 #elif defined(WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
374 /* XXXX on old versions of MS APIs, we only support base
379 r
= (ev_int64_t
) _atoi64(s
);
390 return (ev_int64_t
) _strtoi64(s
, endptr
, base
);
391 #elif defined(_EVENT_SIZEOF_LONG_LONG) && _EVENT_SIZEOF_LONG_LONG == 8
394 if (base
!= 10 && base
!= 16)
397 n
= sscanf(s
, "%lld", &r
);
399 unsigned long long ru
=0;
400 n
= sscanf(s
, "%llx", &ru
);
401 if (ru
> EV_INT64_MAX
)
407 while (EVUTIL_ISSPACE(*s
))
412 while (EVUTIL_ISDIGIT(*s
))
415 while (EVUTIL_ISXDIGIT(*s
))
422 #error "I don't know how to parse 64-bit integers."
426 #ifndef _EVENT_HAVE_GETTIMEOFDAY
427 /* No gettimeofday; this muse be windows. */
429 evutil_gettimeofday(struct timeval
*tv
, struct timezone
*tz
)
437 * _ftime is not the greatest interface here; GetSystemTimeAsFileTime
438 * would give us better resolution, whereas something cobbled together
439 * with GetTickCount could maybe give us monotonic behavior.
441 * Either way, I think this value might be skewed to ignore the
442 * timezone, and just return local time. That's not so good.
445 tv
->tv_sec
= (long) tb
.time
;
446 tv
->tv_usec
= ((int) tb
.millitm
) * 1000;
453 evutil_socket_geterror(evutil_socket_t sock
)
455 int optval
, optvallen
=sizeof(optval
);
456 int err
= WSAGetLastError();
457 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
458 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
,
468 /* XXX we should use an enum here. */
469 /* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
471 evutil_socket_connect(evutil_socket_t
*fd_ptr
, struct sockaddr
*sa
, int socklen
)
476 if ((*fd_ptr
= socket(sa
->sa_family
, SOCK_STREAM
, 0)) < 0)
479 if (evutil_make_socket_nonblocking(*fd_ptr
) < 0) {
484 if (connect(*fd_ptr
, sa
, socklen
) < 0) {
485 int e
= evutil_socket_geterror(*fd_ptr
);
486 if (EVUTIL_ERR_CONNECT_RETRIABLE(e
))
488 if (EVUTIL_ERR_CONNECT_REFUSED(e
))
497 evutil_closesocket(*fd_ptr
);
503 /* Check whether a socket on which we called connect() is done
504 connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
505 error case, set the current socket errno to the error that happened during
506 the connect operation. */
508 evutil_socket_finished_connecting(evutil_socket_t fd
)
511 ev_socklen_t elen
= sizeof(e
);
513 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, (void*)&e
, &elen
) < 0)
517 if (EVUTIL_ERR_CONNECT_RETRIABLE(e
))
519 EVUTIL_SET_SOCKET_ERROR(e
);
526 #if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
527 EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
528 EVUTIL_AI_ADDRCONFIG) != \
529 (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
530 EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
531 EVUTIL_AI_ADDRCONFIG)
532 #error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
535 /* We sometimes need to know whether we have an ipv4 address and whether we
536 have an ipv6 address. If 'have_checked_interfaces', then we've already done
537 the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
538 If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
539 set by evutil_check_interfaces. */
540 static int have_checked_interfaces
, had_ipv4_address
, had_ipv6_address
;
542 /* Macro: True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8
544 #define EVUTIL_V4ADDR_IS_LOCALHOST(addr) (((addr)>>24) == 127)
546 /* Macro: True iff the IPv4 address 'addr', in host order, is a class D
547 * (multiclass) address.
549 #define EVUTIL_V4ADDR_IS_CLASSD(addr) ((((addr)>>24) & 0xf0) == 0xe0)
551 /* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
552 * the test seemed successful. */
554 evutil_check_interfaces(int force_recheck
)
556 const char ZEROES
[] = "\x00\x00\x00\x00\x00\x00\x00\x00"
557 "\x00\x00\x00\x00\x00\x00\x00\x00";
558 evutil_socket_t fd
= -1;
559 struct sockaddr_in sin
, sin_out
;
560 struct sockaddr_in6 sin6
, sin6_out
;
561 ev_socklen_t sin_out_len
= sizeof(sin_out
);
562 ev_socklen_t sin6_out_len
= sizeof(sin6_out
);
565 if (have_checked_interfaces
&& !force_recheck
)
568 /* To check whether we have an interface open for a given protocol, we
569 * try to make a UDP 'connection' to a remote host on the internet.
570 * We don't actually use it, so the address doesn't matter, but we
571 * want to pick one that keep us from using a host- or link-local
573 memset(&sin
, 0, sizeof(sin
));
574 sin
.sin_family
= AF_INET
;
575 sin
.sin_port
= htons(53);
576 r
= evutil_inet_pton(AF_INET
, "18.244.0.188", &sin
.sin_addr
);
579 memset(&sin6
, 0, sizeof(sin6
));
580 sin6
.sin6_family
= AF_INET6
;
581 sin6
.sin6_port
= htons(53);
582 r
= evutil_inet_pton(AF_INET6
, "2001:4860:b002::68", &sin6
.sin6_addr
);
585 memset(&sin_out
, 0, sizeof(sin_out
));
586 memset(&sin6_out
, 0, sizeof(sin6_out
));
588 /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
589 if ((fd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
)) >= 0 &&
590 connect(fd
, (struct sockaddr
*)&sin
, sizeof(sin
)) == 0 &&
591 getsockname(fd
, (struct sockaddr
*)&sin_out
, &sin_out_len
) == 0) {
592 /* We might have an IPv4 interface. */
593 ev_uint32_t addr
= ntohl(sin_out
.sin_addr
.s_addr
);
595 EVUTIL_V4ADDR_IS_LOCALHOST(addr
) ||
596 EVUTIL_V4ADDR_IS_CLASSD(addr
)) {
597 evutil_inet_ntop(AF_INET
, &sin_out
.sin_addr
,
599 /* This is a reserved, ipv4compat, ipv4map, loopback,
600 * link-local or unspecified address. The host should
601 * never have given it to us; it could never connect
603 event_warnx("Got a strange local ipv4 address %s",buf
);
605 event_debug(("Detected an IPv4 interface"));
606 had_ipv4_address
= 1;
610 evutil_closesocket(fd
);
612 if ((fd
= socket(AF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
)) >= 0 &&
613 connect(fd
, (struct sockaddr
*)&sin6
, sizeof(sin6
)) == 0 &&
614 getsockname(fd
, (struct sockaddr
*)&sin6_out
, &sin6_out_len
) == 0) {
615 /* We might have an IPv6 interface. */
616 const unsigned char *addr
=
617 (unsigned char*)sin6_out
.sin6_addr
.s6_addr
;
618 if (!memcmp(addr
, ZEROES
, 8) ||
619 (addr
[0] == 0xfe && (addr
[1] & 0xc0) == 0x80)) {
620 /* This is a reserved, ipv4compat, ipv4map, loopback,
621 * link-local or unspecified address. The host should
622 * never have given it to us; it could never connect
624 evutil_inet_ntop(AF_INET6
, &sin6_out
.sin6_addr
,
626 event_warnx("Got a strange local ipv6 address %s",buf
);
628 event_debug(("Detected an IPv4 interface"));
629 had_ipv6_address
= 1;
634 evutil_closesocket(fd
);
639 /* Internal addrinfo flag. This one is set when we allocate the addrinfo from
640 * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
641 * it, and we should trust what they said.
643 #define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
645 /* Helper: construct a new addrinfo containing the socket address in
646 * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
647 * socktype and protocol info from hints. If they weren't set, then
648 * allocate both a TCP and a UDP addrinfo.
650 struct evutil_addrinfo
*
651 evutil_new_addrinfo(struct sockaddr
*sa
, ev_socklen_t socklen
,
652 const struct evutil_addrinfo
*hints
)
654 struct evutil_addrinfo
*res
;
655 EVUTIL_ASSERT(hints
);
657 if (hints
->ai_socktype
== 0 && hints
->ai_protocol
== 0) {
658 /* Indecisive user! Give them a UDP and a TCP. */
659 struct evutil_addrinfo
*r1
, *r2
;
660 struct evutil_addrinfo tmp
;
661 memcpy(&tmp
, hints
, sizeof(tmp
));
662 tmp
.ai_socktype
= SOCK_STREAM
; tmp
.ai_protocol
= IPPROTO_TCP
;
663 r1
= evutil_new_addrinfo(sa
, socklen
, &tmp
);
666 tmp
.ai_socktype
= SOCK_DGRAM
; tmp
.ai_protocol
= IPPROTO_UDP
;
667 r2
= evutil_new_addrinfo(sa
, socklen
, &tmp
);
669 evutil_freeaddrinfo(r1
);
676 /* We're going to allocate extra space to hold the sockaddr. */
677 res
= mm_calloc(1,sizeof(struct evutil_addrinfo
)+socklen
);
680 res
->ai_addr
= (struct sockaddr
*)
681 (((char*)res
) + sizeof(struct evutil_addrinfo
));
682 memcpy(res
->ai_addr
, sa
, socklen
);
683 res
->ai_addrlen
= socklen
;
684 res
->ai_family
= sa
->sa_family
; /* Same or not? XXX */
685 res
->ai_flags
= EVUTIL_AI_LIBEVENT_ALLOCATED
;
686 res
->ai_socktype
= hints
->ai_socktype
;
687 res
->ai_protocol
= hints
->ai_protocol
;
692 /* Append the addrinfo 'append' to the end of 'first', and return the start of
693 * the list. Either element can be NULL, in which case we return the element
694 * that is not NULL. */
695 struct evutil_addrinfo
*
696 evutil_addrinfo_append(struct evutil_addrinfo
*first
,
697 struct evutil_addrinfo
*append
)
699 struct evutil_addrinfo
*ai
= first
;
704 ai
->ai_next
= append
;
710 parse_numeric_servname(const char *servname
)
714 n
= (int) strtol(servname
, &endptr
, 10);
715 if (n
>=0 && n
<= 65535 && servname
[0] && endptr
&& !endptr
[0])
721 /** Parse a service name in 'servname', which can be a decimal port.
722 * Return the port number, or -1 on error.
725 evutil_parse_servname(const char *servname
, const char *protocol
,
726 const struct evutil_addrinfo
*hints
)
728 int n
= parse_numeric_servname(servname
);
731 #if defined(_EVENT_HAVE_GETSERVBYNAME) || defined(WIN32)
732 if (!(hints
->ai_flags
& EVUTIL_AI_NUMERICSERV
)) {
733 struct servent
*ent
= getservbyname(servname
, protocol
);
735 return ntohs(ent
->s_port
);
742 /* Return a string corresponding to a protocol number that we can pass to
745 evutil_unparse_protoname(int proto
)
759 #ifdef _EVENT_HAVE_GETPROTOBYNUMBER
761 struct protoent
*ent
= getprotobynumber(proto
);
771 evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo
*hints
)
773 /* If we can guess the protocol from the socktype, do so. */
774 if (!hints
->ai_protocol
&& hints
->ai_socktype
) {
775 if (hints
->ai_socktype
== SOCK_DGRAM
)
776 hints
->ai_protocol
= IPPROTO_UDP
;
777 else if (hints
->ai_socktype
== SOCK_STREAM
)
778 hints
->ai_protocol
= IPPROTO_TCP
;
781 /* Set the socktype if it isn't set. */
782 if (!hints
->ai_socktype
&& hints
->ai_protocol
) {
783 if (hints
->ai_protocol
== IPPROTO_UDP
)
784 hints
->ai_socktype
= SOCK_DGRAM
;
785 else if (hints
->ai_protocol
== IPPROTO_TCP
)
786 hints
->ai_socktype
= SOCK_STREAM
;
788 else if (hints
->ai_protocol
== IPPROTO_SCTP
)
789 hints
->ai_socktype
= SOCK_STREAM
;
794 #if AF_UNSPEC != PF_UNSPEC
795 #error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
798 /** Implements the part of looking up hosts by name that's common to both
799 * the blocking and nonblocking resolver:
800 * - Adjust 'hints' to have a reasonable socktype and protocol.
801 * - Look up the port based on 'servname', and store it in *portnum,
802 * - Handle the nodename==NULL case
803 * - Handle some invalid arguments cases.
804 * - Handle the cases where nodename is an IPv4 or IPv6 address.
806 * If we need the resolver to look up the hostname, we return
807 * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
808 * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
809 * set *res as getaddrinfo would.
812 evutil_getaddrinfo_common(const char *nodename
, const char *servname
,
813 struct evutil_addrinfo
*hints
, struct evutil_addrinfo
**res
, int *portnum
)
818 if (nodename
== NULL
&& servname
== NULL
)
819 return EVUTIL_EAI_NONAME
;
821 /* We only understand 3 families */
822 if (hints
->ai_family
!= PF_UNSPEC
&& hints
->ai_family
!= PF_INET
&&
823 hints
->ai_family
!= PF_INET6
)
824 return EVUTIL_EAI_FAMILY
;
826 evutil_getaddrinfo_infer_protocols(hints
);
828 /* Look up the port number and protocol, if possible. */
829 pname
= evutil_unparse_protoname(hints
->ai_protocol
);
831 /* XXXX We could look at the protocol we got back from
832 * getservbyname, but it doesn't seem too useful. */
833 port
= evutil_parse_servname(servname
, pname
, hints
);
835 return EVUTIL_EAI_NONAME
;
839 /* If we have no node name, then we're supposed to bind to 'any' and
840 * connect to localhost. */
841 if (nodename
== NULL
) {
842 struct evutil_addrinfo
*res4
=NULL
, *res6
=NULL
;
843 if (hints
->ai_family
!= PF_INET
) { /* INET6 or UNSPEC. */
844 struct sockaddr_in6 sin6
;
845 memset(&sin6
, 0, sizeof(sin6
));
846 sin6
.sin6_family
= AF_INET6
;
847 sin6
.sin6_port
= htons(port
);
848 if (hints
->ai_flags
& EVUTIL_AI_PASSIVE
) {
852 sin6
.sin6_addr
.s6_addr
[15] = 1;
854 res6
= evutil_new_addrinfo((struct sockaddr
*)&sin6
,
855 sizeof(sin6
), hints
);
857 return EVUTIL_EAI_MEMORY
;
860 if (hints
->ai_family
!= PF_INET6
) { /* INET or UNSPEC */
861 struct sockaddr_in sin
;
862 memset(&sin
, 0, sizeof(sin
));
863 sin
.sin_family
= AF_INET
;
864 sin
.sin_port
= htons(port
);
865 if (hints
->ai_flags
& EVUTIL_AI_PASSIVE
) {
866 /* Bind to 0.0.0.0 */
868 /* connect to 127.0.0.1 */
869 sin
.sin_addr
.s_addr
= htonl(0x7f000001);
871 res4
= evutil_new_addrinfo((struct sockaddr
*)&sin
,
875 evutil_freeaddrinfo(res6
);
876 return EVUTIL_EAI_MEMORY
;
879 *res
= evutil_addrinfo_append(res4
, res6
);
883 /* If we can, we should try to parse the hostname without resolving
886 if (hints
->ai_family
== PF_INET6
|| hints
->ai_family
== PF_UNSPEC
) {
887 struct sockaddr_in6 sin6
;
888 memset(&sin6
, 0, sizeof(sin6
));
889 if (1==evutil_inet_pton(AF_INET6
, nodename
, &sin6
.sin6_addr
)) {
890 /* Got an ipv6 address. */
891 sin6
.sin6_family
= AF_INET6
;
892 sin6
.sin6_port
= htons(port
);
893 *res
= evutil_new_addrinfo((struct sockaddr
*)&sin6
,
894 sizeof(sin6
), hints
);
896 return EVUTIL_EAI_MEMORY
;
902 if (hints
->ai_family
== PF_INET
|| hints
->ai_family
== PF_UNSPEC
) {
903 struct sockaddr_in sin
;
904 memset(&sin
, 0, sizeof(sin
));
905 if (1==evutil_inet_pton(AF_INET
, nodename
, &sin
.sin_addr
)) {
906 /* Got an ipv6 address. */
907 sin
.sin_family
= AF_INET
;
908 sin
.sin_port
= htons(port
);
909 *res
= evutil_new_addrinfo((struct sockaddr
*)&sin
,
912 return EVUTIL_EAI_MEMORY
;
918 /* If we have reached this point, we definitely need to do a DNS
920 if ((hints
->ai_flags
& EVUTIL_AI_NUMERICHOST
)) {
921 /* If we're not allowed to do one, then say so. */
922 return EVUTIL_EAI_NONAME
;
925 return EVUTIL_EAI_NEED_RESOLVE
;
928 #ifdef _EVENT_HAVE_GETADDRINFO
929 #define USE_NATIVE_GETADDRINFO
932 #ifdef USE_NATIVE_GETADDRINFO
933 /* A mask of all the flags that we declare, so we can clear them before calling
934 * the native getaddrinfo */
935 static const unsigned int ALL_NONNATIVE_AI_FLAGS
=
940 EVUTIL_AI_CANONNAME
|
942 #ifndef AI_NUMERICHOST
943 EVUTIL_AI_NUMERICHOST
|
945 #ifndef AI_NUMERICSERV
946 EVUTIL_AI_NUMERICSERV
|
948 #ifndef AI_ADDRCONFIG
949 EVUTIL_AI_ADDRCONFIG
|
957 EVUTIL_AI_LIBEVENT_ALLOCATED
;
959 static const unsigned int ALL_NATIVE_AI_FLAGS
=
966 #ifdef AI_NUMERICHOST
969 #ifdef AI_NUMERICSERV
984 #ifndef USE_NATIVE_GETADDRINFO
985 /* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
988 static struct evutil_addrinfo
*
989 addrinfo_from_hostent(const struct hostent
*ent
,
990 int port
, const struct evutil_addrinfo
*hints
)
993 struct sockaddr_in sin
;
994 struct sockaddr_in6 sin6
;
997 struct evutil_addrinfo
*res
=NULL
, *ai
;
1000 if (ent
->h_addrtype
== PF_INET
) {
1001 memset(&sin
, 0, sizeof(sin
));
1002 sin
.sin_family
= AF_INET
;
1003 sin
.sin_port
= htons(port
);
1004 sa
= (struct sockaddr
*)&sin
;
1005 socklen
= sizeof(struct sockaddr_in
);
1006 addrp
= &sin
.sin_addr
;
1007 if (ent
->h_length
!= sizeof(sin
.sin_addr
)) {
1008 event_warnx("Weird h_length from gethostbyname");
1011 } else if (ent
->h_addrtype
== PF_INET6
) {
1012 memset(&sin6
, 0, sizeof(sin6
));
1013 sin6
.sin6_family
= AF_INET6
;
1014 sin6
.sin6_port
= htons(port
);
1015 sa
= (struct sockaddr
*)&sin6
;
1016 socklen
= sizeof(struct sockaddr_in
);
1017 addrp
= &sin6
.sin6_addr
;
1018 if (ent
->h_length
!= sizeof(sin6
.sin6_addr
)) {
1019 event_warnx("Weird h_length from gethostbyname");
1025 for (i
= 0; ent
->h_addr_list
[i
]; ++i
) {
1026 memcpy(addrp
, ent
->h_addr_list
[i
], ent
->h_length
);
1027 ai
= evutil_new_addrinfo(sa
, socklen
, hints
);
1029 evutil_freeaddrinfo(res
);
1032 res
= evutil_addrinfo_append(res
, ai
);
1035 if (res
&& ((hints
->ai_flags
& EVUTIL_AI_CANONNAME
) && ent
->h_name
)) {
1036 res
->ai_canonname
= mm_strdup(ent
->h_name
);
1037 if (res
->ai_canonname
== NULL
) {
1038 evutil_freeaddrinfo(res
);
1047 /* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
1048 * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
1049 * that we'll only get addresses we could maybe connect to.
1052 evutil_adjust_hints_for_addrconfig(struct evutil_addrinfo
*hints
)
1054 if (!(hints
->ai_flags
& EVUTIL_AI_ADDRCONFIG
))
1056 if (hints
->ai_family
!= PF_UNSPEC
)
1058 if (!have_checked_interfaces
)
1059 evutil_check_interfaces(0);
1060 if (had_ipv4_address
&& !had_ipv6_address
) {
1061 hints
->ai_family
= PF_INET
;
1062 } else if (!had_ipv4_address
&& had_ipv6_address
) {
1063 hints
->ai_family
= PF_INET6
;
1067 #ifdef USE_NATIVE_GETADDRINFO
1068 static int need_numeric_port_hack_
=0;
1069 static int need_socktype_protocol_hack_
=0;
1070 static int tested_for_getaddrinfo_hacks
=0;
1072 /* Some older BSDs (like OpenBSD up to 4.6) used to believe that
1073 giving a numeric port without giving an ai_socktype was verboten.
1074 We test for this so we can apply an appropriate workaround. If it
1075 turns out that the bug is present, then:
1077 - If nodename==NULL and servname is numeric, we build an answer
1078 ourselves using evutil_getaddrinfo_common().
1080 - If nodename!=NULL and servname is numeric, then we set
1081 servname=NULL when calling getaddrinfo, and post-process the
1082 result to set the ports on it.
1084 We test for this bug at runtime, since otherwise we can't have the
1085 same binary run on multiple BSD versions.
1087 - Some versions of Solaris believe that it's nice to leave to protocol
1088 field set to 0. We test for this so we can apply an appropriate
1092 test_for_getaddrinfo_hacks(void)
1095 struct evutil_addrinfo
*ai
=NULL
, *ai2
=NULL
;
1096 struct evutil_addrinfo hints
;
1098 memset(&hints
,0,sizeof(hints
));
1099 hints
.ai_family
= PF_UNSPEC
;
1101 #ifdef AI_NUMERICHOST
1104 #ifdef AI_NUMERICSERV
1108 r
= getaddrinfo("1.2.3.4", "80", &hints
, &ai
);
1109 hints
.ai_socktype
= SOCK_STREAM
;
1110 r2
= getaddrinfo("1.2.3.4", "80", &hints
, &ai2
);
1111 if (r2
== 0 && r
!= 0) {
1112 need_numeric_port_hack_
=1;
1114 if (ai2
&& ai2
->ai_protocol
== 0) {
1115 need_socktype_protocol_hack_
=1;
1122 tested_for_getaddrinfo_hacks
=1;
1126 need_numeric_port_hack(void)
1128 if (!tested_for_getaddrinfo_hacks
)
1129 test_for_getaddrinfo_hacks();
1130 return need_numeric_port_hack_
;
1134 need_socktype_protocol_hack(void)
1136 if (!tested_for_getaddrinfo_hacks
)
1137 test_for_getaddrinfo_hacks();
1138 return need_socktype_protocol_hack_
;
1142 apply_numeric_port_hack(int port
, struct evutil_addrinfo
**ai
)
1144 /* Now we run through the list and set the ports on all of the
1145 * results where ports would make sense. */
1146 for ( ; *ai
; ai
= &(*ai
)->ai_next
) {
1147 struct sockaddr
*sa
= (*ai
)->ai_addr
;
1148 if (sa
&& sa
->sa_family
== AF_INET
) {
1149 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
1150 sin
->sin_port
= htons(port
);
1151 } else if (sa
&& sa
->sa_family
== AF_INET6
) {
1152 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
1153 sin6
->sin6_port
= htons(port
);
1155 /* A numeric port makes no sense here; remove this one
1157 struct evutil_addrinfo
*victim
= *ai
;
1158 *ai
= victim
->ai_next
;
1159 victim
->ai_next
= NULL
;
1160 freeaddrinfo(victim
);
1166 apply_socktype_protocol_hack(struct evutil_addrinfo
*ai
)
1168 struct evutil_addrinfo
*ai_new
;
1169 for (; ai
; ai
= ai
->ai_next
) {
1170 evutil_getaddrinfo_infer_protocols(ai
);
1171 if (ai
->ai_socktype
|| ai
->ai_protocol
)
1173 ai_new
= mm_malloc(sizeof(*ai_new
));
1176 memcpy(ai_new
, ai
, sizeof(*ai_new
));
1177 ai
->ai_socktype
= SOCK_STREAM
;
1178 ai
->ai_protocol
= IPPROTO_TCP
;
1179 ai_new
->ai_socktype
= SOCK_DGRAM
;
1180 ai_new
->ai_protocol
= IPPROTO_UDP
;
1182 ai_new
->ai_next
= ai
->ai_next
;
1183 ai
->ai_next
= ai_new
;
1190 evutil_getaddrinfo(const char *nodename
, const char *servname
,
1191 const struct evutil_addrinfo
*hints_in
, struct evutil_addrinfo
**res
)
1193 #ifdef USE_NATIVE_GETADDRINFO
1194 struct evutil_addrinfo hints
;
1195 int portnum
=-1, need_np_hack
, err
;
1198 memcpy(&hints
, hints_in
, sizeof(hints
));
1200 memset(&hints
, 0, sizeof(hints
));
1201 hints
.ai_family
= PF_UNSPEC
;
1204 #ifndef AI_ADDRCONFIG
1205 /* Not every system has AI_ADDRCONFIG, so fake it. */
1206 if (hints
.ai_family
== PF_UNSPEC
&&
1207 (hints
.ai_flags
& EVUTIL_AI_ADDRCONFIG
)) {
1208 evutil_adjust_hints_for_addrconfig(&hints
);
1212 #ifndef AI_NUMERICSERV
1213 /* Not every system has AI_NUMERICSERV, so fake it. */
1214 if (hints
.ai_flags
& EVUTIL_AI_NUMERICSERV
) {
1215 if (servname
&& parse_numeric_servname(servname
)<0)
1216 return EVUTIL_EAI_NONAME
;
1220 /* Enough operating systems handle enough common non-resolve
1221 * cases here weirdly enough that we are better off just
1222 * overriding them. For example:
1224 * - Windows doesn't like to infer the protocol from the
1225 * socket type, or fill in socket or protocol types much at
1226 * all. It also seems to do its own broken implicit
1227 * always-on version of AI_ADDRCONFIG that keeps it from
1228 * ever resolving even a literal IPv6 address when
1229 * ai_addrtype is PF_UNSPEC.
1234 err
= evutil_getaddrinfo_common(nodename
,servname
,&hints
,
1237 err
== EVUTIL_EAI_MEMORY
||
1238 err
== EVUTIL_EAI_NONAME
)
1240 /* If we make it here, the system getaddrinfo can
1241 * have a crack at it. */
1245 /* See documentation for need_numeric_port_hack above.*/
1246 need_np_hack
= need_numeric_port_hack() && servname
&& !hints
.ai_socktype
1247 && ((portnum
=parse_numeric_servname(servname
)) >= 0);
1250 return evutil_getaddrinfo_common(
1251 NULL
,servname
,&hints
, res
, &portnum
);
1255 if (need_socktype_protocol_hack()) {
1256 evutil_getaddrinfo_infer_protocols(&hints
);
1259 /* Make sure that we didn't actually steal any AI_FLAGS values that
1260 * the system is using. (This is a constant expression, and should ge
1263 * XXXX Turn this into a compile-time failure rather than a run-time
1266 EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS
& ALL_NATIVE_AI_FLAGS
) == 0);
1268 /* Clear any flags that only libevent understands. */
1269 hints
.ai_flags
&= ~ALL_NONNATIVE_AI_FLAGS
;
1271 err
= getaddrinfo(nodename
, servname
, &hints
, res
);
1273 apply_numeric_port_hack(portnum
, res
);
1275 if (need_socktype_protocol_hack()) {
1276 if (apply_socktype_protocol_hack(*res
) < 0) {
1277 evutil_freeaddrinfo(*res
);
1279 return EVUTIL_EAI_MEMORY
;
1285 struct hostent
*ent
= NULL
;
1286 struct evutil_addrinfo hints
;
1289 memcpy(&hints
, hints_in
, sizeof(hints
));
1291 memset(&hints
, 0, sizeof(hints
));
1292 hints
.ai_family
= PF_UNSPEC
;
1295 evutil_adjust_hints_for_addrconfig(&hints
);
1297 err
= evutil_getaddrinfo_common(nodename
, servname
, &hints
, res
, &port
);
1298 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
1299 /* We either succeeded or failed. No need to continue */
1304 /* Use any of the various gethostbyname_r variants as available. */
1306 #ifdef _EVENT_HAVE_GETHOSTBYNAME_R_6_ARG
1307 /* This one is what glibc provides. */
1309 struct hostent hostent
;
1311 r
= gethostbyname_r(nodename
, &hostent
, buf
, sizeof(buf
), &ent
,
1313 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_5_ARG)
1315 struct hostent hostent
;
1316 ent
= gethostbyname_r(nodename
, &hostent
, buf
, sizeof(buf
),
1318 #elif defined(_EVENT_HAVE_GETHOSTBYNAME_R_3_ARG)
1319 struct hostent_data data
;
1320 struct hostent hostent
;
1321 memset(&data
, 0, sizeof(data
));
1322 err
= gethostbyname_r(nodename
, &hostent
, &data
);
1323 ent
= err
? NULL
: &hostent
;
1325 /* fall back to gethostbyname. */
1326 /* XXXX This needs a lock everywhere but Windows. */
1327 ent
= gethostbyname(nodename
);
1329 err
= WSAGetLastError();
1335 /* Now we have either ent or err set. */
1337 /* XXX is this right for windows ? */
1340 return EVUTIL_EAI_AGAIN
;
1343 return EVUTIL_EAI_FAIL
;
1344 case HOST_NOT_FOUND
:
1345 return EVUTIL_EAI_NONAME
;
1347 #if NO_DATA != NO_ADDRESS
1350 return EVUTIL_EAI_NODATA
;
1354 if (ent
->h_addrtype
!= hints
.ai_family
&&
1355 hints
.ai_family
!= PF_UNSPEC
) {
1356 /* This wasn't the type we were hoping for. Too bad
1357 * we never had a chance to ask gethostbyname for what
1359 return EVUTIL_EAI_NONAME
;
1362 /* Make sure we got _some_ answers. */
1363 if (ent
->h_length
== 0)
1364 return EVUTIL_EAI_NODATA
;
1366 /* If we got an address type we don't know how to make a
1367 sockaddr for, give up. */
1368 if (ent
->h_addrtype
!= PF_INET
&& ent
->h_addrtype
!= PF_INET6
)
1369 return EVUTIL_EAI_FAMILY
;
1371 *res
= addrinfo_from_hostent(ent
, port
, &hints
);
1373 return EVUTIL_EAI_MEMORY
;
1381 evutil_freeaddrinfo(struct evutil_addrinfo
*ai
)
1383 #ifdef _EVENT_HAVE_GETADDRINFO
1384 if (!(ai
->ai_flags
& EVUTIL_AI_LIBEVENT_ALLOCATED
)) {
1390 struct evutil_addrinfo
*next
= ai
->ai_next
;
1391 if (ai
->ai_canonname
)
1392 mm_free(ai
->ai_canonname
);
1398 static evdns_getaddrinfo_fn evdns_getaddrinfo_impl
= NULL
;
1401 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo_fn fn
)
1403 if (!evdns_getaddrinfo_impl
)
1404 evdns_getaddrinfo_impl
= fn
;
1407 /* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
1408 * otherwise do a blocking resolve and pass the result to the callback in the
1409 * way that evdns_getaddrinfo would.
1412 evutil_getaddrinfo_async(struct evdns_base
*dns_base
,
1413 const char *nodename
, const char *servname
,
1414 const struct evutil_addrinfo
*hints_in
,
1415 void (*cb
)(int, struct evutil_addrinfo
*, void *), void *arg
)
1417 if (dns_base
&& evdns_getaddrinfo_impl
) {
1418 evdns_getaddrinfo_impl(
1419 dns_base
, nodename
, servname
, hints_in
, cb
, arg
);
1421 struct evutil_addrinfo
*ai
=NULL
;
1423 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &ai
);
1430 evutil_gai_strerror(int err
)
1432 /* As a sneaky side-benefit, this case statement will get most
1433 * compilers to tell us if any of the error codes we defined
1434 * conflict with the platform's native error codes. */
1436 case EVUTIL_EAI_CANCEL
:
1437 return "Request canceled";
1441 case EVUTIL_EAI_ADDRFAMILY
:
1442 return "address family for nodename not supported";
1443 case EVUTIL_EAI_AGAIN
:
1444 return "temporary failure in name resolution";
1445 case EVUTIL_EAI_BADFLAGS
:
1446 return "invalid value for ai_flags";
1447 case EVUTIL_EAI_FAIL
:
1448 return "non-recoverable failure in name resolution";
1449 case EVUTIL_EAI_FAMILY
:
1450 return "ai_family not supported";
1451 case EVUTIL_EAI_MEMORY
:
1452 return "memory allocation failure";
1453 case EVUTIL_EAI_NODATA
:
1454 return "no address associated with nodename";
1455 case EVUTIL_EAI_NONAME
:
1456 return "nodename nor servname provided, or not known";
1457 case EVUTIL_EAI_SERVICE
:
1458 return "servname not supported for ai_socktype";
1459 case EVUTIL_EAI_SOCKTYPE
:
1460 return "ai_socktype not supported";
1461 case EVUTIL_EAI_SYSTEM
:
1462 return "system error";
1464 #if defined(USE_NATIVE_GETADDRINFO) && defined(WIN32)
1465 return gai_strerrorA(err
);
1466 #elif defined(USE_NATIVE_GETADDRINFO)
1467 return gai_strerror(err
);
1469 return "Unknown error code";
1475 #define E(code, s) { code, (s " [" #code " ]") }
1476 static struct { int code
; const char *msg
; } windows_socket_errors
[] = {
1477 E(WSAEINTR
, "Interrupted function call"),
1478 E(WSAEACCES
, "Permission denied"),
1479 E(WSAEFAULT
, "Bad address"),
1480 E(WSAEINVAL
, "Invalid argument"),
1481 E(WSAEMFILE
, "Too many open files"),
1482 E(WSAEWOULDBLOCK
, "Resource temporarily unavailable"),
1483 E(WSAEINPROGRESS
, "Operation now in progress"),
1484 E(WSAEALREADY
, "Operation already in progress"),
1485 E(WSAENOTSOCK
, "Socket operation on nonsocket"),
1486 E(WSAEDESTADDRREQ
, "Destination address required"),
1487 E(WSAEMSGSIZE
, "Message too long"),
1488 E(WSAEPROTOTYPE
, "Protocol wrong for socket"),
1489 E(WSAENOPROTOOPT
, "Bad protocol option"),
1490 E(WSAEPROTONOSUPPORT
, "Protocol not supported"),
1491 E(WSAESOCKTNOSUPPORT
, "Socket type not supported"),
1492 /* What's the difference between NOTSUPP and NOSUPPORT? :) */
1493 E(WSAEOPNOTSUPP
, "Operation not supported"),
1494 E(WSAEPFNOSUPPORT
, "Protocol family not supported"),
1495 E(WSAEAFNOSUPPORT
, "Address family not supported by protocol family"),
1496 E(WSAEADDRINUSE
, "Address already in use"),
1497 E(WSAEADDRNOTAVAIL
, "Cannot assign requested address"),
1498 E(WSAENETDOWN
, "Network is down"),
1499 E(WSAENETUNREACH
, "Network is unreachable"),
1500 E(WSAENETRESET
, "Network dropped connection on reset"),
1501 E(WSAECONNABORTED
, "Software caused connection abort"),
1502 E(WSAECONNRESET
, "Connection reset by peer"),
1503 E(WSAENOBUFS
, "No buffer space available"),
1504 E(WSAEISCONN
, "Socket is already connected"),
1505 E(WSAENOTCONN
, "Socket is not connected"),
1506 E(WSAESHUTDOWN
, "Cannot send after socket shutdown"),
1507 E(WSAETIMEDOUT
, "Connection timed out"),
1508 E(WSAECONNREFUSED
, "Connection refused"),
1509 E(WSAEHOSTDOWN
, "Host is down"),
1510 E(WSAEHOSTUNREACH
, "No route to host"),
1511 E(WSAEPROCLIM
, "Too many processes"),
1513 /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
1514 E(WSASYSNOTREADY
, "Network subsystem is unavailable"),
1515 E(WSAVERNOTSUPPORTED
, "Winsock.dll out of range"),
1516 E(WSANOTINITIALISED
, "Successful WSAStartup not yet performed"),
1517 E(WSAEDISCON
, "Graceful shutdown now in progress"),
1518 #ifdef WSATYPE_NOT_FOUND
1519 E(WSATYPE_NOT_FOUND
, "Class type not found"),
1521 E(WSAHOST_NOT_FOUND
, "Host not found"),
1522 E(WSATRY_AGAIN
, "Nonauthoritative host not found"),
1523 E(WSANO_RECOVERY
, "This is a nonrecoverable error"),
1524 E(WSANO_DATA
, "Valid name, no data record of requested type)"),
1526 /* There are some more error codes whose numeric values are marked
1527 * <b>OS dependent</b>. They start with WSA_, apparently for the same
1528 * reason that practitioners of some craft traditions deliberately
1529 * introduce imperfections into their baskets and rugs "to allow the
1530 * evil spirits to escape." If we catch them, then our binaries
1531 * might not report consistent results across versions of Windows.
1532 * Thus, I'm going to let them all fall through.
1537 /** Equivalent to strerror, but for windows socket errors. */
1539 evutil_socket_error_to_string(int errcode
)
1541 /* XXXX Is there really no built-in function to do this? */
1543 for (i
=0; windows_socket_errors
[i
].code
>= 0; ++i
) {
1544 if (errcode
== windows_socket_errors
[i
].code
)
1545 return windows_socket_errors
[i
].msg
;
1547 return strerror(errcode
);
1552 evutil_snprintf(char *buf
, size_t buflen
, const char *format
, ...)
1556 va_start(ap
, format
);
1557 r
= evutil_vsnprintf(buf
, buflen
, format
, ap
);
1563 evutil_vsnprintf(char *buf
, size_t buflen
, const char *format
, va_list ap
)
1568 #if defined(_MSC_VER) || defined(WIN32)
1569 r
= _vsnprintf(buf
, buflen
, format
, ap
);
1571 r
= _vscprintf(format
, ap
);
1573 /* Make sure we always use the correct vsnprintf on IRIX */
1574 extern int _xpg5_vsnprintf(char * __restrict
,
1575 __SGI_LIBC_NAMESPACE_QUALIFIER
size_t,
1576 const char * __restrict
, /* va_list */ char *);
1578 r
= _xpg5_vsnprintf(buf
, buflen
, format
, ap
);
1580 r
= vsnprintf(buf
, buflen
, format
, ap
);
1582 buf
[buflen
-1] = '\0';
1586 #define USE_INTERNAL_NTOP
1587 #define USE_INTERNAL_PTON
1590 evutil_inet_ntop(int af
, const void *src
, char *dst
, size_t len
)
1592 #if defined(_EVENT_HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
1593 return inet_ntop(af
, src
, dst
, len
);
1595 if (af
== AF_INET
) {
1596 const struct in_addr
*in
= src
;
1597 const ev_uint32_t a
= ntohl(in
->s_addr
);
1599 r
= evutil_snprintf(dst
, len
, "%d.%d.%d.%d",
1600 (int)(ev_uint8_t
)((a
>>24)&0xff),
1601 (int)(ev_uint8_t
)((a
>>16)&0xff),
1602 (int)(ev_uint8_t
)((a
>>8 )&0xff),
1603 (int)(ev_uint8_t
)((a
)&0xff));
1604 if (r
<0||(size_t)r
>=len
)
1609 } else if (af
== AF_INET6
) {
1610 const struct in6_addr
*addr
= src
;
1612 int longestGapLen
= 0, longestGapPos
= -1, i
,
1613 curGapPos
= -1, curGapLen
= 0;
1614 ev_uint16_t words
[8];
1615 for (i
= 0; i
< 8; ++i
) {
1617 (((ev_uint16_t
)addr
->s6_addr
[2*i
])<<8) + addr
->s6_addr
[2*i
+1];
1619 if (words
[0] == 0 && words
[1] == 0 && words
[2] == 0 && words
[3] == 0 &&
1620 words
[4] == 0 && ((words
[5] == 0 && words
[6] && words
[7]) ||
1621 (words
[5] == 0xffff))) {
1622 /* This is an IPv4 address. */
1623 if (words
[5] == 0) {
1624 evutil_snprintf(buf
, sizeof(buf
), "::%d.%d.%d.%d",
1625 addr
->s6_addr
[12], addr
->s6_addr
[13],
1626 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1628 evutil_snprintf(buf
, sizeof(buf
), "::%x:%d.%d.%d.%d", words
[5],
1629 addr
->s6_addr
[12], addr
->s6_addr
[13],
1630 addr
->s6_addr
[14], addr
->s6_addr
[15]);
1632 if (strlen(buf
) > len
)
1634 strlcpy(dst
, buf
, len
);
1639 if (words
[i
] == 0) {
1642 while (i
<8 && words
[i
] == 0) {
1645 if (curGapLen
> longestGapLen
) {
1646 longestGapPos
= curGapPos
;
1647 longestGapLen
= curGapLen
;
1653 if (longestGapLen
<=1)
1657 for (i
= 0; i
< 8; ++i
) {
1658 if (words
[i
] == 0 && longestGapPos
== i
) {
1662 while (i
< 8 && words
[i
] == 0)
1664 --i
; /* to compensate for loop increment. */
1667 sizeof(buf
)-(cp
-buf
), "%x", (unsigned)words
[i
]);
1674 if (strlen(buf
) > len
)
1676 strlcpy(dst
, buf
, len
);
1686 evutil_inet_pton(int af
, const char *src
, void *dst
)
1688 #if defined(_EVENT_HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
1689 return inet_pton(af
, src
, dst
);
1691 if (af
== AF_INET
) {
1694 struct in_addr
*addr
= dst
;
1695 if (sscanf(src
, "%d.%d.%d.%d%c", &a
,&b
,&c
,&d
,&more
) != 4)
1697 if (a
< 0 || a
> 255) return 0;
1698 if (b
< 0 || b
> 255) return 0;
1699 if (c
< 0 || c
> 255) return 0;
1700 if (d
< 0 || d
> 255) return 0;
1701 addr
->s_addr
= htonl((a
<<24) | (b
<<16) | (c
<<8) | d
);
1704 } else if (af
== AF_INET6
) {
1705 struct in6_addr
*out
= dst
;
1706 ev_uint16_t words
[8];
1707 int gapPos
= -1, i
, setWords
=0;
1708 const char *dot
= strchr(src
, '.');
1709 const char *eow
; /* end of words. */
1713 eow
= src
+strlen(src
);
1715 int byte1
,byte2
,byte3
,byte4
;
1717 for (eow
= dot
-1; eow
>= src
&& EVUTIL_ISDIGIT(*eow
); --eow
)
1721 /* We use "scanf" because some platform inet_aton()s are too lax
1722 * about IPv4 addresses of the form "1.2.3" */
1723 if (sscanf(eow
, "%d.%d.%d.%d%c",
1724 &byte1
,&byte2
,&byte3
,&byte4
,&more
) != 4)
1727 if (byte1
> 255 || byte1
< 0 ||
1728 byte2
> 255 || byte2
< 0 ||
1729 byte3
> 255 || byte3
< 0 ||
1730 byte4
> 255 || byte4
< 0)
1733 words
[6] = (byte1
<<8) | byte2
;
1734 words
[7] = (byte3
<<8) | byte4
;
1742 if (EVUTIL_ISXDIGIT(*src
)) {
1744 long r
= strtol(src
, &next
, 16);
1752 words
[i
++] = (ev_uint16_t
)r
;
1755 if (*src
!= ':' && src
!= eow
)
1758 } else if (*src
== ':' && i
> 0 && gapPos
==-1) {
1761 } else if (*src
== ':' && i
== 0 && src
[1] == ':' && gapPos
==-1) {
1770 (setWords
== 8 && gapPos
!= -1) ||
1771 (setWords
< 8 && gapPos
== -1))
1775 int nToMove
= setWords
- (dot
? 2 : 0) - gapPos
;
1776 int gapLen
= 8 - setWords
;
1777 /* assert(nToMove >= 0); */
1779 return -1; /* should be impossible */
1780 memmove(&words
[gapPos
+gapLen
], &words
[gapPos
],
1781 sizeof(ev_uint16_t
)*nToMove
);
1782 memset(&words
[gapPos
], 0, sizeof(ev_uint16_t
)*gapLen
);
1784 for (i
= 0; i
< 8; ++i
) {
1785 out
->s6_addr
[2*i
] = words
[i
] >> 8;
1786 out
->s6_addr
[2*i
+1] = words
[i
] & 0xff;
1798 evutil_parse_sockaddr_port(const char *ip_as_string
, struct sockaddr
*out
, int *outlen
)
1802 const char *cp
, *addr_part
, *port_part
;
1804 /* recognized formats are:
1812 cp
= strchr(ip_as_string
, ':');
1813 if (*ip_as_string
== '[') {
1815 if (!(cp
= strchr(ip_as_string
, ']'))) {
1818 len
= (int) ( cp
-(ip_as_string
+ 1) );
1819 if (len
> (int)sizeof(buf
)-1) {
1822 memcpy(buf
, ip_as_string
+1, len
);
1830 } else if (cp
&& strchr(cp
+1, ':')) {
1832 addr_part
= ip_as_string
;
1836 if (cp
- ip_as_string
> (int)sizeof(buf
)-1) {
1839 memcpy(buf
, ip_as_string
, cp
-ip_as_string
);
1840 buf
[cp
-ip_as_string
] = '\0';
1844 addr_part
= ip_as_string
;
1849 if (port_part
== NULL
) {
1852 port
= atoi(port_part
);
1853 if (port
<= 0 || port
> 65535) {
1859 return -1; /* Should be impossible. */
1863 struct sockaddr_in6 sin6
;
1864 memset(&sin6
, 0, sizeof(sin6
));
1865 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
1866 sin6
.sin6_len
= sizeof(sin6
);
1868 sin6
.sin6_family
= AF_INET6
;
1869 sin6
.sin6_port
= htons(port
);
1870 if (1 != evutil_inet_pton(AF_INET6
, addr_part
, &sin6
.sin6_addr
))
1872 if ((int)sizeof(sin6
) > *outlen
)
1874 memset(out
, 0, *outlen
);
1875 memcpy(out
, &sin6
, sizeof(sin6
));
1876 *outlen
= sizeof(sin6
);
1882 struct sockaddr_in sin
;
1883 memset(&sin
, 0, sizeof(sin
));
1884 #ifdef _EVENT_HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
1885 sin
.sin_len
= sizeof(sin
);
1887 sin
.sin_family
= AF_INET
;
1888 sin
.sin_port
= htons(port
);
1889 if (1 != evutil_inet_pton(AF_INET
, addr_part
, &sin
.sin_addr
))
1891 if ((int)sizeof(sin
) > *outlen
)
1893 memset(out
, 0, *outlen
);
1894 memcpy(out
, &sin
, sizeof(sin
));
1895 *outlen
= sizeof(sin
);
1901 evutil_format_sockaddr_port(const struct sockaddr
*sa
, char *out
, size_t outlen
)
1904 const char *res
=NULL
;
1906 if (sa
->sa_family
== AF_INET
) {
1907 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)sa
;
1908 res
= evutil_inet_ntop(AF_INET
, &sin
->sin_addr
,b
,sizeof(b
));
1909 port
= ntohs(sin
->sin_port
);
1911 evutil_snprintf(out
, outlen
, "%s:%d", b
, port
);
1914 } else if (sa
->sa_family
== AF_INET6
) {
1915 const struct sockaddr_in6
*sin6
= (const struct sockaddr_in6
*)sa
;
1916 res
= evutil_inet_ntop(AF_INET6
, &sin6
->sin6_addr
,b
,sizeof(b
));
1917 port
= ntohs(sin6
->sin6_port
);
1919 evutil_snprintf(out
, outlen
, "[%s]:%d", b
, port
);
1924 evutil_snprintf(out
, outlen
, "<addr with socktype %d>",
1925 (int)sa
->sa_family
);
1930 evutil_sockaddr_cmp(const struct sockaddr
*sa1
, const struct sockaddr
*sa2
,
1934 if (0 != (r
= (sa1
->sa_family
- sa2
->sa_family
)))
1937 if (sa1
->sa_family
== AF_INET
) {
1938 const struct sockaddr_in
*sin1
, *sin2
;
1939 sin1
= (const struct sockaddr_in
*)sa1
;
1940 sin2
= (const struct sockaddr_in
*)sa2
;
1941 if (sin1
->sin_addr
.s_addr
< sin2
->sin_addr
.s_addr
)
1943 else if (sin1
->sin_addr
.s_addr
> sin2
->sin_addr
.s_addr
)
1945 else if (include_port
&&
1946 (r
= ((int)sin1
->sin_port
- (int)sin2
->sin_port
)))
1952 else if (sa1
->sa_family
== AF_INET6
) {
1953 const struct sockaddr_in6
*sin1
, *sin2
;
1954 sin1
= (const struct sockaddr_in6
*)sa1
;
1955 sin2
= (const struct sockaddr_in6
*)sa2
;
1956 if ((r
= memcmp(sin1
->sin6_addr
.s6_addr
, sin2
->sin6_addr
.s6_addr
, 16)))
1958 else if (include_port
&&
1959 (r
= ((int)sin1
->sin6_port
- (int)sin2
->sin6_port
)))
1968 /* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
1969 * has 256 bits to look up whether a character is in some set or not. This
1970 * fails on non-ASCII platforms, but so does every other place where we
1971 * take a char and write it onto the network.
1973 static const ev_uint32_t EVUTIL_ISALPHA_TABLE
[8] =
1974 { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
1975 static const ev_uint32_t EVUTIL_ISALNUM_TABLE
[8] =
1976 { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
1977 static const ev_uint32_t EVUTIL_ISSPACE_TABLE
[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
1978 static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE
[8] =
1979 { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
1980 static const ev_uint32_t EVUTIL_ISDIGIT_TABLE
[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
1981 static const ev_uint32_t EVUTIL_ISPRINT_TABLE
[8] =
1982 { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
1983 static const ev_uint32_t EVUTIL_ISUPPER_TABLE
[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
1984 static const ev_uint32_t EVUTIL_ISLOWER_TABLE
[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
1985 /* Upper-casing and lowercasing tables to map characters to upper/lowercase
1987 static const unsigned char EVUTIL_TOUPPER_TABLE
[256] = {
1988 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1989 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
1990 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
1991 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
1992 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
1993 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
1994 96,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
1995 80,81,82,83,84,85,86,87,88,89,90,123,124,125,126,127,
1996 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
1997 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
1998 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
1999 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2000 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2001 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2002 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2003 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2005 static const unsigned char EVUTIL_TOLOWER_TABLE
[256] = {
2006 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
2007 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
2008 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
2009 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
2010 64,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2011 112,113,114,115,116,117,118,119,120,121,122,91,92,93,94,95,
2012 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
2013 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
2014 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
2015 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
2016 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
2017 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
2018 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
2019 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
2020 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
2021 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
2024 #define IMPL_CTYPE_FN(name) \
2025 int EVUTIL_##name(char c) { \
2027 return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1 << (u & 31))); \
2029 IMPL_CTYPE_FN(ISALPHA
)
2030 IMPL_CTYPE_FN(ISALNUM
)
2031 IMPL_CTYPE_FN(ISSPACE
)
2032 IMPL_CTYPE_FN(ISDIGIT
)
2033 IMPL_CTYPE_FN(ISXDIGIT
)
2034 IMPL_CTYPE_FN(ISPRINT
)
2035 IMPL_CTYPE_FN(ISLOWER
)
2036 IMPL_CTYPE_FN(ISUPPER
)
2038 char EVUTIL_TOLOWER(char c
)
2040 return ((char)EVUTIL_TOLOWER_TABLE
[(ev_uint8_t
)c
]);
2042 char EVUTIL_TOUPPER(char c
)
2044 return ((char)EVUTIL_TOUPPER_TABLE
[(ev_uint8_t
)c
]);
2047 evutil_ascii_strcasecmp(const char *s1
, const char *s2
)
2051 c1
= EVUTIL_TOLOWER(*s1
++);
2052 c2
= EVUTIL_TOLOWER(*s2
++);
2061 int evutil_ascii_strncasecmp(const char *s1
, const char *s2
, size_t n
)
2065 c1
= EVUTIL_TOLOWER(*s1
++);
2066 c2
= EVUTIL_TOLOWER(*s2
++);
2078 evutil_issetugid(void)
2080 #ifdef _EVENT_HAVE_ISSETUGID
2084 #ifdef _EVENT_HAVE_GETEUID
2085 if (getuid() != geteuid())
2088 #ifdef _EVENT_HAVE_GETEGID
2089 if (getgid() != getegid())
2097 evutil_getenv(const char *varname
)
2099 if (evutil_issetugid())
2102 return getenv(varname
);
2106 _evutil_weakrand(void)
2116 * Volatile pointer to memset: we use this to keep the compiler from
2117 * eliminating our call to memset.
2119 void * (*volatile evutil_memset_volatile_
)(void *, int, size_t) = memset
;
2122 evutil_memclear_(void *mem
, size_t len
)
2124 evutil_memset_volatile_(mem
, 0, len
);
2128 evutil_sockaddr_is_loopback(const struct sockaddr
*addr
)
2130 static const char LOOPBACK_S6
[16] =
2131 "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
2132 if (addr
->sa_family
== AF_INET
) {
2133 const struct sockaddr_in
*sin
= (const struct sockaddr_in
*)addr
;
2134 return (ntohl(sin
->sin_addr
.s_addr
) & 0xff000000) == 0x7f000000;
2135 } else if (addr
->sa_family
== AF_INET6
) {
2136 const struct sockaddr_in6
*sin6
= (const struct sockaddr_in6
*)addr
;
2137 return !memcmp(sin6
->sin6_addr
.s6_addr
, LOOPBACK_S6
, 16);
2142 #define MAX_SECONDS_IN_MSEC_LONG \
2143 (((LONG_MAX) - 999) / 1000)
2146 evutil_tv_to_msec(const struct timeval
*tv
)
2148 if (tv
->tv_usec
> 1000000 || tv
->tv_sec
> MAX_SECONDS_IN_MSEC_LONG
)
2151 return (tv
->tv_sec
* 1000) + ((tv
->tv_usec
+ 999) / 1000);
2155 evutil_hex_char_to_int(char c
)
2169 case 'A': case 'a': return 10;
2170 case 'B': case 'b': return 11;
2171 case 'C': case 'c': return 12;
2172 case 'D': case 'd': return 13;
2173 case 'E': case 'e': return 14;
2174 case 'F': case 'f': return 15;
2181 evutil_load_windows_system_library(const TCHAR
*library_name
)
2183 TCHAR path
[MAX_PATH
];
2185 n
= GetSystemDirectory(path
, MAX_PATH
);
2186 if (n
== 0 || n
+ _tcslen(library_name
) + 2 >= MAX_PATH
)
2188 _tcscat(path
, TEXT("\\"));
2189 _tcscat(path
, library_name
);
2190 return LoadLibrary(path
);