diff options
Diffstat (limited to 'src/lib/net')
-rw-r--r-- | src/lib/net/.may_include | 15 | ||||
-rw-r--r-- | src/lib/net/address.c | 2046 | ||||
-rw-r--r-- | src/lib/net/address.h | 388 | ||||
-rw-r--r-- | src/lib/net/alertsock.c | 295 | ||||
-rw-r--r-- | src/lib/net/alertsock.h | 45 | ||||
-rw-r--r-- | src/lib/net/buffers_net.c | 202 | ||||
-rw-r--r-- | src/lib/net/buffers_net.h | 27 | ||||
-rw-r--r-- | src/lib/net/gethostname.c | 30 | ||||
-rw-r--r-- | src/lib/net/gethostname.h | 19 | ||||
-rw-r--r-- | src/lib/net/inaddr.c | 267 | ||||
-rw-r--r-- | src/lib/net/inaddr.h | 27 | ||||
-rw-r--r-- | src/lib/net/inaddr_st.h | 104 | ||||
-rw-r--r-- | src/lib/net/include.am | 34 | ||||
-rw-r--r-- | src/lib/net/nettypes.h | 44 | ||||
-rw-r--r-- | src/lib/net/resolve.c | 424 | ||||
-rw-r--r-- | src/lib/net/resolve.h | 58 | ||||
-rw-r--r-- | src/lib/net/socket.c | 697 | ||||
-rw-r--r-- | src/lib/net/socket.h | 118 | ||||
-rw-r--r-- | src/lib/net/socketpair.c | 214 | ||||
-rw-r--r-- | src/lib/net/socketpair.h | 19 | ||||
-rw-r--r-- | src/lib/net/socks5_status.h | 32 |
21 files changed, 5105 insertions, 0 deletions
diff --git a/src/lib/net/.may_include b/src/lib/net/.may_include new file mode 100644 index 0000000000..13b209bbed --- /dev/null +++ b/src/lib/net/.may_include @@ -0,0 +1,15 @@ +orconfig.h +siphash.h +ht.h + +lib/arch/*.h +lib/cc/*.h +lib/container/*.h +lib/ctime/*.h +lib/err/*.h +lib/lock/*.h +lib/log/*.h +lib/net/*.h +lib/string/*.h +lib/testsupport/*.h +lib/malloc/*.h
\ No newline at end of file diff --git a/src/lib/net/address.c b/src/lib/net/address.c new file mode 100644 index 0000000000..03767e2950 --- /dev/null +++ b/src/lib/net/address.c @@ -0,0 +1,2046 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file address.c + * \brief Functions to use and manipulate the tor_addr_t structure. + * + * This module doesn't have any support for the libc resolver: that is all in + * resolve.c. + **/ + +#define ADDRESS_PRIVATE + +#include "orconfig.h" + +#ifdef _WIN32 +/* For access to structs needed by GetAdaptersAddresses */ +#ifndef WIN32_LEAN_AND_MEAN +#error "orconfig.h didn't define WIN32_LEAN_AND_MEAN" +#endif +#ifndef WINVER +#error "orconfig.h didn't define WINVER" +#endif +#ifndef _WIN32_WINNT +#error "orconfig.h didn't define _WIN32_WINNT" +#endif +#if WINVER < 0x0501 +#error "winver too low" +#endif +#if _WIN32_WINNT < 0x0501 +#error "winver too low" +#endif +#include <winsock2.h> +#include <process.h> +#include <windows.h> +#include <iphlpapi.h> +#endif /* defined(_WIN32) */ + +#include "lib/net/address.h" +#include "lib/net/socket.h" +#include "lib/container/smartlist.h" +#include "lib/ctime/di_ops.h" +#include "lib/log/log.h" +#include "lib/log/escape.h" +#include "lib/malloc/malloc.h" +#include "lib/net/inaddr.h" +#include "lib/string/compat_ctype.h" +#include "lib/string/compat_string.h" +#include "lib/string/parse_int.h" +#include "lib/string/printf.h" +#include "lib/string/util_string.h" + +#include "siphash.h" + +#ifdef HAVE_SYS_TIME_H +#include <sys/time.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_ERRNO_H +#include <errno.h> +#endif +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif +#ifdef HAVE_SYS_PARAM_H +#include <sys/param.h> /* FreeBSD needs this to know what version it is */ +#endif +#ifdef HAVE_SYS_UN_H +#include <sys/un.h> +#endif +#ifdef HAVE_IFADDRS_H +#include <ifaddrs.h> +#endif +#ifdef HAVE_SYS_IOCTL_H +#include <sys/ioctl.h> +#endif +#ifdef HAVE_NET_IF_H +#include <net/if.h> +#endif +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to + * work correctly. Bail out here if we've found a platform where AF_UNSPEC + * isn't 0. */ +#if AF_UNSPEC != 0 +#error We rely on AF_UNSPEC being 0. Let us know about your platform, please! +#endif + +/** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a + * sockaddr object in *<b>sa_out</b> of object size <b>len</b>. If not enough + * room is available in sa_out, or on error, return 0. On success, return + * the length of the sockaddr. + * + * Interface note: ordinarily, we return -1 for error. We can't do that here, + * since socklen_t is unsigned on some platforms. + **/ +socklen_t +tor_addr_to_sockaddr(const tor_addr_t *a, + uint16_t port, + struct sockaddr *sa_out, + socklen_t len) +{ + memset(sa_out, 0, len); + + sa_family_t family = tor_addr_family(a); + if (family == AF_INET) { + struct sockaddr_in *sin; + if (len < (int)sizeof(struct sockaddr_in)) + return 0; + sin = (struct sockaddr_in *)sa_out; +#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN + sin->sin_len = sizeof(struct sockaddr_in); +#endif + sin->sin_family = AF_INET; + sin->sin_port = htons(port); + sin->sin_addr.s_addr = tor_addr_to_ipv4n(a); + return sizeof(struct sockaddr_in); + } else if (family == AF_INET6) { + struct sockaddr_in6 *sin6; + if (len < (int)sizeof(struct sockaddr_in6)) + return 0; + sin6 = (struct sockaddr_in6 *)sa_out; +#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN + sin6->sin6_len = sizeof(struct sockaddr_in6); +#endif + sin6->sin6_family = AF_INET6; + sin6->sin6_port = htons(port); + memcpy(&sin6->sin6_addr, tor_addr_to_in6_assert(a), + sizeof(struct in6_addr)); + return sizeof(struct sockaddr_in6); + } else { + return 0; + } +} + +/** Set address <b>a</b> to zero. This address belongs to + * the AF_UNIX family. */ +static void +tor_addr_make_af_unix(tor_addr_t *a) +{ + memset(a, 0, sizeof(*a)); + a->family = AF_UNIX; +} + +/** Set the tor_addr_t in <b>a</b> to contain the socket address contained in + * <b>sa</b>. IF <b>port_out</b> is non-NULL and <b>sa</b> contains a port, + * set *<b>port_out</b> to that port. Return 0 on success and -1 on + * failure. */ +int +tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, + uint16_t *port_out) +{ + tor_assert(a); + tor_assert(sa); + + /* This memset is redundant; leaving it in to avoid any future accidents, + however. */ + memset(a, 0, sizeof(*a)); + + if (sa->sa_family == AF_INET) { + struct sockaddr_in *sin = (struct sockaddr_in *) sa; + tor_addr_from_ipv4n(a, sin->sin_addr.s_addr); + if (port_out) + *port_out = ntohs(sin->sin_port); + } else if (sa->sa_family == AF_INET6) { + struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa; + tor_addr_from_in6(a, &sin6->sin6_addr); + if (port_out) + *port_out = ntohs(sin6->sin6_port); + } else if (sa->sa_family == AF_UNIX) { + tor_addr_make_af_unix(a); + return 0; + } else { + tor_addr_make_unspec(a); + return -1; + } + return 0; +} + +/** Return a newly allocated string holding the address described in + * <b>sa</b>. AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */ +char * +tor_sockaddr_to_str(const struct sockaddr *sa) +{ + char address[TOR_ADDR_BUF_LEN]; + char *result; + tor_addr_t addr; + uint16_t port; +#ifdef HAVE_SYS_UN_H + if (sa->sa_family == AF_UNIX) { + struct sockaddr_un *s_un = (struct sockaddr_un *)sa; + tor_asprintf(&result, "unix:%s", s_un->sun_path); + return result; + } +#endif /* defined(HAVE_SYS_UN_H) */ + if (sa->sa_family == AF_UNSPEC) + return tor_strdup("unspec"); + + if (tor_addr_from_sockaddr(&addr, sa, &port) < 0) + return NULL; + if (! tor_addr_to_str(address, &addr, sizeof(address), 1)) + return NULL; + tor_asprintf(&result, "%s:%d", address, (int)port); + return result; +} + +/** Set address <b>a</b> to the unspecified address. This address belongs to + * no family. */ +void +tor_addr_make_unspec(tor_addr_t *a) +{ + memset(a, 0, sizeof(*a)); + a->family = AF_UNSPEC; +} + +/** Set address <b>a</b> to the null address in address family <b>family</b>. + * The null address for AF_INET is 0.0.0.0. The null address for AF_INET6 is + * [::]. AF_UNSPEC is all null. */ +void +tor_addr_make_null(tor_addr_t *a, sa_family_t family) +{ + memset(a, 0, sizeof(*a)); + a->family = family; +} + +/** Return true iff <b>ip</b> is an IP reserved to localhost or local networks + * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is + * also treated as internal for now.) + */ +int +tor_addr_is_internal_(const tor_addr_t *addr, int for_listening, + const char *filename, int lineno) +{ + uint32_t iph4 = 0; + uint32_t iph6[4]; + + tor_assert(addr); + sa_family_t v_family = tor_addr_family(addr); + + if (v_family == AF_INET) { + iph4 = tor_addr_to_ipv4h(addr); + } else if (v_family == AF_INET6) { + if (tor_addr_is_v4(addr)) { /* v4-mapped */ + uint32_t *addr32 = NULL; + v_family = AF_INET; + // Work around an incorrect NULL pointer dereference warning in + // "clang --analyze" due to limited analysis depth + addr32 = tor_addr_to_in6_addr32(addr); + // To improve performance, wrap this assertion in: + // #if !defined(__clang_analyzer__) || PARANOIA + tor_assert(addr32); + iph4 = ntohl(addr32[3]); + } + } + + if (v_family == AF_INET6) { + const uint32_t *a32 = tor_addr_to_in6_addr32(addr); + iph6[0] = ntohl(a32[0]); + iph6[1] = ntohl(a32[1]); + iph6[2] = ntohl(a32[2]); + iph6[3] = ntohl(a32[3]); + if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */ + return 0; + + if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */ + ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */ + ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */ + return 1; + + if (!iph6[0] && !iph6[1] && !iph6[2] && + ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */ + return 1; + + return 0; + } else if (v_family == AF_INET) { + if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */ + return 0; + if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */ + ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */ + ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */ + ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */ + ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */ + ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */ + return 1; + return 0; + } + + /* unknown address family... assume it's not safe for external use */ + /* rather than tor_assert(0) */ + log_warn(LD_BUG, "tor_addr_is_internal() called from %s:%d with a " + "non-IP address of type %d", filename, lineno, (int)v_family); + tor_fragile_assert(); + return 1; +} + +/** Convert a tor_addr_t <b>addr</b> into a string, and store it in + * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success, + * or NULL on failure. If <b>decorate</b>, surround IPv6 addresses with + * brackets. + */ +const char * +tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate) +{ + const char *ptr; + tor_assert(addr && dest); + + switch (tor_addr_family(addr)) { + case AF_INET: + /* Shortest addr x.x.x.x + \0 */ + if (len < 8) + return NULL; + ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len); + break; + case AF_INET6: + /* Shortest addr [ :: ] + \0 */ + if (len < (3 + (decorate ? 2 : 0))) + return NULL; + + if (decorate) + ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2); + else + ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len); + + if (ptr && decorate) { + *dest = '['; + memcpy(dest+strlen(dest), "]", 2); + tor_assert(ptr == dest+1); + ptr = dest; + } + break; + case AF_UNIX: + tor_snprintf(dest, len, "AF_UNIX"); + ptr = dest; + break; + default: + return NULL; + } + return ptr; +} + +/** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>. Return 0 + * if this is not an .in-addr.arpa address or an .ip6.arpa address. Return -1 + * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address. + * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address + * family does not match <b>family</b>. On success, return 1, and store the + * result, if any, into <b>result</b>, if provided. + * + * If <b>accept_regular</b> is set and the address is in neither recognized + * reverse lookup hostname format, try parsing the address as a regular + * IPv4 or IPv6 address too. + */ +int +tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, + int family, int accept_regular) +{ + if (!strcasecmpend(address, ".in-addr.arpa")) { + /* We have an in-addr.arpa address. */ + char buf[INET_NTOA_BUF_LEN]; + size_t len; + struct in_addr inaddr; + if (family == AF_INET6) + return -1; + + len = strlen(address) - strlen(".in-addr.arpa"); + if (len >= INET_NTOA_BUF_LEN) + return -1; /* Too long. */ + + memcpy(buf, address, len); + buf[len] = '\0'; + if (tor_inet_aton(buf, &inaddr) == 0) + return -1; /* malformed. */ + + /* reverse the bytes */ + inaddr.s_addr = (uint32_t) + (((inaddr.s_addr & 0x000000ff) << 24) + |((inaddr.s_addr & 0x0000ff00) << 8) + |((inaddr.s_addr & 0x00ff0000) >> 8) + |((inaddr.s_addr & 0xff000000) >> 24)); + + if (result) { + tor_addr_from_in(result, &inaddr); + } + return 1; + } + + if (!strcasecmpend(address, ".ip6.arpa")) { + const char *cp; + int n0, n1; + struct in6_addr in6; + + if (family == AF_INET) + return -1; + + cp = address; + for (int i = 0; i < 16; ++i) { + n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */ + if (*cp++ != '.') return -1; /* Then a dot. */ + n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */ + if (*cp++ != '.') return -1; /* Then another dot. */ + if (n0<0 || n1 < 0) /* Both nybbles must be hex. */ + return -1; + + /* We don't check the length of the string in here. But that's okay, + * since we already know that the string ends with ".ip6.arpa", and + * there is no way to frameshift .ip6.arpa so it fits into the pattern + * of hexdigit, period, hexdigit, period that we enforce above. + */ + + /* Assign from low-byte to high-byte. */ + in6.s6_addr[15-i] = n0 | (n1 << 4); + } + if (strcasecmp(cp, "ip6.arpa")) + return -1; + + if (result) { + tor_addr_from_in6(result, &in6); + } + return 1; + } + + if (accept_regular) { + tor_addr_t tmp; + int r = tor_addr_parse(&tmp, address); + if (r < 0) + return 0; + if (r != family && family != AF_UNSPEC) + return -1; + + if (result) + memcpy(result, &tmp, sizeof(tor_addr_t)); + + return 1; + } + + return 0; +} + +/** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name, + * and store the result in the <b>outlen</b>-byte buffer at + * <b>out</b>. Returns a non-negative integer on success. + * Returns -1 on failure. */ +int +tor_addr_to_PTR_name(char *out, size_t outlen, + const tor_addr_t *addr) +{ + tor_assert(out); + tor_assert(addr); + + if (addr->family == AF_INET) { + uint32_t a = tor_addr_to_ipv4h(addr); + + return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa", + (int)(uint8_t)((a )&0xff), + (int)(uint8_t)((a>>8 )&0xff), + (int)(uint8_t)((a>>16)&0xff), + (int)(uint8_t)((a>>24)&0xff)); + } else if (addr->family == AF_INET6) { + int i; + char *cp = out; + const uint8_t *bytes = tor_addr_to_in6_addr8(addr); + if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN) + return -1; + for (i = 15; i >= 0; --i) { + uint8_t byte = bytes[i]; + *cp++ = "0123456789abcdef"[byte & 0x0f]; + *cp++ = '.'; + *cp++ = "0123456789abcdef"[byte >> 4]; + *cp++ = '.'; + } + memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */ + return 32 * 2 + 8; + } + return -1; +} + +/** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly + * a mask and port or port range. Store the parsed address in + * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any) + * in <b>port_min_out</b> and <b>port_max_out</b>. + * + * The syntax is: + * Address OptMask OptPortRange + * Address ::= IPv4Address / "[" IPv6Address "]" / "*" + * OptMask ::= "/" Integer / + * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer / + * + * - If mask, minport, or maxport are NULL, we do not want these + * options to be set; treat them as an error if present. + * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6). + * - If the string has one port, it is placed in both min and max port + * variables. + * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535. + * + * Return an address family on success, or -1 if an invalid address string is + * provided. + * + * If 'flags & TAPMP_EXTENDED_STAR' is false, then the wildcard address '*' + * yield an IPv4 wildcard. + * + * If 'flags & TAPMP_EXTENDED_STAR' is true, then the wildcard address '*' + * yields an AF_UNSPEC wildcard address, which expands to corresponding + * wildcard IPv4 and IPv6 rules, and the following change is made + * in the grammar above: + * Address ::= IPv4Address / "[" IPv6Address "]" / "*" / "*4" / "*6" + * with the new "*4" and "*6" productions creating a wildcard to match + * IPv4 or IPv6 addresses. + * + * If 'flags & TAPMP_EXTENDED_STAR' and 'flags & TAPMP_STAR_IPV4_ONLY' are + * both true, then the wildcard address '*' yields an IPv4 wildcard. + * + * If 'flags & TAPMP_EXTENDED_STAR' and 'flags & TAPMP_STAR_IPV6_ONLY' are + * both true, then the wildcard address '*' yields an IPv6 wildcard. + * + * TAPMP_STAR_IPV4_ONLY and TAPMP_STAR_IPV6_ONLY are mutually exclusive. */ +int +tor_addr_parse_mask_ports(const char *s, + unsigned flags, + tor_addr_t *addr_out, + maskbits_t *maskbits_out, + uint16_t *port_min_out, uint16_t *port_max_out) +{ + char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL; + char *endptr; + int any_flag=0, v4map=0; + sa_family_t family; + struct in6_addr in6_tmp; + struct in_addr in_tmp = { .s_addr = 0 }; + + tor_assert(s); + tor_assert(addr_out); + /* We can either only want an IPv4 address or only want an IPv6 address, + * but we can't only want IPv4 & IPv6 at the same time. */ + tor_assert(!((flags & TAPMP_STAR_IPV4_ONLY) + && (flags & TAPMP_STAR_IPV6_ONLY))); + + /** Longest possible length for an address, mask, and port-range combination. + * Includes IP, [], /mask, :, ports */ +#define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1) + + if (strlen(s) > MAX_ADDRESS_LENGTH) { + log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s)); + goto err; + } + base = tor_strdup(s); + + /* Break 'base' into separate strings. */ + address = base; + if (*address == '[') { /* Probably IPv6 */ + address++; + rbracket = strchr(address, ']'); + if (!rbracket) { + log_warn(LD_GENERAL, + "No closing IPv6 bracket in address pattern; rejecting."); + goto err; + } + } + mask = strchr((rbracket?rbracket:address),'/'); + port = strchr((mask?mask:(rbracket?rbracket:address)), ':'); + if (port) + *port++ = '\0'; + if (mask) + *mask++ = '\0'; + if (rbracket) + *rbracket = '\0'; + if (port && mask) + tor_assert(port > mask); + if (mask && rbracket) + tor_assert(mask > rbracket); + + /* Now "address" is the a.b.c.d|'*'|abcd::1 part... + * "mask" is the Mask|Maskbits part... + * and "port" is the *|port|min-max part. + */ + + /* Process the address portion */ + memset(addr_out, 0, sizeof(tor_addr_t)); + + if (!strcmp(address, "*")) { + if (flags & TAPMP_EXTENDED_STAR) { + if (flags & TAPMP_STAR_IPV4_ONLY) { + family = AF_INET; + tor_addr_from_ipv4h(addr_out, 0); + } else if (flags & TAPMP_STAR_IPV6_ONLY) { + static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; + family = AF_INET6; + tor_addr_from_ipv6_bytes(addr_out, nil_bytes); + } else { + family = AF_UNSPEC; + tor_addr_make_unspec(addr_out); + log_info(LD_GENERAL, + "'%s' expands into rules which apply to all IPv4 and IPv6 " + "addresses. (Use accept/reject *4:* for IPv4 or " + "accept[6]/reject[6] *6:* for IPv6.)", s); + } + } else { + family = AF_INET; + tor_addr_from_ipv4h(addr_out, 0); + } + any_flag = 1; + } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) { + family = AF_INET; + tor_addr_from_ipv4h(addr_out, 0); + any_flag = 1; + } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) { + static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; + family = AF_INET6; + tor_addr_from_ipv6_bytes(addr_out, nil_bytes); + any_flag = 1; + } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) { + family = AF_INET6; + tor_addr_from_in6(addr_out, &in6_tmp); + } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) { + family = AF_INET; + tor_addr_from_in(addr_out, &in_tmp); + } else { + log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.", + escaped(address)); + goto err; + } + + v4map = tor_addr_is_v4(addr_out); + + /* Parse mask */ + if (maskbits_out) { + int bits = 0; + struct in_addr v4mask; + + if (mask) { /* the caller (tried to) specify a mask */ + bits = (int) strtol(mask, &endptr, 10); + if (!*endptr) { /* strtol converted everything, so it was an integer */ + if ((bits<0 || bits>128) || + (family == AF_INET && bits > 32)) { + log_warn(LD_GENERAL, + "Bad number of mask bits (%d) on address range; rejecting.", + bits); + goto err; + } + } else { /* mask might still be an address-style mask */ + if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) { + bits = addr_mask_get_bits(ntohl(v4mask.s_addr)); + if (bits < 0) { + log_warn(LD_GENERAL, + "IPv4-style mask %s is not a prefix address; rejecting.", + escaped(mask)); + goto err; + } + } else { /* Not IPv4; we don't do address-style IPv6 masks. */ + log_warn(LD_GENERAL, + "Malformed mask on address range %s; rejecting.", + escaped(s)); + goto err; + } + } + if (family == AF_INET6 && v4map) { + if (bits > 32 && bits < 96) { /* Crazy */ + log_warn(LD_GENERAL, + "Bad mask bits %d for V4-mapped V6 address; rejecting.", + bits); + goto err; + } + /* XXXX_IP6 is this really what we want? */ + bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */ + } + if (any_flag) { + log_warn(LD_GENERAL, + "Found bit prefix with wildcard address; rejecting"); + goto err; + } + } else { /* pick an appropriate mask, as none was given */ + if (any_flag) + bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */ + else if (tor_addr_family(addr_out) == AF_INET) + bits = 32; + else if (tor_addr_family(addr_out) == AF_INET6) + bits = 128; + } + *maskbits_out = (maskbits_t) bits; + } else { + if (mask) { + log_warn(LD_GENERAL, + "Unexpected mask in address %s; rejecting", escaped(s)); + goto err; + } + } + + /* Parse port(s) */ + if (port_min_out) { + uint16_t port2; + if (!port_max_out) /* caller specified one port; fake the second one */ + port_max_out = &port2; + + if (parse_port_range(port, port_min_out, port_max_out) < 0) { + goto err; + } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) { + log_warn(LD_GENERAL, + "Wanted one port from address range, but there are two."); + + port_max_out = NULL; /* caller specified one port, so set this back */ + goto err; + } + } else { + if (port) { + log_warn(LD_GENERAL, + "Unexpected ports in address %s; rejecting", escaped(s)); + goto err; + } + } + + tor_free(base); + return tor_addr_family(addr_out); + err: + tor_free(base); + return -1; +} + +/** Determine whether an address is IPv4, either native or IPv4-mapped IPv6. + * Note that this is about representation only, as any decent stack will + * reject IPv4-mapped addresses received on the wire (and won't use them + * on the wire either). + */ +int +tor_addr_is_v4(const tor_addr_t *addr) +{ + tor_assert(addr); + + if (tor_addr_family(addr) == AF_INET) + return 1; + + if (tor_addr_family(addr) == AF_INET6) { + /* First two don't need to be ordered */ + uint32_t *a32 = tor_addr_to_in6_addr32(addr); + if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu) + return 1; + } + + return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */ +} + +/** Determine whether an address <b>addr</b> is null, either all zeroes or + * belonging to family AF_UNSPEC. + */ +int +tor_addr_is_null(const tor_addr_t *addr) +{ + tor_assert(addr); + + switch (tor_addr_family(addr)) { + case AF_INET6: { + uint32_t *a32 = tor_addr_to_in6_addr32(addr); + return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0); + } + case AF_INET: + return (tor_addr_to_ipv4n(addr) == 0); + case AF_UNIX: + return 1; + case AF_UNSPEC: + return 1; + default: + log_warn(LD_BUG, "Called with unknown address family %d", + (int)tor_addr_family(addr)); + return 0; + } + //return 1; +} + +/** Return true iff <b>addr</b> is a loopback address */ +int +tor_addr_is_loopback(const tor_addr_t *addr) +{ + tor_assert(addr); + switch (tor_addr_family(addr)) { + case AF_INET6: { + /* ::1 */ + uint32_t *a32 = tor_addr_to_in6_addr32(addr); + return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && + (ntohl(a32[3]) == 1); + } + case AF_INET: + /* 127.0.0.1 */ + return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000; + case AF_UNSPEC: + return 0; + /* LCOV_EXCL_START */ + default: + tor_fragile_assert(); + return 0; + /* LCOV_EXCL_STOP */ + } +} + +/* Is addr valid? + * Checks that addr is non-NULL and not tor_addr_is_null(). + * If for_listening is true, IPv4 addr 0.0.0.0 is allowed. + * It means "bind to all addresses on the local machine". */ +int +tor_addr_is_valid(const tor_addr_t *addr, int for_listening) +{ + /* NULL addresses are invalid regardless of for_listening */ + if (addr == NULL) { + return 0; + } + + /* Only allow IPv4 0.0.0.0 for_listening. */ + if (for_listening && addr->family == AF_INET + && tor_addr_to_ipv4h(addr) == 0) { + return 1; + } + + /* Otherwise, the address is valid if it's not tor_addr_is_null() */ + return !tor_addr_is_null(addr); +} + +/* Is the network-order IPv4 address v4n_addr valid? + * Checks that addr is not zero. + * Except if for_listening is true, where IPv4 addr 0.0.0.0 is allowed. */ +int +tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening) +{ + /* Any IPv4 address is valid with for_listening. */ + if (for_listening) { + return 1; + } + + /* Otherwise, zero addresses are invalid. */ + return v4n_addr != 0; +} + +/* Is port valid? + * Checks that port is not 0. + * Except if for_listening is true, where port 0 is allowed. + * It means "OS chooses a port". */ +int +tor_port_is_valid(uint16_t port, int for_listening) +{ + /* Any port value is valid with for_listening. */ + if (for_listening) { + return 1; + } + + /* Otherwise, zero ports are invalid. */ + return port != 0; +} + +/** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in + * network order). */ +void +tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr) +{ + tor_assert(dest); + memset(dest, 0, sizeof(tor_addr_t)); + dest->family = AF_INET; + dest->addr.in_addr.s_addr = v4addr; +} + +/** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at + * <b>ipv6_bytes</b>. */ +void +tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes) +{ + tor_assert(dest); + tor_assert(ipv6_bytes); + memset(dest, 0, sizeof(tor_addr_t)); + dest->family = AF_INET6; + memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16); +} + +/** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */ +void +tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6) +{ + tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr); +} + +/** Copy a tor_addr_t from <b>src</b> to <b>dest</b>. + */ +void +tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src) +{ + if (src == dest) + return; + tor_assert(src); + tor_assert(dest); + memcpy(dest, src, sizeof(tor_addr_t)); +} + +/** Copy a tor_addr_t from <b>src</b> to <b>dest</b>, taking extra care to + * copy only the well-defined portions. Used for computing hashes of + * addresses. + */ +void +tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src) +{ + tor_assert(src != dest); + tor_assert(src); + tor_assert(dest); + memset(dest, 0, sizeof(tor_addr_t)); + dest->family = src->family; + switch (tor_addr_family(src)) + { + case AF_INET: + dest->addr.in_addr.s_addr = src->addr.in_addr.s_addr; + break; + case AF_INET6: + memcpy(dest->addr.in6_addr.s6_addr, src->addr.in6_addr.s6_addr, 16); + case AF_UNSPEC: + break; + // LCOV_EXCL_START + default: + tor_fragile_assert(); + // LCOV_EXCL_STOP + } +} + +/** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two + * addresses are equivalent under the mask mbits, less than 0 if addr1 + * precedes addr2, and greater than 0 otherwise. + * + * Different address families (IPv4 vs IPv6) are always considered unequal if + * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are + * considered equivalent to their IPv4 equivalents. + * + * As a special case, all pointer-wise distinct AF_UNIX addresses are always + * considered unequal since tor_addr_t currently does not contain the + * information required to make the comparison. + */ +int +tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, + tor_addr_comparison_t how) +{ + return tor_addr_compare_masked(addr1, addr2, 128, how); +} + +/** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of + * the address. + * + * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32. + * + * The mask is interpreted relative to <b>addr1</b>, so that if a is + * \::ffff:1.2.3.4, and b is 3.4.5.6, + * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as + * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC). + * + * We guarantee that the ordering from tor_addr_compare_masked is a total + * order on addresses, but not that it is any particular order, or that it + * will be the same from one version to the next. + */ +int +tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2, + maskbits_t mbits, tor_addr_comparison_t how) +{ + /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a + * is greater than b. May evaluate a and b more than once. */ +#define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1)) + sa_family_t family1, family2, v_family1, v_family2; + + tor_assert(addr1 && addr2); + + v_family1 = family1 = tor_addr_family(addr1); + v_family2 = family2 = tor_addr_family(addr2); + + if (family1==family2) { + /* When the families are the same, there's only one way to do the + * comparison: exactly. */ + int r; + switch (family1) { + case AF_UNSPEC: + return 0; /* All unspecified addresses are equal */ + case AF_INET: { + uint32_t a1 = tor_addr_to_ipv4h(addr1); + uint32_t a2 = tor_addr_to_ipv4h(addr2); + if (mbits <= 0) + return 0; + if (mbits > 32) + mbits = 32; + a1 >>= (32-mbits); + a2 >>= (32-mbits); + r = TRISTATE(a1, a2); + return r; + } + case AF_INET6: { + if (mbits > 128) + mbits = 128; + + const uint8_t *a1 = tor_addr_to_in6_addr8(addr1); + const uint8_t *a2 = tor_addr_to_in6_addr8(addr2); + const int bytes = mbits >> 3; + const int leftover_bits = mbits & 7; + if (bytes && (r = tor_memcmp(a1, a2, bytes))) { + return r; + } else if (leftover_bits) { + uint8_t b1 = a1[bytes] >> (8-leftover_bits); + uint8_t b2 = a2[bytes] >> (8-leftover_bits); + return TRISTATE(b1, b2); + } else { + return 0; + } + } + case AF_UNIX: + /* HACKHACKHACKHACKHACK: + * tor_addr_t doesn't contain a copy of sun_path, so it's not + * possible to compare this at all. + * + * Since the only time we currently actually should be comparing + * 2 AF_UNIX addresses is when dealing with ISO_CLIENTADDR (which + * is disabled for AF_UNIX SocksPorts anyway), this just does + * a pointer comparison. + * + * See: #20261. + */ + if (addr1 < addr2) + return -1; + else if (addr1 == addr2) + return 0; + else + return 1; + /* LCOV_EXCL_START */ + default: + tor_fragile_assert(); + return 0; + /* LCOV_EXCL_STOP */ + } + } else if (how == CMP_EXACT) { + /* Unequal families and an exact comparison? Stop now! */ + return TRISTATE(family1, family2); + } + + if (mbits == 0) + return 0; + + if (family1 == AF_INET6 && tor_addr_is_v4(addr1)) + v_family1 = AF_INET; + if (family2 == AF_INET6 && tor_addr_is_v4(addr2)) + v_family2 = AF_INET; + if (v_family1 == v_family2) { + /* One or both addresses are a mapped ipv4 address. */ + uint32_t a1, a2; + if (family1 == AF_INET6) { + a1 = tor_addr_to_mapped_ipv4h(addr1); + if (mbits <= 96) + return 0; + mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */ + } else { + a1 = tor_addr_to_ipv4h(addr1); + } + if (family2 == AF_INET6) { + a2 = tor_addr_to_mapped_ipv4h(addr2); + } else { + a2 = tor_addr_to_ipv4h(addr2); + } + if (mbits > 32) mbits = 32; + a1 >>= (32-mbits); + a2 >>= (32-mbits); + return TRISTATE(a1, a2); + } else { + /* Unequal families, and semantic comparison, and no semantic family + * matches. */ + return TRISTATE(family1, family2); + } +} + +/** Input for siphash, to produce some output for an unspec value. */ +static const uint32_t unspec_hash_input[] = { 0x4e4df09f, 0x92985342 }; + +/** Return a hash code based on the address addr. DOCDOC extra */ +uint64_t +tor_addr_hash(const tor_addr_t *addr) +{ + switch (tor_addr_family(addr)) { + case AF_INET: + return siphash24g(&addr->addr.in_addr.s_addr, 4); + case AF_UNSPEC: + return siphash24g(unspec_hash_input, sizeof(unspec_hash_input)); + case AF_INET6: + return siphash24g(&addr->addr.in6_addr.s6_addr, 16); + /* LCOV_EXCL_START */ + default: + tor_fragile_assert(); + return 0; + /* LCOV_EXCL_STOP */ + } +} + +/** As tor_addr_hash, but use a particular siphash key. */ +uint64_t +tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr) +{ + /* This is duplicate code with tor_addr_hash, since this function needs to + * be backportable all the way to 0.2.9. */ + + switch (tor_addr_family(addr)) { + case AF_INET: + return siphash24(&addr->addr.in_addr.s_addr, 4, key); + case AF_UNSPEC: + return siphash24(unspec_hash_input, sizeof(unspec_hash_input), key); + case AF_INET6: + return siphash24(&addr->addr.in6_addr.s6_addr, 16, key); + default: + /* LCOV_EXCL_START */ + tor_fragile_assert(); + return 0; + /* LCOV_EXCL_STOP */ + } +} + +/** Return a newly allocated string with a representation of <b>addr</b>. */ +char * +tor_addr_to_str_dup(const tor_addr_t *addr) +{ + char buf[TOR_ADDR_BUF_LEN]; + if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) { + return tor_strdup(buf); + } else { + return tor_strdup("<unknown address type>"); + } +} + +/** Return a string representing the address <b>addr</b>. This string + * is statically allocated, and must not be freed. Each call to + * <b>fmt_addr_impl</b> invalidates the last result of the function. + * This function is not thread-safe. If <b>decorate</b> is set, add + * brackets to IPv6 addresses. + * + * It's better to use the wrapper macros of this function: + * <b>fmt_addr()</b> and <b>fmt_and_decorate_addr()</b>. + */ +const char * +fmt_addr_impl(const tor_addr_t *addr, int decorate) +{ + static char buf[TOR_ADDR_BUF_LEN]; + if (!addr) return "<null>"; + if (tor_addr_to_str(buf, addr, sizeof(buf), decorate)) + return buf; + else + return "???"; +} + +/** Return a string representing the pair <b>addr</b> and <b>port</b>. + * This calls fmt_and_decorate_addr internally, so IPv6 addresses will + * have brackets, and the caveats of fmt_addr_impl apply. + */ +const char * +fmt_addrport(const tor_addr_t *addr, uint16_t port) +{ + /* Add space for a colon and up to 5 digits. */ + static char buf[TOR_ADDR_BUF_LEN + 6]; + tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port); + return buf; +} + +/** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4 + * addresses. Also not thread-safe, also clobbers its return buffer on + * repeated calls. */ +const char * +fmt_addr32(uint32_t addr) +{ + static char buf[INET_NTOA_BUF_LEN]; + struct in_addr in; + in.s_addr = htonl(addr); + tor_inet_ntoa(&in, buf, sizeof(buf)); + return buf; +} + +/** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string + * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by + * square brackets. + * + * Return an address family on success, or -1 if an invalid address string is + * provided. */ +int +tor_addr_parse(tor_addr_t *addr, const char *src) +{ + /* Holds substring of IPv6 address after removing square brackets */ + char *tmp = NULL; + int result; + struct in_addr in_tmp; + struct in6_addr in6_tmp; + tor_assert(addr && src); + if (src[0] == '[' && src[1]) + src = tmp = tor_strndup(src+1, strlen(src)-2); + + if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) { + result = AF_INET6; + tor_addr_from_in6(addr, &in6_tmp); + } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) { + result = AF_INET; + tor_addr_from_in(addr, &in_tmp); + } else { + result = -1; + } + + tor_free(tmp); + return result; +} + +#ifdef HAVE_IFADDRS_TO_SMARTLIST +/* + * Convert a linked list consisting of <b>ifaddrs</b> structures + * into smartlist of <b>tor_addr_t</b> structures. + */ +STATIC smartlist_t * +ifaddrs_to_smartlist(const struct ifaddrs *ifa, sa_family_t family) +{ + smartlist_t *result = smartlist_new(); + const struct ifaddrs *i; + + for (i = ifa; i; i = i->ifa_next) { + tor_addr_t tmp; + if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING)) + continue; + if (!i->ifa_addr) + continue; + if (i->ifa_addr->sa_family != AF_INET && + i->ifa_addr->sa_family != AF_INET6) + continue; + if (family != AF_UNSPEC && i->ifa_addr->sa_family != family) + continue; + if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0) + continue; + smartlist_add(result, tor_memdup(&tmp, sizeof(tmp))); + } + + return result; +} + +/** Use getiffaddrs() function to get list of current machine + * network interface addresses. Represent the result by smartlist of + * <b>tor_addr_t</b> structures. + */ +STATIC smartlist_t * +get_interface_addresses_ifaddrs(int severity, sa_family_t family) +{ + + /* Most free Unixy systems provide getifaddrs, which gives us a linked list + * of struct ifaddrs. */ + struct ifaddrs *ifa = NULL; + smartlist_t *result; + if (getifaddrs(&ifa) < 0) { + log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s", + strerror(errno)); + return NULL; + } + + result = ifaddrs_to_smartlist(ifa, family); + + freeifaddrs(ifa); + + return result; +} +#endif /* defined(HAVE_IFADDRS_TO_SMARTLIST) */ + +#ifdef HAVE_IP_ADAPTER_TO_SMARTLIST + +/** Convert a Windows-specific <b>addresses</b> linked list into smartlist + * of <b>tor_addr_t</b> structures. + */ + +STATIC smartlist_t * +ip_adapter_addresses_to_smartlist(const IP_ADAPTER_ADDRESSES *addresses) +{ + smartlist_t *result = smartlist_new(); + const IP_ADAPTER_ADDRESSES *address; + + for (address = addresses; address; address = address->Next) { + const IP_ADAPTER_UNICAST_ADDRESS *a; + for (a = address->FirstUnicastAddress; a; a = a->Next) { + /* Yes, it's a linked list inside a linked list */ + const struct sockaddr *sa = a->Address.lpSockaddr; + tor_addr_t tmp; + if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6) + continue; + if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0) + continue; + smartlist_add(result, tor_memdup(&tmp, sizeof(tmp))); + } + } + + return result; +} + +/** Windows only: use GetAdaptersAddresses() to retrieve the network interface + * addresses of the current machine. + * Returns a smartlist of <b>tor_addr_t</b> structures. + */ +STATIC smartlist_t * +get_interface_addresses_win32(int severity, sa_family_t family) +{ + smartlist_t *result = NULL; + ULONG size, res; + IP_ADAPTER_ADDRESSES *addresses = NULL; + + (void) severity; + +#define FLAGS (GAA_FLAG_SKIP_ANYCAST | \ + GAA_FLAG_SKIP_MULTICAST | \ + GAA_FLAG_SKIP_DNS_SERVER) + + /* Guess how much space we need. */ + size = 15*1024; + addresses = tor_malloc(size); + /* Exists in windows XP and later. */ + res = GetAdaptersAddresses(family, FLAGS, NULL, addresses, &size); + if (res == ERROR_BUFFER_OVERFLOW) { + /* we didn't guess that we needed enough space; try again */ + tor_free(addresses); + addresses = tor_malloc(size); + res = GetAdaptersAddresses(AF_UNSPEC, FLAGS, NULL, addresses, &size); + } + if (res != NO_ERROR) { + log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res); + goto done; + } + + result = ip_adapter_addresses_to_smartlist(addresses); + + done: + tor_free(addresses); + return result; +} + +#endif /* defined(HAVE_IP_ADAPTER_TO_SMARTLIST) */ + +#ifdef HAVE_IFCONF_TO_SMARTLIST + +/* Guess how much space we need. There shouldn't be any struct ifreqs + * larger than this, even on OS X where the struct's size is dynamic. */ +#define IFREQ_SIZE 4096 + +/* This is defined on Mac OS X */ +#ifndef _SIZEOF_ADDR_IFREQ +#define _SIZEOF_ADDR_IFREQ sizeof +#endif + +/* Free ifc->ifc_buf safely. */ +static void +ifconf_free_ifc_buf(struct ifconf *ifc) +{ + /* On macOS, tor_free() takes the address of ifc.ifc_buf, which leads to + * undefined behaviour, because pointer-to-pointers are expected to be + * aligned at 8-bytes, but the ifconf structure is packed. So we use + * raw_free() instead. */ + raw_free(ifc->ifc_buf); + ifc->ifc_buf = NULL; +} + +/** Convert <b>*buf</b>, an ifreq structure array of size <b>buflen</b>, + * into smartlist of <b>tor_addr_t</b> structures. + */ +STATIC smartlist_t * +ifreq_to_smartlist(char *buf, size_t buflen) +{ + smartlist_t *result = smartlist_new(); + char *end = buf + buflen; + + /* These acrobatics are due to alignment issues which trigger + * undefined behaviour traps on OSX. */ + struct ifreq *r = tor_malloc(IFREQ_SIZE); + + while (buf < end) { + /* Copy up to IFREQ_SIZE bytes into the struct ifreq, but don't overrun + * buf. */ + memcpy(r, buf, end - buf < IFREQ_SIZE ? end - buf : IFREQ_SIZE); + + const struct sockaddr *sa = &r->ifr_addr; + tor_addr_t tmp; + int valid_sa_family = (sa->sa_family == AF_INET || + sa->sa_family == AF_INET6); + + int conversion_success = (tor_addr_from_sockaddr(&tmp, sa, NULL) == 0); + + if (valid_sa_family && conversion_success) + smartlist_add(result, tor_memdup(&tmp, sizeof(tmp))); + + buf += _SIZEOF_ADDR_IFREQ(*r); + } + + tor_free(r); + return result; +} + +/** Use ioctl(.,SIOCGIFCONF,.) to get a list of current machine + * network interface addresses. Represent the result by smartlist of + * <b>tor_addr_t</b> structures. + */ +STATIC smartlist_t * +get_interface_addresses_ioctl(int severity, sa_family_t family) +{ + /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */ + struct ifconf ifc; + ifc.ifc_buf = NULL; + int fd; + smartlist_t *result = NULL; + + /* This interface, AFAICT, only supports AF_INET addresses, + * except on AIX. For Solaris, we could use SIOCGLIFCONF. */ + + /* Bail out if family is neither AF_INET nor AF_UNSPEC since + * ioctl() technique supports non-IPv4 interface addresses on + * a small number of niche systems only. If family is AF_UNSPEC, + * fall back to getting AF_INET addresses only. */ + if (family == AF_UNSPEC) + family = AF_INET; + else if (family != AF_INET) + return NULL; + + fd = socket(family, SOCK_DGRAM, 0); + if (fd < 0) { + tor_log(severity, LD_NET, "socket failed: %s", strerror(errno)); + goto done; + } + + int mult = 1; + do { + mult *= 2; + ifc.ifc_len = mult * IFREQ_SIZE; + ifc.ifc_buf = tor_realloc(ifc.ifc_buf, ifc.ifc_len); + + tor_assert(ifc.ifc_buf); + + if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) { + tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno)); + goto done; + } + /* Ensure we have least IFREQ_SIZE bytes unused at the end. Otherwise, we + * don't know if we got everything during ioctl. */ + } while (mult * IFREQ_SIZE - ifc.ifc_len <= IFREQ_SIZE); + result = ifreq_to_smartlist(ifc.ifc_buf, ifc.ifc_len); + + done: + if (fd >= 0) + close(fd); + ifconf_free_ifc_buf(&ifc); + return result; +} +#endif /* defined(HAVE_IFCONF_TO_SMARTLIST) */ + +/** Try to ask our network interfaces what addresses they are bound to. + * Return a new smartlist of tor_addr_t on success, and NULL on failure. + * (An empty smartlist indicates that we successfully learned that we have no + * addresses.) Log failure messages at <b>severity</b>. Only return the + * interface addresses of requested <b>family</b> and ignore the addresses + * of other address families. */ +MOCK_IMPL(smartlist_t *, +get_interface_addresses_raw,(int severity, sa_family_t family)) +{ + smartlist_t *result = NULL; +#if defined(HAVE_IFADDRS_TO_SMARTLIST) + if ((result = get_interface_addresses_ifaddrs(severity, family))) + return result; +#endif +#if defined(HAVE_IP_ADAPTER_TO_SMARTLIST) + if ((result = get_interface_addresses_win32(severity, family))) + return result; +#endif +#if defined(HAVE_IFCONF_TO_SMARTLIST) + if ((result = get_interface_addresses_ioctl(severity, family))) + return result; +#endif + (void) severity; + (void) result; + return NULL; +} + +/** Return true iff <b>a</b> is a multicast address. */ +int +tor_addr_is_multicast(const tor_addr_t *a) +{ + sa_family_t family = tor_addr_family(a); + if (family == AF_INET) { + uint32_t ipv4h = tor_addr_to_ipv4h(a); + if ((ipv4h >> 24) == 0xe0) + return 1; /* Multicast */ + } else if (family == AF_INET6) { + const uint8_t *a32 = tor_addr_to_in6_addr8(a); + if (a32[0] == 0xff) + return 1; + } + return 0; +} + +/** Attempt to retrieve IP address of current host by utilizing some + * UDP socket trickery. Only look for address of given <b>family</b> + * (only AF_INET and AF_INET6 are supported). Set result to *<b>addr</b>. + * Return 0 on success, -1 on failure. + */ +MOCK_IMPL(int, +get_interface_address6_via_udp_socket_hack,(int severity, + sa_family_t family, + tor_addr_t *addr)) +{ + struct sockaddr_storage target_addr; + int sock=-1, r=-1; + socklen_t addr_len; + + memset(addr, 0, sizeof(tor_addr_t)); + memset(&target_addr, 0, sizeof(target_addr)); + + /* Don't worry: no packets are sent. We just need to use a real address + * on the actual Internet. */ + if (family == AF_INET6) { + struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr; + /* Use the "discard" service port */ + sin6->sin6_port = htons(9); + sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP); + addr_len = (socklen_t)sizeof(struct sockaddr_in6); + sin6->sin6_family = AF_INET6; + S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */ + } else if (family == AF_INET) { + struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr; + /* Use the "discard" service port */ + sin->sin_port = htons(9); + sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP); + addr_len = (socklen_t)sizeof(struct sockaddr_in); + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */ + } else { + return -1; + } + + if (sock < 0) { + int e = tor_socket_errno(-1); + log_fn(severity, LD_NET, "unable to create socket: %s", + tor_socket_strerror(e)); + goto err; + } + + if (tor_connect_socket(sock,(struct sockaddr *)&target_addr, + addr_len) < 0) { + int e = tor_socket_errno(sock); + log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e)); + goto err; + } + + if (tor_addr_from_getsockname(addr, sock) < 0) { + int e = tor_socket_errno(sock); + log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s", + tor_socket_strerror(e)); + goto err; + } + + if (tor_addr_is_loopback(addr) || tor_addr_is_multicast(addr)) { + log_fn(severity, LD_NET, "Address that we determined via UDP socket" + " magic is unsuitable for public comms."); + } else { + r=0; + } + + err: + if (sock >= 0) + tor_close_socket(sock); + if (r == -1) + memset(addr, 0, sizeof(tor_addr_t)); + return r; +} + +/** Set *<b>addr</b> to an arbitrary IP address (if any) of an interface that + * connects to the Internet. Prefer public IP addresses to internal IP + * addresses. This address should only be used in checking whether our + * address has changed, as it may be an internal IP address. Return 0 on + * success, -1 on failure. + * Prefer get_interface_address6_list for a list of all addresses on all + * interfaces which connect to the Internet. + */ +MOCK_IMPL(int, +get_interface_address6,(int severity, sa_family_t family, tor_addr_t *addr)) +{ + smartlist_t *addrs; + int rv = -1; + tor_assert(addr); + + memset(addr, 0, sizeof(tor_addr_t)); + + /* Get a list of public or internal IPs in arbitrary order */ + addrs = get_interface_address6_list(severity, family, 1); + + /* Find the first non-internal address, or the last internal address + * Ideally, we want the default route, see #12377 for details */ + SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) { + tor_addr_copy(addr, a); + rv = 0; + + /* If we found a non-internal address, declare success. Otherwise, + * keep looking. */ + if (!tor_addr_is_internal(a, 0)) + break; + } SMARTLIST_FOREACH_END(a); + + interface_address6_list_free(addrs); + return rv; +} + +/** Free a smartlist of IP addresses returned by get_interface_address6_list. + */ +void +interface_address6_list_free_(smartlist_t *addrs) +{ + if (addrs != NULL) { + SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a)); + smartlist_free(addrs); + } +} + +/** Return a smartlist of the IP addresses of type family from all interfaces + * on the server. Excludes loopback and multicast addresses. Only includes + * internal addresses if include_internal is true. (Note that a relay behind + * NAT may use an internal address to connect to the Internet.) + * An empty smartlist means that there are no addresses of the selected type + * matching these criteria. + * Returns NULL on failure. + * Use interface_address6_list_free to free the returned list. + */ +MOCK_IMPL(smartlist_t *, +get_interface_address6_list,(int severity, + sa_family_t family, + int include_internal)) +{ + smartlist_t *addrs; + tor_addr_t addr; + + /* Try to do this the smart way if possible. */ + if ((addrs = get_interface_addresses_raw(severity, family))) { + SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) + { + if (tor_addr_is_loopback(a) || + tor_addr_is_multicast(a)) { + SMARTLIST_DEL_CURRENT_KEEPORDER(addrs, a); + tor_free(a); + continue; + } + + if (!include_internal && tor_addr_is_internal(a, 0)) { + SMARTLIST_DEL_CURRENT_KEEPORDER(addrs, a); + tor_free(a); + continue; + } + } SMARTLIST_FOREACH_END(a); + } + + if (addrs && smartlist_len(addrs) > 0) { + return addrs; + } + + /* if we removed all entries as unsuitable */ + if (addrs) { + smartlist_free(addrs); + } + + /* Okay, the smart way is out. */ + addrs = smartlist_new(); + + if (family == AF_INET || family == AF_UNSPEC) { + if (get_interface_address6_via_udp_socket_hack(severity,AF_INET, + &addr) == 0) { + if (include_internal || !tor_addr_is_internal(&addr, 0)) { + smartlist_add(addrs, tor_memdup(&addr, sizeof(addr))); + } + } + } + + if (family == AF_INET6 || family == AF_UNSPEC) { + if (get_interface_address6_via_udp_socket_hack(severity,AF_INET6, + &addr) == 0) { + if (include_internal || !tor_addr_is_internal(&addr, 0)) { + smartlist_add(addrs, tor_memdup(&addr, sizeof(addr))); + } + } + } + + return addrs; +} + +/* ====== + * IPv4 helpers + * XXXX IPv6 deprecate some of these. + */ + +/** Given an address of the form "ip:port", try to divide it into its + * ip and port portions, setting *<b>address_out</b> to a newly + * allocated string holding the address portion and *<b>port_out</b> + * to the port. + * + * Don't do DNS lookups and don't allow domain names in the "ip" field. + * + * If <b>default_port</b> is less than 0, don't accept <b>addrport</b> of the + * form "ip" or "ip:0". Otherwise, accept those forms, and set + * *<b>port_out</b> to <b>default_port</b>. + * + * Return 0 on success, -1 on failure. */ +int +tor_addr_port_parse(int severity, const char *addrport, + tor_addr_t *address_out, uint16_t *port_out, + int default_port) +{ + int retval = -1; + int r; + char *addr_tmp = NULL; + + tor_assert(addrport); + tor_assert(address_out); + tor_assert(port_out); + + r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out); + if (r < 0) + goto done; + + if (!*port_out) { + if (default_port >= 0) + *port_out = default_port; + else + goto done; + } + + /* make sure that address_out is an IP address */ + if (tor_addr_parse(address_out, addr_tmp) < 0) + goto done; + + retval = 0; + + done: + tor_free(addr_tmp); + return retval; +} + +/** Given an address of the form "host[:port]", try to divide it into its host + * and port portions, setting *<b>address_out</b> to a newly allocated string + * holding the address portion and *<b>port_out</b> to the port (or 0 if no + * port is given). Return 0 on success, -1 on failure. */ +int +tor_addr_port_split(int severity, const char *addrport, + char **address_out, uint16_t *port_out) +{ + tor_addr_t a_tmp; + tor_assert(addrport); + tor_assert(address_out); + tor_assert(port_out); + /* We need to check for IPv6 manually because the logic below doesn't + * do a good job on IPv6 addresses that lack a port. */ + if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) { + *port_out = 0; + *address_out = tor_strdup(addrport); + return 0; + } + + const char *colon; + char *address_ = NULL; + int port_; + int ok = 1; + + colon = strrchr(addrport, ':'); + if (colon) { + address_ = tor_strndup(addrport, colon-addrport); + port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL); + if (!port_) { + log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1)); + ok = 0; + } + if (!port_out) { + char *esc_addrport = esc_for_log(addrport); + log_fn(severity, LD_GENERAL, + "Port %s given on %s when not required", + escaped(colon+1), esc_addrport); + tor_free(esc_addrport); + ok = 0; + } + } else { + address_ = tor_strdup(addrport); + port_ = 0; + } + + if (ok) { + *address_out = address_; + } else { + *address_out = NULL; + tor_free(address_); + } + + if (port_out) + *port_out = ok ? ((uint16_t) port_) : 0; + + return ok ? 0 : -1; +} + +/** If <b>mask</b> is an address mask for a bit-prefix, return the number of + * bits. Otherwise, return -1. */ +int +addr_mask_get_bits(uint32_t mask) +{ + int i; + if (mask == 0) + return 0; + if (mask == 0xFFFFFFFFu) + return 32; + for (i=1; i<=32; ++i) { + if (mask == (uint32_t) ~((1u<<(32-i))-1)) { + return i; + } + } + return -1; +} + +/** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the + * various *out pointers as appropriate. Return 0 on success, -1 on failure. + */ +int +parse_port_range(const char *port, uint16_t *port_min_out, + uint16_t *port_max_out) +{ + int port_min, port_max, ok; + tor_assert(port_min_out); + tor_assert(port_max_out); + + if (!port || *port == '\0' || strcmp(port, "*") == 0) { + port_min = 1; + port_max = 65535; + } else { + char *endptr = NULL; + port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr); + if (!ok) { + log_warn(LD_GENERAL, + "Malformed port %s on address range; rejecting.", + escaped(port)); + return -1; + } else if (endptr && *endptr == '-') { + port = endptr+1; + endptr = NULL; + port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr); + if (!ok) { + log_warn(LD_GENERAL, + "Malformed port %s on address range; rejecting.", + escaped(port)); + return -1; + } + } else { + port_max = port_min; + } + if (port_min > port_max) { + log_warn(LD_GENERAL, "Insane port range on address policy; rejecting."); + return -1; + } + } + + if (port_min < 1) + port_min = 1; + if (port_max > 65535) + port_max = 65535; + + *port_min_out = (uint16_t) port_min; + *port_max_out = (uint16_t) port_max; + + return 0; +} + +/** Given a host-order <b>addr</b>, call tor_inet_ntop() on it + * and return a strdup of the resulting address. + */ +char * +tor_dup_ip(uint32_t addr) +{ + char buf[TOR_ADDR_BUF_LEN]; + struct in_addr in; + + in.s_addr = htonl(addr); + tor_inet_ntop(AF_INET, &in, buf, sizeof(buf)); + return tor_strdup(buf); +} + +/** + * Set *<b>addr</b> to a host-order IPv4 address (if any) of an + * interface that connects to the Internet. Prefer public IP addresses to + * internal IP addresses. This address should only be used in checking + * whether our address has changed, as it may be an internal IPv4 address. + * Return 0 on success, -1 on failure. + * Prefer get_interface_address_list6 for a list of all IPv4 and IPv6 + * addresses on all interfaces which connect to the Internet. + */ +MOCK_IMPL(int, +get_interface_address,(int severity, uint32_t *addr)) +{ + tor_addr_t local_addr; + int r; + + memset(addr, 0, sizeof(uint32_t)); + + r = get_interface_address6(severity, AF_INET, &local_addr); + if (r>=0) + *addr = tor_addr_to_ipv4h(&local_addr); + return r; +} + +/** Return true if we can tell that <b>name</b> is a canonical name for the + * loopback address. Return true also for *.local hostnames, which are + * multicast DNS names for hosts on the local network. */ +int +tor_addr_hostname_is_local(const char *name) +{ + return !strcasecmp(name, "localhost") || + !strcasecmp(name, "local") || + !strcasecmpend(name, ".local"); +} + +/** Return a newly allocated tor_addr_port_t with <b>addr</b> and + <b>port</b> filled in. */ +tor_addr_port_t * +tor_addr_port_new(const tor_addr_t *addr, uint16_t port) +{ + tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t)); + if (addr) + tor_addr_copy(&ap->addr, addr); + ap->port = port; + return ap; +} + +/** Return true iff <a>a</b> and <b>b</b> are the same address and port */ +int +tor_addr_port_eq(const tor_addr_port_t *a, + const tor_addr_port_t *b) +{ + return tor_addr_eq(&a->addr, &b->addr) && a->port == b->port; +} + +/** Return true if <b>string</b> represents a valid IPv4 adddress in + * 'a.b.c.d' form. + */ +int +string_is_valid_ipv4_address(const char *string) +{ + struct in_addr addr; + + return (tor_inet_pton(AF_INET,string,&addr) == 1); +} + +/** Return true if <b>string</b> represents a valid IPv6 address in + * a form that inet_pton() can parse. + */ +int +string_is_valid_ipv6_address(const char *string) +{ + struct in6_addr addr; + + return (tor_inet_pton(AF_INET6,string,&addr) == 1); +} + +/** Return true iff <b>string</b> is a valid destination address, + * i.e. either a DNS hostname or IPv4/IPv6 address string. + */ +int +string_is_valid_dest(const char *string) +{ + char *tmp = NULL; + int retval; + size_t len; + + if (string == NULL) + return 0; + + len = strlen(string); + + if (len == 0) + return 0; + + if (string[0] == '[' && string[len - 1] == ']') + string = tmp = tor_strndup(string + 1, len - 2); + + retval = string_is_valid_ipv4_address(string) || + string_is_valid_ipv6_address(string) || + string_is_valid_nonrfc_hostname(string); + + tor_free(tmp); + + return retval; +} + +/** Return true iff <b>string</b> matches a pattern of DNS names + * that we allow Tor clients to connect to. + * + * Note: This allows certain technically invalid characters ('_') to cope + * with misconfigured zones that have been encountered in the wild. + */ +int +string_is_valid_nonrfc_hostname(const char *string) +{ + int result = 1; + int has_trailing_dot; + char *last_label; + smartlist_t *components; + + if (!string || strlen(string) == 0) + return 0; + + if (string_is_valid_ipv4_address(string)) + return 0; + + components = smartlist_new(); + + smartlist_split_string(components,string,".",0,0); + + if (BUG(smartlist_len(components) == 0)) + return 0; // LCOV_EXCL_LINE should be impossible given the earlier checks. + + /* Allow a single terminating '.' used rarely to indicate domains + * are FQDNs rather than relative. */ + last_label = (char *)smartlist_get(components, + smartlist_len(components) - 1); + has_trailing_dot = (last_label[0] == '\0'); + if (has_trailing_dot) { + smartlist_pop_last(components); + tor_free(last_label); + last_label = NULL; + } + + SMARTLIST_FOREACH_BEGIN(components, char *, c) { + if ((c[0] == '-') || (*c == '_')) { + result = 0; + break; + } + + do { + result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_')); + c++; + } while (result && *c); + + if (result == 0) { + break; + } + } SMARTLIST_FOREACH_END(c); + + SMARTLIST_FOREACH_BEGIN(components, char *, c) { + tor_free(c); + } SMARTLIST_FOREACH_END(c); + + smartlist_free(components); + + return result; +} diff --git a/src/lib/net/address.h b/src/lib/net/address.h new file mode 100644 index 0000000000..e857b4068b --- /dev/null +++ b/src/lib/net/address.h @@ -0,0 +1,388 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file address.h + * \brief Headers for address.h + **/ + +#ifndef TOR_ADDRESS_H +#define TOR_ADDRESS_H + +#include "orconfig.h" +#include "lib/cc/torint.h" +#include "lib/log/util_bug.h" +#include "lib/net/inaddr_st.h" +#include "lib/net/nettypes.h" + +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef _WIN32 +#include <winsock2.h> +#include <windows.h> +#endif + +#include <stddef.h> +#include <stdlib.h> + +#ifdef ADDRESS_PRIVATE + +#if defined(HAVE_SYS_IOCTL_H) +#include <sys/ioctl.h> +#endif + +#ifdef HAVE_GETIFADDRS +#define HAVE_IFADDRS_TO_SMARTLIST +#endif + +#ifdef _WIN32 +#define HAVE_IP_ADAPTER_TO_SMARTLIST +#endif + +#if defined(SIOCGIFCONF) && defined(HAVE_IOCTL) +#define HAVE_IFCONF_TO_SMARTLIST +#endif + +#if defined(HAVE_NET_IF_H) +#include <net/if.h> // for struct ifconf +#endif + +#if defined(HAVE_IFADDRS_TO_SMARTLIST) +#include <ifaddrs.h> +#endif + +// TODO win32 specific includes +#endif /* defined(ADDRESS_PRIVATE) */ + +/** The number of bits from an address to consider while doing a masked + * comparison. */ +typedef uint8_t maskbits_t; + +struct in_addr; +/** Holds an IPv4 or IPv6 address. (Uses less memory than struct + * sockaddr_storage.) */ +typedef struct tor_addr_t +{ + sa_family_t family; + union { + uint32_t dummy_; /* This field is here so we have something to initialize + * with a reliable cross-platform type. */ + struct in_addr in_addr; + struct in6_addr in6_addr; + } addr; +} tor_addr_t; + +/** Holds an IP address and a TCP/UDP port. */ +typedef struct tor_addr_port_t +{ + tor_addr_t addr; + uint16_t port; +} tor_addr_port_t; + +#define TOR_ADDR_NULL {AF_UNSPEC, {0}} + +/* XXXX To do: extract all of the functions here that can possibly invoke + * XXXX resolver, and make sure they have distinctive names. */ + +static inline const struct in6_addr *tor_addr_to_in6(const tor_addr_t *a); +static inline const struct in6_addr *tor_addr_to_in6_assert( + const tor_addr_t *a); +static inline uint32_t tor_addr_to_ipv4n(const tor_addr_t *a); +static inline uint32_t tor_addr_to_ipv4h(const tor_addr_t *a); +static inline uint32_t tor_addr_to_mapped_ipv4h(const tor_addr_t *a); +static inline sa_family_t tor_addr_family(const tor_addr_t *a); +static inline const struct in_addr *tor_addr_to_in(const tor_addr_t *a); +static inline int tor_addr_eq_ipv4h(const tor_addr_t *a, uint32_t u); + +socklen_t tor_addr_to_sockaddr(const tor_addr_t *a, uint16_t port, + struct sockaddr *sa_out, socklen_t len); +int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, + uint16_t *port_out); +void tor_addr_make_unspec(tor_addr_t *a); +void tor_addr_make_null(tor_addr_t *a, sa_family_t family); +char *tor_sockaddr_to_str(const struct sockaddr *sa); + +/** Return an in6_addr* equivalent to <b>a</b>, or NULL if <b>a</b> is not + * an IPv6 address. */ +static inline const struct in6_addr * +tor_addr_to_in6(const tor_addr_t *a) +{ + return a->family == AF_INET6 ? &a->addr.in6_addr : NULL; +} + +/** As tor_addr_to_in6, but assert that the address truly is an IPv6 + * address. */ +static inline const struct in6_addr * +tor_addr_to_in6_assert(const tor_addr_t *a) +{ + tor_assert(a->family == AF_INET6); + return &a->addr.in6_addr; +} + +/** Given an IPv6 address <b>x</b>, yield it as an array of uint8_t. + * + * Requires that <b>x</b> is actually an IPv6 address. + */ +#define tor_addr_to_in6_addr8(x) tor_addr_to_in6_assert(x)->s6_addr + +/** Given an IPv6 address <b>x</b>, yield it as an array of uint16_t. + * + * Requires that <b>x</b> is actually an IPv6 address. + */ +#define tor_addr_to_in6_addr16(x) S6_ADDR16(*tor_addr_to_in6_assert(x)) +/** Given an IPv6 address <b>x</b>, yield it as an array of uint32_t. + * + * Requires that <b>x</b> is actually an IPv6 address. + */ +#define tor_addr_to_in6_addr32(x) S6_ADDR32(*tor_addr_to_in6_assert(x)) + +/** Return an IPv4 address in network order for <b>a</b>, or 0 if + * <b>a</b> is not an IPv4 address. */ +static inline uint32_t +tor_addr_to_ipv4n(const tor_addr_t *a) +{ + return a->family == AF_INET ? a->addr.in_addr.s_addr : 0; +} +/** Return an IPv4 address in host order for <b>a</b>, or 0 if + * <b>a</b> is not an IPv4 address. */ +static inline uint32_t +tor_addr_to_ipv4h(const tor_addr_t *a) +{ + return ntohl(tor_addr_to_ipv4n(a)); +} +/** Given an IPv6 address, return its mapped IPv4 address in host order, or + * 0 if <b>a</b> is not an IPv6 address. + * + * (Does not check whether the address is really a mapped address */ +static inline uint32_t +tor_addr_to_mapped_ipv4h(const tor_addr_t *a) +{ + if (a->family == AF_INET6) { + uint32_t *addr32 = NULL; + // Work around an incorrect NULL pointer dereference warning in + // "clang --analyze" due to limited analysis depth + addr32 = tor_addr_to_in6_addr32(a); + // To improve performance, wrap this assertion in: + // #if !defined(__clang_analyzer__) || PARANOIA + tor_assert(addr32); + return ntohl(addr32[3]); + } else { + return 0; + } +} +/** Return the address family of <b>a</b>. Possible values are: + * AF_INET6, AF_INET, AF_UNSPEC. */ +static inline sa_family_t +tor_addr_family(const tor_addr_t *a) +{ + return a->family; +} +/** Return an in_addr* equivalent to <b>a</b>, or NULL if <b>a</b> is not + * an IPv4 address. */ +static inline const struct in_addr * +tor_addr_to_in(const tor_addr_t *a) +{ + return a->family == AF_INET ? &a->addr.in_addr : NULL; +} +/** Return true iff <b>a</b> is an IPv4 address equal to the host-ordered + * address in <b>u</b>. */ +static inline int +tor_addr_eq_ipv4h(const tor_addr_t *a, uint32_t u) +{ + return a->family == AF_INET ? (tor_addr_to_ipv4h(a) == u) : 0; +} + +/** Length of a buffer that you need to allocate to be sure you can encode + * any tor_addr_t. + * + * This allows enough space for + * "[ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255]", + * plus a terminating NUL. + */ +#define TOR_ADDR_BUF_LEN 48 + +char *tor_addr_to_str_dup(const tor_addr_t *addr) ATTR_MALLOC; + +/** Wrapper function of fmt_addr_impl(). It does not decorate IPv6 + * addresses. */ +#define fmt_addr(a) fmt_addr_impl((a), 0) +/** Wrapper function of fmt_addr_impl(). It decorates IPv6 + * addresses. */ +#define fmt_and_decorate_addr(a) fmt_addr_impl((a), 1) +const char *fmt_addr_impl(const tor_addr_t *addr, int decorate); +const char *fmt_addrport(const tor_addr_t *addr, uint16_t port); +const char * fmt_addr32(uint32_t addr); + +MOCK_DECL(int,get_interface_address6,(int severity, sa_family_t family, +tor_addr_t *addr)); +struct smartlist_t; +void interface_address6_list_free_(struct smartlist_t * addrs);// XXXX +#define interface_address6_list_free(addrs) \ + FREE_AND_NULL(struct smartlist_t, interface_address6_list_free_, (addrs)) +MOCK_DECL(struct smartlist_t *,get_interface_address6_list,(int severity, + sa_family_t family, + int include_internal)); + +/** Flag to specify how to do a comparison between addresses. In an "exact" + * comparison, addresses are equivalent only if they are in the same family + * with the same value. In a "semantic" comparison, IPv4 addresses match all + * IPv6 encodings of those addresses. */ +typedef enum { + CMP_EXACT, + CMP_SEMANTIC, +} tor_addr_comparison_t; + +int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, + tor_addr_comparison_t how); +int tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2, + maskbits_t mask, tor_addr_comparison_t how); +/** Return true iff a and b are the same address. The comparison is done + * "exactly". */ +#define tor_addr_eq(a,b) (0==tor_addr_compare((a),(b),CMP_EXACT)) + +uint64_t tor_addr_hash(const tor_addr_t *addr); +struct sipkey; +uint64_t tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr); +int tor_addr_is_v4(const tor_addr_t *addr); +int tor_addr_is_internal_(const tor_addr_t *ip, int for_listening, + const char *filename, int lineno); +#define tor_addr_is_internal(addr, for_listening) \ + tor_addr_is_internal_((addr), (for_listening), SHORT_FILE__, __LINE__) +int tor_addr_is_multicast(const tor_addr_t *a); + +/** Longest length that can be required for a reverse lookup name. */ +/* 32 nybbles, 32 dots, 8 characters of "ip6.arpa", 1 NUL: 73 characters. */ +#define REVERSE_LOOKUP_NAME_BUF_LEN 73 +int tor_addr_to_PTR_name(char *out, size_t outlen, + const tor_addr_t *addr); +int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, + int family, int accept_regular); + +/* Does the address * yield an AF_UNSPEC wildcard address (1), + * which expands to corresponding wildcard IPv4 and IPv6 rules, and do we + * allow *4 and *6 for IPv4 and IPv6 wildcards, respectively; + * or does the address * yield IPv4 wildcard address (0). */ +#define TAPMP_EXTENDED_STAR 1 +/* Does the address * yield an IPv4 wildcard address rule (1); + * or does it yield wildcard IPv4 and IPv6 rules (0) */ +#define TAPMP_STAR_IPV4_ONLY (1 << 1) +/* Does the address * yield an IPv6 wildcard address rule (1); + * or does it yield wildcard IPv4 and IPv6 rules (0) */ +#define TAPMP_STAR_IPV6_ONLY (1 << 2) +/* TAPMP_STAR_IPV4_ONLY and TAPMP_STAR_IPV6_ONLY are mutually exclusive. */ +int tor_addr_parse_mask_ports(const char *s, unsigned flags, + tor_addr_t *addr_out, maskbits_t *mask_out, + uint16_t *port_min_out, uint16_t *port_max_out); +const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, + int decorate); +int tor_addr_parse(tor_addr_t *addr, const char *src); +void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src); +void tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src); +void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr); +/** Set <b>dest</b> to the IPv4 address encoded in <b>v4addr</b> in host + * order. */ +#define tor_addr_from_ipv4h(dest, v4addr) \ + tor_addr_from_ipv4n((dest), htonl(v4addr)) +void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *bytes); +/** Set <b>dest</b> to the IPv4 address incoded in <b>in</b>. */ +#define tor_addr_from_in(dest, in) \ + tor_addr_from_ipv4n((dest), (in)->s_addr); +void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6); +int tor_addr_is_null(const tor_addr_t *addr); +int tor_addr_is_loopback(const tor_addr_t *addr); + +int tor_addr_is_valid(const tor_addr_t *addr, int for_listening); +int tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening); +#define tor_addr_is_valid_ipv4h(v4h_addr, for_listening) \ + tor_addr_is_valid_ipv4n(htonl(v4h_addr), (for_listening)) +int tor_port_is_valid(uint16_t port, int for_listening); +/* Are addr and port both valid? */ +#define tor_addr_port_is_valid(addr, port, for_listening) \ + (tor_addr_is_valid((addr), (for_listening)) && \ + tor_port_is_valid((port), (for_listening))) +/* Are ap->addr and ap->port both valid? */ +#define tor_addr_port_is_valid_ap(ap, for_listening) \ + tor_addr_port_is_valid(&(ap)->addr, (ap)->port, (for_listening)) +/* Are the network-order v4addr and port both valid? */ +#define tor_addr_port_is_valid_ipv4n(v4n_addr, port, for_listening) \ + (tor_addr_is_valid_ipv4n((v4n_addr), (for_listening)) && \ + tor_port_is_valid((port), (for_listening))) +/* Are the host-order v4addr and port both valid? */ +#define tor_addr_port_is_valid_ipv4h(v4h_addr, port, for_listening) \ + (tor_addr_is_valid_ipv4h((v4h_addr), (for_listening)) && \ + tor_port_is_valid((port), (for_listening))) + +int tor_addr_port_split(int severity, const char *addrport, + char **address_out, uint16_t *port_out); + +int tor_addr_port_parse(int severity, const char *addrport, + tor_addr_t *address_out, uint16_t *port_out, + int default_port); + +int tor_addr_hostname_is_local(const char *name); + +/* IPv4 helpers */ +int parse_port_range(const char *port, uint16_t *port_min_out, + uint16_t *port_max_out); +int addr_mask_get_bits(uint32_t mask); +char *tor_dup_ip(uint32_t addr) ATTR_MALLOC; +MOCK_DECL(int,get_interface_address,(int severity, uint32_t *addr)); +#define interface_address_list_free(lst)\ + interface_address6_list_free(lst) +/** Return a smartlist of the IPv4 addresses of all interfaces on the server. + * Excludes loopback and multicast addresses. Only includes internal addresses + * if include_internal is true. (Note that a relay behind NAT may use an + * internal address to connect to the Internet.) + * An empty smartlist means that there are no IPv4 addresses. + * Returns NULL on failure. + * Use free_interface_address_list to free the returned list. + */ +static inline struct smartlist_t * +get_interface_address_list(int severity, int include_internal) +{ + return get_interface_address6_list(severity, AF_INET, include_internal); +} + +tor_addr_port_t *tor_addr_port_new(const tor_addr_t *addr, uint16_t port); +int tor_addr_port_eq(const tor_addr_port_t *a, + const tor_addr_port_t *b); + +int string_is_valid_dest(const char *string); +int string_is_valid_nonrfc_hostname(const char *string); +int string_is_valid_ipv4_address(const char *string); +int string_is_valid_ipv6_address(const char *string); + +#ifdef ADDRESS_PRIVATE +MOCK_DECL(struct smartlist_t *,get_interface_addresses_raw,(int severity, + sa_family_t family)); +MOCK_DECL(int,get_interface_address6_via_udp_socket_hack,(int severity, + sa_family_t family, + tor_addr_t *addr)); + +#ifdef HAVE_IFADDRS_TO_SMARTLIST +STATIC struct smartlist_t *ifaddrs_to_smartlist(const struct ifaddrs *ifa, + sa_family_t family); +STATIC struct smartlist_t *get_interface_addresses_ifaddrs(int severity, + sa_family_t family); +#endif /* defined(HAVE_IFADDRS_TO_SMARTLIST) */ + +#ifdef HAVE_IP_ADAPTER_TO_SMARTLIST +STATIC struct smartlist_t *ip_adapter_addresses_to_smartlist( + const IP_ADAPTER_ADDRESSES *addresses); +STATIC struct smartlist_t *get_interface_addresses_win32(int severity, + sa_family_t family); +#endif /* defined(HAVE_IP_ADAPTER_TO_SMARTLIST) */ + +#ifdef HAVE_IFCONF_TO_SMARTLIST +STATIC struct smartlist_t *ifreq_to_smartlist(char *ifr, + size_t buflen); +STATIC struct smartlist_t *get_interface_addresses_ioctl(int severity, + sa_family_t family); +#endif /* defined(HAVE_IFCONF_TO_SMARTLIST) */ + +#endif /* defined(ADDRESS_PRIVATE) */ + +#endif /* !defined(TOR_ADDRESS_H) */ diff --git a/src/lib/net/alertsock.c b/src/lib/net/alertsock.c new file mode 100644 index 0000000000..340f9513fb --- /dev/null +++ b/src/lib/net/alertsock.c @@ -0,0 +1,295 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file alertsock.c + * + * \brief Use a socket to alert the main thread from a worker thread. + * + * Because our main loop spends all of its time in select, epoll, kqueue, or + * etc, we need a way to wake up the main loop from another thread. This code + * tries to provide the fastest reasonable way to do that, depending on our + * platform. + **/ + +#include "orconfig.h" +#include "lib/net/alertsock.h" +#include "lib/net/socket.h" +#include "lib/log/util_bug.h" + +#ifdef HAVE_SYS_EVENTFD_H +#include <sys/eventfd.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#ifdef _WIN32 +#include <winsock2.h> +#endif + +#if defined(HAVE_EVENTFD) || defined(HAVE_PIPE) +/* As write(), but retry on EINTR, and return the negative error code on + * error. */ +static int +write_ni(int fd, const void *buf, size_t n) +{ + int r; + again: + r = (int) write(fd, buf, n); + if (r < 0) { + if (errno == EINTR) + goto again; + else + return -errno; + } + return r; +} +/* As read(), but retry on EINTR, and return the negative error code on error. + */ +static int +read_ni(int fd, void *buf, size_t n) +{ + int r; + again: + r = (int) read(fd, buf, n); + if (r < 0) { + if (errno == EINTR) + goto again; + else + return -errno; + } + return r; +} +#endif /* defined(HAVE_EVENTFD) || defined(HAVE_PIPE) */ + +/** As send(), but retry on EINTR, and return the negative error code on + * error. */ +static int +send_ni(int fd, const void *buf, size_t n, int flags) +{ + int r; + again: + r = (int) send(fd, buf, n, flags); + if (r < 0) { + int error = tor_socket_errno(fd); + if (ERRNO_IS_EINTR(error)) + goto again; + else + return -error; + } + return r; +} + +/** As recv(), but retry on EINTR, and return the negative error code on + * error. */ +static int +recv_ni(int fd, void *buf, size_t n, int flags) +{ + int r; + again: + r = (int) recv(fd, buf, n, flags); + if (r < 0) { + int error = tor_socket_errno(fd); + if (ERRNO_IS_EINTR(error)) + goto again; + else + return -error; + } + return r; +} + +#ifdef HAVE_EVENTFD +/* Increment the event count on an eventfd <b>fd</b> */ +static int +eventfd_alert(int fd) +{ + uint64_t u = 1; + int r = write_ni(fd, (void*)&u, sizeof(u)); + if (r < 0 && -r != EAGAIN) + return -1; + return 0; +} + +/* Drain all events from an eventfd <b>fd</b>. */ +static int +eventfd_drain(int fd) +{ + uint64_t u = 0; + int r = read_ni(fd, (void*)&u, sizeof(u)); + if (r < 0 && -r != EAGAIN) + return r; + return 0; +} +#endif /* defined(HAVE_EVENTFD) */ + +#ifdef HAVE_PIPE +/** Send a byte over a pipe. Return 0 on success or EAGAIN; -1 on error */ +static int +pipe_alert(int fd) +{ + ssize_t r = write_ni(fd, "x", 1); + if (r < 0 && -r != EAGAIN) + return (int)r; + return 0; +} + +/** Drain all input from a pipe <b>fd</b> and ignore it. Return 0 on + * success, -1 on error. */ +static int +pipe_drain(int fd) +{ + char buf[32]; + ssize_t r; + do { + r = read_ni(fd, buf, sizeof(buf)); + } while (r > 0); + if (r < 0 && errno != EAGAIN) + return -errno; + /* A value of r = 0 means EOF on the fd so successfully drained. */ + return 0; +} +#endif /* defined(HAVE_PIPE) */ + +/** Send a byte on socket <b>fd</b>t. Return 0 on success or EAGAIN, + * -1 on error. */ +static int +sock_alert(tor_socket_t fd) +{ + ssize_t r = send_ni(fd, "x", 1, 0); + if (r < 0 && !ERRNO_IS_EAGAIN(-r)) + return (int)r; + return 0; +} + +/** Drain all the input from a socket <b>fd</b>, and ignore it. Return 0 on + * success, -errno on error. */ +static int +sock_drain(tor_socket_t fd) +{ + char buf[32]; + ssize_t r; + do { + r = recv_ni(fd, buf, sizeof(buf), 0); + } while (r > 0); + if (r < 0 && !ERRNO_IS_EAGAIN(-r)) + return (int)r; + /* A value of r = 0 means EOF on the fd so successfully drained. */ + return 0; +} + +/** Allocate a new set of alert sockets, and set the appropriate function + * pointers, in <b>socks_out</b>. */ +int +alert_sockets_create(alert_sockets_t *socks_out, uint32_t flags) +{ + tor_socket_t socks[2] = { TOR_INVALID_SOCKET, TOR_INVALID_SOCKET }; + +#ifdef HAVE_EVENTFD + /* First, we try the Linux eventfd() syscall. This gives a 64-bit counter + * associated with a single file descriptor. */ +#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK) + if (!(flags & ASOCKS_NOEVENTFD2)) + socks[0] = eventfd(0, EFD_CLOEXEC|EFD_NONBLOCK); +#endif + if (socks[0] < 0 && !(flags & ASOCKS_NOEVENTFD)) { + socks[0] = eventfd(0,0); + if (socks[0] >= 0) { + if (fcntl(socks[0], F_SETFD, FD_CLOEXEC) < 0 || + set_socket_nonblocking(socks[0]) < 0) { + // LCOV_EXCL_START -- if eventfd succeeds, fcntl will. + tor_assert_nonfatal_unreached(); + close(socks[0]); + return -1; + // LCOV_EXCL_STOP + } + } + } + if (socks[0] >= 0) { + socks_out->read_fd = socks_out->write_fd = socks[0]; + socks_out->alert_fn = eventfd_alert; + socks_out->drain_fn = eventfd_drain; + return 0; + } +#endif /* defined(HAVE_EVENTFD) */ + +#ifdef HAVE_PIPE2 + /* Now we're going to try pipes. First type the pipe2() syscall, if we + * have it, so we can save some calls... */ + if (!(flags & ASOCKS_NOPIPE2) && + pipe2(socks, O_NONBLOCK|O_CLOEXEC) == 0) { + socks_out->read_fd = socks[0]; + socks_out->write_fd = socks[1]; + socks_out->alert_fn = pipe_alert; + socks_out->drain_fn = pipe_drain; + return 0; + } +#endif /* defined(HAVE_PIPE2) */ + +#ifdef HAVE_PIPE + /* Now try the regular pipe() syscall. Pipes have a bit lower overhead than + * socketpairs, fwict. */ + if (!(flags & ASOCKS_NOPIPE) && + pipe(socks) == 0) { + if (fcntl(socks[0], F_SETFD, FD_CLOEXEC) < 0 || + fcntl(socks[1], F_SETFD, FD_CLOEXEC) < 0 || + set_socket_nonblocking(socks[0]) < 0 || + set_socket_nonblocking(socks[1]) < 0) { + // LCOV_EXCL_START -- if pipe succeeds, you can fcntl the output + tor_assert_nonfatal_unreached(); + close(socks[0]); + close(socks[1]); + return -1; + // LCOV_EXCL_STOP + } + socks_out->read_fd = socks[0]; + socks_out->write_fd = socks[1]; + socks_out->alert_fn = pipe_alert; + socks_out->drain_fn = pipe_drain; + return 0; + } +#endif /* defined(HAVE_PIPE) */ + + /* If nothing else worked, fall back on socketpair(). */ + if (!(flags & ASOCKS_NOSOCKETPAIR) && + tor_socketpair(AF_UNIX, SOCK_STREAM, 0, socks) == 0) { + if (set_socket_nonblocking(socks[0]) < 0 || + set_socket_nonblocking(socks[1])) { + // LCOV_EXCL_START -- if socketpair worked, you can make it nonblocking. + tor_assert_nonfatal_unreached(); + tor_close_socket(socks[0]); + tor_close_socket(socks[1]); + return -1; + // LCOV_EXCL_STOP + } + socks_out->read_fd = socks[0]; + socks_out->write_fd = socks[1]; + socks_out->alert_fn = sock_alert; + socks_out->drain_fn = sock_drain; + return 0; + } + return -1; +} + +/** Close the sockets in <b>socks</b>. */ +void +alert_sockets_close(alert_sockets_t *socks) +{ + if (socks->alert_fn == sock_alert) { + /* they are sockets. */ + tor_close_socket(socks->read_fd); + tor_close_socket(socks->write_fd); + } else { + close(socks->read_fd); + if (socks->write_fd != socks->read_fd) + close(socks->write_fd); + } + socks->read_fd = socks->write_fd = -1; +} diff --git a/src/lib/net/alertsock.h b/src/lib/net/alertsock.h new file mode 100644 index 0000000000..5dfe53a2a0 --- /dev/null +++ b/src/lib/net/alertsock.h @@ -0,0 +1,45 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file alertsock.h + * + * \brief Header for alertsock.c + **/ + +#ifndef TOR_ALERTSOCK_H +#define TOR_ALERTSOCK_H + +#include "orconfig.h" +#include "lib/net/nettypes.h" +#include "lib/cc/torint.h" + +/** Helper type used to manage waking up the main thread while it's in + * the libevent main loop. Used by the work queue code. */ +typedef struct alert_sockets_t { + /* XXXX This structure needs a better name. */ + /** Socket that the main thread should listen for EV_READ events on. + * Note that this socket may be a regular fd on a non-Windows platform. + */ + tor_socket_t read_fd; + /** Socket to use when alerting the main thread. */ + tor_socket_t write_fd; + /** Function to alert the main thread */ + int (*alert_fn)(tor_socket_t write_fd); + /** Function to make the main thread no longer alerted. */ + int (*drain_fn)(tor_socket_t read_fd); +} alert_sockets_t; + +/* Flags to disable one or more alert_sockets backends. */ +#define ASOCKS_NOEVENTFD2 (1u<<0) +#define ASOCKS_NOEVENTFD (1u<<1) +#define ASOCKS_NOPIPE2 (1u<<2) +#define ASOCKS_NOPIPE (1u<<3) +#define ASOCKS_NOSOCKETPAIR (1u<<4) + +int alert_sockets_create(alert_sockets_t *socks_out, uint32_t flags); +void alert_sockets_close(alert_sockets_t *socks); + +#endif diff --git a/src/lib/net/buffers_net.c b/src/lib/net/buffers_net.c new file mode 100644 index 0000000000..c52ea2784e --- /dev/null +++ b/src/lib/net/buffers_net.c @@ -0,0 +1,202 @@ +/* Copyright (c) 2001 Matej Pfajfar. + * Copyright (c) 2001-2004, Roger Dingledine. + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file buffers_net.c + * \brief Read and write data on a buf_t object. + **/ + +#define BUFFERS_PRIVATE +#include "lib/net/buffers_net.h" +#include "lib/container/buffers.h" +#include "lib/log/log.h" +#include "lib/log/util_bug.h" +#include "lib/net/nettypes.h" + +#ifdef _WIN32 +#include <winsock2.h> +#endif + +#include <stdlib.h> + +#ifdef PARANOIA +/** Helper: If PARANOIA is defined, assert that the buffer in local variable + * <b>buf</b> is well-formed. */ +#define check() STMT_BEGIN buf_assert_ok(buf); STMT_END +#else +#define check() STMT_NIL +#endif /* defined(PARANOIA) */ + +/** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into + * <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set + * *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking, + * and the number of bytes read otherwise. */ +static inline int +read_to_chunk(buf_t *buf, chunk_t *chunk, tor_socket_t fd, size_t at_most, + int *reached_eof, int *socket_error) +{ + ssize_t read_result; + if (at_most > CHUNK_REMAINING_CAPACITY(chunk)) + at_most = CHUNK_REMAINING_CAPACITY(chunk); + read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0); + + if (read_result < 0) { + int e = tor_socket_errno(fd); + if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */ +#ifdef _WIN32 + if (e == WSAENOBUFS) + log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?"); +#endif + *socket_error = e; + return -1; + } + return 0; /* would block. */ + } else if (read_result == 0) { + log_debug(LD_NET,"Encountered eof on fd %d", (int)fd); + *reached_eof = 1; + return 0; + } else { /* actually got bytes. */ + buf->datalen += read_result; + chunk->datalen += read_result; + log_debug(LD_NET,"Read %ld bytes. %d on inbuf.", (long)read_result, + (int)buf->datalen); + tor_assert(read_result < INT_MAX); + return (int)read_result; + } +} + +/** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most + * <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0 + * (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on + * error; else return the number of bytes read. + */ +/* XXXX indicate "read blocked" somehow? */ +int +buf_read_from_socket(buf_t *buf, tor_socket_t s, size_t at_most, + int *reached_eof, + int *socket_error) +{ + /* XXXX It's stupid to overload the return values for these functions: + * "error status" and "number of bytes read" are not mutually exclusive. + */ + int r = 0; + size_t total_read = 0; + + check(); + tor_assert(reached_eof); + tor_assert(SOCKET_OK(s)); + + if (BUG(buf->datalen >= INT_MAX)) + return -1; + if (BUG(buf->datalen >= INT_MAX - at_most)) + return -1; + + while (at_most > total_read) { + size_t readlen = at_most - total_read; + chunk_t *chunk; + if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) { + chunk = buf_add_chunk_with_capacity(buf, at_most, 1); + if (readlen > chunk->memlen) + readlen = chunk->memlen; + } else { + size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail); + chunk = buf->tail; + if (cap < readlen) + readlen = cap; + } + + r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error); + check(); + if (r < 0) + return r; /* Error */ + tor_assert(total_read+r < INT_MAX); + total_read += r; + if ((size_t)r < readlen) { /* eof, block, or no more to read. */ + break; + } + } + return (int)total_read; +} + +/** Helper for buf_flush_to_socket(): try to write <b>sz</b> bytes from chunk + * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct + * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes + * written on success, 0 on blocking, -1 on failure. + */ +static inline int +flush_chunk(tor_socket_t s, buf_t *buf, chunk_t *chunk, size_t sz, + size_t *buf_flushlen) +{ + ssize_t write_result; + + if (sz > chunk->datalen) + sz = chunk->datalen; + write_result = tor_socket_send(s, chunk->data, sz, 0); + + if (write_result < 0) { + int e = tor_socket_errno(s); + if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */ +#ifdef _WIN32 + if (e == WSAENOBUFS) + log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?"); +#endif + return -1; + } + log_debug(LD_NET,"write() would block, returning."); + return 0; + } else { + *buf_flushlen -= write_result; + buf_drain(buf, write_result); + tor_assert(write_result < INT_MAX); + return (int)write_result; + } +} + +/** Write data from <b>buf</b> to the socket <b>s</b>. Write at most + * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by + * the number of bytes actually written, and remove the written bytes + * from the buffer. Return the number of bytes written on success, + * -1 on failure. Return 0 if write() would block. + */ +int +buf_flush_to_socket(buf_t *buf, tor_socket_t s, size_t sz, + size_t *buf_flushlen) +{ + /* XXXX It's stupid to overload the return values for these functions: + * "error status" and "number of bytes flushed" are not mutually exclusive. + */ + int r; + size_t flushed = 0; + tor_assert(buf_flushlen); + tor_assert(SOCKET_OK(s)); + if (BUG(*buf_flushlen > buf->datalen)) { + *buf_flushlen = buf->datalen; + } + if (BUG(sz > *buf_flushlen)) { + sz = *buf_flushlen; + } + + check(); + while (sz) { + size_t flushlen0; + tor_assert(buf->head); + if (buf->head->datalen >= sz) + flushlen0 = sz; + else + flushlen0 = buf->head->datalen; + + r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen); + check(); + if (r < 0) + return r; + flushed += r; + sz -= r; + if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */ + break; + } + tor_assert(flushed < INT_MAX); + return (int)flushed; +} diff --git a/src/lib/net/buffers_net.h b/src/lib/net/buffers_net.h new file mode 100644 index 0000000000..417f6f9413 --- /dev/null +++ b/src/lib/net/buffers_net.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2001 Matej Pfajfar. + * Copyright (c) 2001-2004, Roger Dingledine. + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file buffers_net.h + * + * \brief Header file for buffers_net.c. + **/ + +#ifndef TOR_BUFFERS_NET_H +#define TOR_BUFFERS_NET_H + +#include <stddef.h> +#include "lib/net/socket.h" + +struct buf_t; +int buf_read_from_socket(struct buf_t *buf, tor_socket_t s, size_t at_most, + int *reached_eof, + int *socket_error); + +int buf_flush_to_socket(struct buf_t *buf, tor_socket_t s, size_t sz, + size_t *buf_flushlen); + +#endif /* !defined(TOR_BUFFERS_H) */ diff --git a/src/lib/net/gethostname.c b/src/lib/net/gethostname.c new file mode 100644 index 0000000000..1c4431af29 --- /dev/null +++ b/src/lib/net/gethostname.c @@ -0,0 +1,30 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file gethostname.c + * \brief Mockable wrapper for gethostname(). + */ + +#include "orconfig.h" +#include "lib/net/gethostname.h" + +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef _WIN32 +#include <winsock2.h> +#endif + +/** Get name of current host and write it to <b>name</b> array, whose + * length is specified by <b>namelen</b> argument. Return 0 upon + * successful completion; otherwise return return -1. (Currently, + * this function is merely a mockable wrapper for POSIX gethostname().) + */ +MOCK_IMPL(int, +tor_gethostname,(char *name, size_t namelen)) +{ + return gethostname(name,namelen); +} diff --git a/src/lib/net/gethostname.h b/src/lib/net/gethostname.h new file mode 100644 index 0000000000..7bf0ce5920 --- /dev/null +++ b/src/lib/net/gethostname.h @@ -0,0 +1,19 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file gethostname.h + * \brief Header for gethostname.c + **/ + +#ifndef TOR_GETHOSTNAME_H +#define TOR_GETHOSTNAME_H + +#include "lib/testsupport/testsupport.h" +#include <stddef.h> + +MOCK_DECL(int,tor_gethostname,(char *name, size_t namelen)); + +#endif diff --git a/src/lib/net/inaddr.c b/src/lib/net/inaddr.c new file mode 100644 index 0000000000..dcd8fcdd65 --- /dev/null +++ b/src/lib/net/inaddr.c @@ -0,0 +1,267 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file inaddr.c + * \brief Convert in_addr and in6_addr to and from strings. + **/ + +#include "lib/net/inaddr.h" + +#include "lib/cc/torint.h" +#include "lib/log/util_bug.h" +#include "lib/net/inaddr_st.h" +#include "lib/string/compat_ctype.h" +#include "lib/string/compat_string.h" +#include "lib/string/printf.h" +#include "lib/string/scanf.h" +#include "lib/string/util_string.h" + +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif + +#include <stdlib.h> +#include <string.h> + +#ifdef _WIN32 +#include <winsock2.h> +#endif + +/** Set *addr to the IP address (in dotted-quad notation) stored in *str. + * Return 1 on success, 0 if *str is badly formatted. + * (Like inet_aton(str,addr), but works on Windows and Solaris.) + */ +int +tor_inet_aton(const char *str, struct in_addr* addr) +{ + unsigned a,b,c,d; + char more; + if (tor_sscanf(str, "%3u.%3u.%3u.%3u%c", &a,&b,&c,&d,&more) != 4) + return 0; + if (a > 255) return 0; + if (b > 255) return 0; + if (c > 255) return 0; + if (d > 255) return 0; + addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d); + return 1; +} + +/** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual), + * write it as a string into the <b>buf_len</b>-byte buffer in + * <b>buf</b>. Returns a non-negative integer on success. + * Returns -1 on failure. + */ +int +tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len) +{ + uint32_t a = ntohl(in->s_addr); + return tor_snprintf(buf, buf_len, "%d.%d.%d.%d", + (int)(uint8_t)((a>>24)&0xff), + (int)(uint8_t)((a>>16)&0xff), + (int)(uint8_t)((a>>8 )&0xff), + (int)(uint8_t)((a )&0xff)); +} + +/** Given <b>af</b>==AF_INET and <b>src</b> a struct in_addr, or + * <b>af</b>==AF_INET6 and <b>src</b> a struct in6_addr, try to format the + * address and store it in the <b>len</b>-byte buffer <b>dst</b>. Returns + * <b>dst</b> on success, NULL on failure. + * + * (Like inet_ntop(af,src,dst,len), but works on platforms that don't have it: + * Tor sometimes needs to format ipv6 addresses even on platforms without ipv6 + * support.) */ +const char * +tor_inet_ntop(int af, const void *src, char *dst, size_t len) +{ + if (af == AF_INET) { + if (tor_inet_ntoa(src, dst, len) < 0) + return NULL; + else + return dst; + } else if (af == AF_INET6) { + const struct in6_addr *addr = src; + char buf[64], *cp; + int longestGapLen = 0, longestGapPos = -1, i, + curGapPos = -1, curGapLen = 0; + uint16_t words[8]; + for (i = 0; i < 8; ++i) { + words[i] = (((uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1]; + } + if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 && + words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) || + (words[5] == 0xffff))) { + /* This is an IPv4 address. */ + if (words[5] == 0) { + tor_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d", + addr->s6_addr[12], addr->s6_addr[13], + addr->s6_addr[14], addr->s6_addr[15]); + } else { + tor_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5], + addr->s6_addr[12], addr->s6_addr[13], + addr->s6_addr[14], addr->s6_addr[15]); + } + if ((strlen(buf) + 1) > len) /* +1 for \0 */ + return NULL; + strlcpy(dst, buf, len); + return dst; + } + i = 0; + while (i < 8) { + if (words[i] == 0) { + curGapPos = i++; + curGapLen = 1; + while (i<8 && words[i] == 0) { + ++i; ++curGapLen; + } + if (curGapLen > longestGapLen) { + longestGapPos = curGapPos; + longestGapLen = curGapLen; + } + } else { + ++i; + } + } + if (longestGapLen<=1) + longestGapPos = -1; + + cp = buf; + for (i = 0; i < 8; ++i) { + if (words[i] == 0 && longestGapPos == i) { + if (i == 0) + *cp++ = ':'; + *cp++ = ':'; + while (i < 8 && words[i] == 0) + ++i; + --i; /* to compensate for loop increment. */ + } else { + tor_snprintf(cp, sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]); + cp += strlen(cp); + if (i != 7) + *cp++ = ':'; + } + } + *cp = '\0'; + if ((strlen(buf) + 1) > len) /* +1 for \0 */ + return NULL; + strlcpy(dst, buf, len); + return dst; + } else { + return NULL; + } +} + +/** Given <b>af</b>==AF_INET or <b>af</b>==AF_INET6, and a string <b>src</b> + * encoding an IPv4 address or IPv6 address correspondingly, try to parse the + * address and store the result in <b>dst</b> (which must have space for a + * struct in_addr or a struct in6_addr, as appropriate). Return 1 on success, + * 0 on a bad parse, and -1 on a bad <b>af</b>. + * + * (Like inet_pton(af,src,dst) but works on platforms that don't have it: Tor + * sometimes needs to format ipv6 addresses even on platforms without ipv6 + * support.) */ +int +tor_inet_pton(int af, const char *src, void *dst) +{ + if (af == AF_INET) { + return tor_inet_aton(src, dst); + } else if (af == AF_INET6) { + struct in6_addr *out = dst; + uint16_t words[8]; + int gapPos = -1, i, setWords=0; + const char *dot = strchr(src, '.'); + const char *eow; /* end of words. */ + memset(words, 0xf8, sizeof(words)); + if (dot == src) + return 0; + else if (!dot) + eow = src+strlen(src); + else { + unsigned byte1,byte2,byte3,byte4; + char more; + for (eow = dot-1; eow > src && TOR_ISDIGIT(*eow); --eow) + ; + if (*eow != ':') + return 0; + ++eow; + + /* We use "scanf" because some platform inet_aton()s are too lax + * about IPv4 addresses of the form "1.2.3" */ + if (tor_sscanf(eow, "%3u.%3u.%3u.%3u%c", + &byte1,&byte2,&byte3,&byte4,&more) != 4) + return 0; + + if (byte1 > 255 || byte2 > 255 || byte3 > 255 || byte4 > 255) + return 0; + + words[6] = (byte1<<8) | byte2; + words[7] = (byte3<<8) | byte4; + setWords += 2; + } + + i = 0; + while (src < eow) { + if (i > 7) + return 0; + if (TOR_ISXDIGIT(*src)) { + char *next; + ssize_t len; + long r = strtol(src, &next, 16); + if (next == NULL || next == src) { + /* The 'next == src' error case can happen on versions of openbsd + * which treat "0xfoo" as an error, rather than as "0" followed by + * "xfoo". */ + return 0; + } + + len = *next == '\0' ? eow - src : next - src; + if (len > 4) + return 0; + if (len > 1 && !TOR_ISXDIGIT(src[1])) + return 0; /* 0x is not valid */ + + tor_assert(r >= 0); + tor_assert(r < 65536); + words[i++] = (uint16_t)r; + setWords++; + src = next; + if (*src != ':' && src != eow) + return 0; + ++src; + } else if (*src == ':' && i > 0 && gapPos == -1) { + gapPos = i; + ++src; + } else if (*src == ':' && i == 0 && src+1 < eow && src[1] == ':' && + gapPos == -1) { + gapPos = i; + src += 2; + } else { + return 0; + } + } + + if (setWords > 8 || + (setWords == 8 && gapPos != -1) || + (setWords < 8 && gapPos == -1)) + return 0; + + if (gapPos >= 0) { + int nToMove = setWords - (dot ? 2 : 0) - gapPos; + int gapLen = 8 - setWords; + tor_assert(nToMove >= 0); + memmove(&words[gapPos+gapLen], &words[gapPos], + sizeof(uint16_t)*nToMove); + memset(&words[gapPos], 0, sizeof(uint16_t)*gapLen); + } + for (i = 0; i < 8; ++i) { + out->s6_addr[2*i ] = words[i] >> 8; + out->s6_addr[2*i+1] = words[i] & 0xff; + } + + return 1; + } else { + return -1; + } +} diff --git a/src/lib/net/inaddr.h b/src/lib/net/inaddr.h new file mode 100644 index 0000000000..121025a126 --- /dev/null +++ b/src/lib/net/inaddr.h @@ -0,0 +1,27 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file inaddr.h + * \brief Header for inaddr.c. + **/ + +#ifndef TOR_INADDR_H +#define TOR_INADDR_H + +#include "orconfig.h" +#include <stddef.h> + +struct in_addr; + +int tor_inet_aton(const char *str, struct in_addr *addr); +/** Length of a buffer to allocate to hold the results of tor_inet_ntoa.*/ +#define INET_NTOA_BUF_LEN 16 +int tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len); + +const char *tor_inet_ntop(int af, const void *src, char *dst, size_t len); +int tor_inet_pton(int af, const char *src, void *dst); + +#endif diff --git a/src/lib/net/inaddr_st.h b/src/lib/net/inaddr_st.h new file mode 100644 index 0000000000..dc4c6e3a00 --- /dev/null +++ b/src/lib/net/inaddr_st.h @@ -0,0 +1,104 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file inaddr_st.h + * + * \brief Define in6_addr, its members, and related types on platforms that + * lack it. + **/ + +#ifndef TOR_INADDR_ST_H +#define TOR_INADDR_ST_H + +#include "orconfig.h" +#include <stddef.h> + +#ifdef HAVE_ARPA_INET_H +#include <arpa/inet.h> +#endif +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif +#ifdef HAVE_NETINET_IN6_H +#include <netinet/in6.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif + +#ifdef _WIN32 +#include <winsock2.h> +#include <ws2tcpip.h> +#include <windows.h> +#endif + +#include "lib/cc/torint.h" + +struct in_addr; + +/** Implementation of struct in6_addr for platforms that do not have it. + * Generally, these platforms are ones without IPv6 support, but we want to + * have a working in6_addr there anyway, so we can use it to parse IPv6 + * addresses. */ +#if !defined(HAVE_STRUCT_IN6_ADDR) +struct in6_addr +{ + union { + uint8_t u6_addr8[16]; + uint16_t u6_addr16[8]; + uint32_t u6_addr32[4]; + } in6_u; +#define s6_addr in6_u.u6_addr8 +#define s6_addr16 in6_u.u6_addr16 +#define s6_addr32 in6_u.u6_addr32 +}; +#endif /* !defined(HAVE_STRUCT_IN6_ADDR) */ + +/** @{ */ +/** Many BSD variants seem not to define these. */ +#if defined(__APPLE__) || defined(__darwin__) || \ + defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) +#ifndef s6_addr16 +#define s6_addr16 __u6_addr.__u6_addr16 +#endif +#ifndef s6_addr32 +#define s6_addr32 __u6_addr.__u6_addr32 +#endif +#endif /* defined(__APPLE__) || defined(__darwin__) || ... */ +/** @} */ + +#ifndef HAVE_SA_FAMILY_T +typedef uint16_t sa_family_t; +#endif + +/** @{ */ +/** Apparently, MS and Solaris don't define s6_addr16 or s6_addr32; these + * macros get you a pointer to s6_addr32 or local equivalent. */ +#ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR32 +#define S6_ADDR32(x) ((uint32_t*)(x).s6_addr32) +#else +#define S6_ADDR32(x) ((uint32_t*)((char*)&(x).s6_addr)) +#endif +#ifdef HAVE_STRUCT_IN6_ADDR_S6_ADDR16 +#define S6_ADDR16(x) ((uint16_t*)(x).s6_addr16) +#else +#define S6_ADDR16(x) ((uint16_t*)((char*)&(x).s6_addr)) +#endif +/** @} */ + +/** Implementation of struct sockaddr_in6 on platforms that do not have + * it. See notes on struct in6_addr. */ +#if !defined(HAVE_STRUCT_SOCKADDR_IN6) +struct sockaddr_in6 { + sa_family_t sin6_family; + uint16_t sin6_port; + // uint32_t sin6_flowinfo; + struct in6_addr sin6_addr; + // uint32_t sin6_scope_id; +}; +#endif /* !defined(HAVE_STRUCT_SOCKADDR_IN6) */ + +#endif /* TOR_INADDR_ST_H */ diff --git a/src/lib/net/include.am b/src/lib/net/include.am new file mode 100644 index 0000000000..ff0967e786 --- /dev/null +++ b/src/lib/net/include.am @@ -0,0 +1,34 @@ + +noinst_LIBRARIES += src/lib/libtor-net.a + +if UNITTESTS_ENABLED +noinst_LIBRARIES += src/lib/libtor-net-testing.a +endif + +src_lib_libtor_net_a_SOURCES = \ + src/lib/net/address.c \ + src/lib/net/alertsock.c \ + src/lib/net/buffers_net.c \ + src/lib/net/gethostname.c \ + src/lib/net/inaddr.c \ + src/lib/net/resolve.c \ + src/lib/net/socket.c \ + src/lib/net/socketpair.c + +src_lib_libtor_net_testing_a_SOURCES = \ + $(src_lib_libtor_net_a_SOURCES) +src_lib_libtor_net_testing_a_CPPFLAGS = $(AM_CPPFLAGS) $(TEST_CPPFLAGS) +src_lib_libtor_net_testing_a_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS) + +noinst_HEADERS += \ + src/lib/net/address.h \ + src/lib/net/alertsock.h \ + src/lib/net/buffers_net.h \ + src/lib/net/gethostname.h \ + src/lib/net/inaddr.h \ + src/lib/net/inaddr_st.h \ + src/lib/net/nettypes.h \ + src/lib/net/resolve.h \ + src/lib/net/socket.h \ + src/lib/net/socketpair.h \ + src/lib/net/socks5_status.h diff --git a/src/lib/net/nettypes.h b/src/lib/net/nettypes.h new file mode 100644 index 0000000000..f7f2ec7d6a --- /dev/null +++ b/src/lib/net/nettypes.h @@ -0,0 +1,44 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file nettypes.h + * \brief Declarations for types used throughout the Tor networking system + **/ + +#ifndef TOR_NET_TYPES_H +#define TOR_NET_TYPES_H + +#include "orconfig.h" +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif + +#if (SIZEOF_SOCKLEN_T == 0) +typedef int socklen_t; +#endif + +#ifdef _WIN32 +/* XXX Actually, this should arguably be SOCKET; we use intptr_t here so that + * any inadvertent checks for the socket being <= 0 or > 0 will probably + * still work. */ +#define tor_socket_t intptr_t +#define TOR_SOCKET_T_FORMAT "%"PRIuPTR +#define SOCKET_OK(s) ((SOCKET)(s) != INVALID_SOCKET) +#define TOR_INVALID_SOCKET INVALID_SOCKET +#else /* !(defined(_WIN32)) */ +/** Type used for a network socket. */ +#define tor_socket_t int +#define TOR_SOCKET_T_FORMAT "%d" +/** Macro: true iff 's' is a possible value for a valid initialized socket. */ +#define SOCKET_OK(s) ((s) >= 0) +/** Error/uninitialized value for a tor_socket_t. */ +#define TOR_INVALID_SOCKET (-1) +#endif /* defined(_WIN32) */ + +#endif diff --git a/src/lib/net/resolve.c b/src/lib/net/resolve.c new file mode 100644 index 0000000000..7c8df3e307 --- /dev/null +++ b/src/lib/net/resolve.c @@ -0,0 +1,424 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file resolve.c + * \brief Use the libc DNS resolver to convert hostnames into addresses. + **/ + +#include "lib/net/resolve.h" + +#include "lib/net/address.h" +#include "lib/net/inaddr.h" +#include "lib/malloc/malloc.h" +#include "lib/string/parse_int.h" +#include "lib/string/util_string.h" + +#include "siphash.h" +#include "ht.h" + +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif +#ifdef HAVE_SYS_SOCKET_H +#include <sys/socket.h> +#endif +#ifdef HAVE_NETDB_H +#include <netdb.h> +#endif + +#include <string.h> + +/** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set + * *<b>addr</b> to the proper IP address, in host byte order. Returns 0 + * on success, -1 on failure; 1 on transient failure. + * + * (This function exists because standard windows gethostbyname + * doesn't treat raw IP addresses properly.) + */ + +MOCK_IMPL(int, +tor_lookup_hostname,(const char *name, uint32_t *addr)) +{ + tor_addr_t myaddr; + int ret; + + if ((ret = tor_addr_lookup(name, AF_INET, &myaddr))) + return ret; + + if (tor_addr_family(&myaddr) == AF_INET) { + *addr = tor_addr_to_ipv4h(&myaddr); + return ret; + } + + return -1; +} + +/** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set + * *<b>addr</b> to the proper IP address and family. The <b>family</b> + * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a + * <i>preferred</i> family, though another one may be returned if only one + * family is implemented for this address. + * + * Return 0 on success, -1 on failure; 1 on transient failure. + */ +MOCK_IMPL(int, +tor_addr_lookup,(const char *name, uint16_t family, tor_addr_t *addr)) +{ + /* Perhaps eventually this should be replaced by a tor_getaddrinfo or + * something. + */ + struct in_addr iaddr; + struct in6_addr iaddr6; + tor_assert(name); + tor_assert(addr); + tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC); + if (!*name) { + /* Empty address is an error. */ + return -1; + } else if (tor_inet_pton(AF_INET, name, &iaddr)) { + /* It's an IPv4 IP. */ + if (family == AF_INET6) + return -1; + tor_addr_from_in(addr, &iaddr); + return 0; + } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) { + if (family == AF_INET) + return -1; + tor_addr_from_in6(addr, &iaddr6); + return 0; + } else { +#ifdef HAVE_GETADDRINFO + int err; + struct addrinfo *res=NULL, *res_p; + struct addrinfo *best=NULL; + struct addrinfo hints; + int result = -1; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = family; + hints.ai_socktype = SOCK_STREAM; + err = tor_getaddrinfo(name, NULL, &hints, &res); + /* The check for 'res' here shouldn't be necessary, but it makes static + * analysis tools happy. */ + if (!err && res) { + best = NULL; + for (res_p = res; res_p; res_p = res_p->ai_next) { + if (family == AF_UNSPEC) { + if (res_p->ai_family == AF_INET) { + best = res_p; + break; + } else if (res_p->ai_family == AF_INET6 && !best) { + best = res_p; + } + } else if (family == res_p->ai_family) { + best = res_p; + break; + } + } + if (!best) + best = res; + if (best->ai_family == AF_INET) { + tor_addr_from_in(addr, + &((struct sockaddr_in*)best->ai_addr)->sin_addr); + result = 0; + } else if (best->ai_family == AF_INET6) { + tor_addr_from_in6(addr, + &((struct sockaddr_in6*)best->ai_addr)->sin6_addr); + result = 0; + } + tor_freeaddrinfo(res); + return result; + } + return (err == EAI_AGAIN) ? 1 : -1; +#else /* !(defined(HAVE_GETADDRINFO)) */ + struct hostent *ent; + int err; +#ifdef HAVE_GETHOSTBYNAME_R_6_ARG + char buf[2048]; + struct hostent hostent; + int r; + r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err); +#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG) + char buf[2048]; + struct hostent hostent; + ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err); +#elif defined(HAVE_GETHOSTBYNAME_R_3_ARG) + struct hostent_data data; + struct hostent hent; + memset(&data, 0, sizeof(data)); + err = gethostbyname_r(name, &hent, &data); + ent = err ? NULL : &hent; +#else + ent = gethostbyname(name); +#ifdef _WIN32 + err = WSAGetLastError(); +#else + err = h_errno; +#endif +#endif /* defined(HAVE_GETHOSTBYNAME_R_6_ARG) || ... */ + if (ent) { + if (ent->h_addrtype == AF_INET) { + tor_addr_from_in(addr, (struct in_addr*) ent->h_addr); + } else if (ent->h_addrtype == AF_INET6) { + tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr); + } else { + tor_assert(0); // LCOV_EXCL_LINE: gethostbyname() returned bizarre type + } + return 0; + } +#ifdef _WIN32 + return (err == WSATRY_AGAIN) ? 1 : -1; +#else + return (err == TRY_AGAIN) ? 1 : -1; +#endif +#endif /* defined(HAVE_GETADDRINFO) */ + } +} + +/** Parse an address or address-port combination from <b>s</b>, resolve the + * address as needed, and put the result in <b>addr_out</b> and (optionally) + * <b>port_out</b>. Return 0 on success, negative on failure. */ +int +tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out) +{ + const char *port; + tor_addr_t addr; + uint16_t portval; + char *tmp = NULL; + + tor_assert(s); + tor_assert(addr_out); + + s = eat_whitespace(s); + + if (*s == '[') { + port = strstr(s, "]"); + if (!port) + goto err; + tmp = tor_strndup(s+1, port-(s+1)); + port = port+1; + if (*port == ':') + port++; + else + port = NULL; + } else { + port = strchr(s, ':'); + if (port) + tmp = tor_strndup(s, port-s); + else + tmp = tor_strdup(s); + if (port) + ++port; + } + + if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) != 0) + goto err; + tor_free(tmp); + + if (port) { + portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL); + if (!portval) + goto err; + } else { + portval = 0; + } + + if (port_out) + *port_out = portval; + tor_addr_copy(addr_out, &addr); + + return 0; + err: + tor_free(tmp); + return -1; +} + +#ifdef USE_SANDBOX_GETADDRINFO +/** True if we should only return cached values */ +static int sandbox_getaddrinfo_is_active = 0; + +/** Cache entry for getaddrinfo results; used when sandboxing is implemented + * so that we can consult the cache when the sandbox prevents us from doing + * getaddrinfo. + * + * We support only a limited range of getaddrinfo calls, where servname is null + * and hints contains only socktype=SOCK_STREAM, family in INET,INET6,UNSPEC. + */ +typedef struct cached_getaddrinfo_item_t { + HT_ENTRY(cached_getaddrinfo_item_t) node; + char *name; + int family; + /** set if no error; otherwise NULL */ + struct addrinfo *res; + /** 0 for no error; otherwise an EAI_* value */ + int err; +} cached_getaddrinfo_item_t; + +static unsigned +cached_getaddrinfo_item_hash(const cached_getaddrinfo_item_t *item) +{ + return (unsigned)siphash24g(item->name, strlen(item->name)) + item->family; +} + +static unsigned +cached_getaddrinfo_items_eq(const cached_getaddrinfo_item_t *a, + const cached_getaddrinfo_item_t *b) +{ + return (a->family == b->family) && 0 == strcmp(a->name, b->name); +} + +#define cached_getaddrinfo_item_free(item) \ + FREE_AND_NULL(cached_getaddrinfo_item_t, \ + cached_getaddrinfo_item_free_, (item)) + +static void +cached_getaddrinfo_item_free_(cached_getaddrinfo_item_t *item) +{ + if (item == NULL) + return; + + tor_free(item->name); + if (item->res) + freeaddrinfo(item->res); + tor_free(item); +} + +static HT_HEAD(getaddrinfo_cache, cached_getaddrinfo_item_t) + getaddrinfo_cache = HT_INITIALIZER(); + +HT_PROTOTYPE(getaddrinfo_cache, cached_getaddrinfo_item_t, node, + cached_getaddrinfo_item_hash, + cached_getaddrinfo_items_eq) +HT_GENERATE2(getaddrinfo_cache, cached_getaddrinfo_item_t, node, + cached_getaddrinfo_item_hash, + cached_getaddrinfo_items_eq, + 0.6, tor_reallocarray_, tor_free_) + +/** If true, don't try to cache getaddrinfo results. */ +static int sandbox_getaddrinfo_cache_disabled = 0; + +/** Tell the sandbox layer not to try to cache getaddrinfo results. Used as in + * tor-resolve, when we have no intention of initializing crypto or of + * installing the sandbox.*/ +void +sandbox_disable_getaddrinfo_cache(void) +{ + sandbox_getaddrinfo_cache_disabled = 1; +} + +void +tor_freeaddrinfo(struct addrinfo *ai) +{ + if (sandbox_getaddrinfo_cache_disabled) + freeaddrinfo(ai); +} + +int +tor_getaddrinfo(const char *name, const char *servname, + const struct addrinfo *hints, + struct addrinfo **res) +{ + int err; + struct cached_getaddrinfo_item_t search, *item; + + if (sandbox_getaddrinfo_cache_disabled) { + return getaddrinfo(name, NULL, hints, res); + } + + if (servname != NULL) { + log_warn(LD_BUG, "called with non-NULL servname"); + return EAI_NONAME; + } + if (name == NULL) { + log_warn(LD_BUG, "called with NULL name"); + return EAI_NONAME; + } + + *res = NULL; + + memset(&search, 0, sizeof(search)); + search.name = (char *) name; + search.family = hints ? hints->ai_family : AF_UNSPEC; + item = HT_FIND(getaddrinfo_cache, &getaddrinfo_cache, &search); + + if (! sandbox_getaddrinfo_is_active) { + /* If the sandbox is not turned on yet, then getaddrinfo and store the + result. */ + + err = getaddrinfo(name, NULL, hints, res); + log_info(LD_NET,"(Sandbox) getaddrinfo %s.", err ? "failed" : "succeeded"); + + if (! item) { + item = tor_malloc_zero(sizeof(*item)); + item->name = tor_strdup(name); + item->family = hints ? hints->ai_family : AF_UNSPEC; + HT_INSERT(getaddrinfo_cache, &getaddrinfo_cache, item); + } + + if (item->res) { + freeaddrinfo(item->res); + item->res = NULL; + } + item->res = *res; + item->err = err; + return err; + } + + /* Otherwise, the sandbox is on. If we have an item, yield its cached + result. */ + if (item) { + *res = item->res; + return item->err; + } + + /* getting here means something went wrong */ + log_err(LD_BUG,"(Sandbox) failed to get address %s!", name); + return EAI_NONAME; +} + +int +tor_add_addrinfo(const char *name) +{ + struct addrinfo *res; + struct addrinfo hints; + int i; + static const int families[] = { AF_INET, AF_INET6, AF_UNSPEC }; + + memset(&hints, 0, sizeof(hints)); + hints.ai_socktype = SOCK_STREAM; + for (i = 0; i < 3; ++i) { + hints.ai_family = families[i]; + + res = NULL; + (void) tor_getaddrinfo(name, NULL, &hints, &res); + if (res) + tor_freeaddrinfo(res); + } + + return 0; +} + +void +tor_free_getaddrinfo_cache(void) +{ + cached_getaddrinfo_item_t **next, **item, *this; + + for (item = HT_START(getaddrinfo_cache, &getaddrinfo_cache); + item; + item = next) { + this = *item; + next = HT_NEXT_RMV(getaddrinfo_cache, &getaddrinfo_cache, item); + cached_getaddrinfo_item_free(this); + } + + HT_CLEAR(getaddrinfo_cache, &getaddrinfo_cache); +} + +void +tor_make_getaddrinfo_cache_active(void) +{ + sandbox_getaddrinfo_is_active = 1; +} +#endif diff --git a/src/lib/net/resolve.h b/src/lib/net/resolve.h new file mode 100644 index 0000000000..bf870c44c4 --- /dev/null +++ b/src/lib/net/resolve.h @@ -0,0 +1,58 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file resolve.h + * \brief Header for resolve.c + **/ + +#ifndef TOR_RESOLVE_H +#define TOR_RESOLVE_H + +#include "orconfig.h" +#include "lib/cc/torint.h" +#include "lib/testsupport/testsupport.h" +#ifdef _WIN32 +#include <winsock2.h> +#endif + +#if defined(HAVE_SECCOMP_H) && defined(__linux__) +#define USE_SANDBOX_GETADDRINFO +#endif + +struct tor_addr_t; + +MOCK_DECL(int, tor_lookup_hostname,(const char *name, uint32_t *addr)); +MOCK_DECL(int, tor_addr_lookup,(const char *name, uint16_t family, + struct tor_addr_t *addr_out)); +int tor_addr_port_lookup(const char *s, struct tor_addr_t *addr_out, + uint16_t *port_out); + +struct addrinfo; +#ifdef USE_SANDBOX_GETADDRINFO +/** Pre-calls getaddrinfo in order to pre-record result. */ +int tor_add_addrinfo(const char *addr); + +struct addrinfo; +/** Replacement for getaddrinfo(), using pre-recorded results. */ +int tor_getaddrinfo(const char *name, const char *servname, + const struct addrinfo *hints, + struct addrinfo **res); +void tor_freeaddrinfo(struct addrinfo *addrinfo); +void tor_free_getaddrinfo_cache(void); +void tor_make_getaddrinfo_cache_active(void); +#else /* !(defined(USE_SANDBOX_GETADDRINFO)) */ +#define tor_getaddrinfo(name, servname, hints, res) \ + getaddrinfo((name),(servname), (hints),(res)) +#define tor_add_addrinfo(name) \ + ((void)(name)) +#define tor_freeaddrinfo(addrinfo) \ + freeaddrinfo((addrinfo)) +#define tor_free_getaddrinfo_cache() +#endif /* defined(USE_SANDBOX_GETADDRINFO) */ + +void sandbox_disable_getaddrinfo_cache(void); + +#endif diff --git a/src/lib/net/socket.c b/src/lib/net/socket.c new file mode 100644 index 0000000000..cd7c9685cd --- /dev/null +++ b/src/lib/net/socket.c @@ -0,0 +1,697 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file socket.c + * \brief Compatibility and utility functions for working with network + * sockets. + **/ + +#define SOCKET_PRIVATE +#include "lib/net/socket.h" +#include "lib/net/socketpair.h" +#include "lib/net/address.h" +#include "lib/cc/compat_compiler.h" +#include "lib/err/torerr.h" +#include "lib/lock/compat_mutex.h" +#include "lib/log/log.h" +#include "lib/log/util_bug.h" + +#ifdef _WIN32 +#include <winsock2.h> +#include <windows.h> +#endif +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_FCNTL_H +#include <fcntl.h> +#endif +#include <stddef.h> +#include <string.h> + +/** Called before we make any calls to network-related functions. + * (Some operating systems require their network libraries to be + * initialized.) */ +int +network_init(void) +{ +#ifdef _WIN32 + /* This silly exercise is necessary before windows will allow + * gethostbyname to work. */ + WSADATA WSAData; + int r; + r = WSAStartup(0x101,&WSAData); + if (r) { + log_warn(LD_NET,"Error initializing windows network layer: code was %d",r); + return -1; + } + if (sizeof(SOCKET) != sizeof(tor_socket_t)) { + log_warn(LD_BUG,"The tor_socket_t type does not match SOCKET in size; Tor " + "might not work. (Sizes are %d and %d respectively.)", + (int)sizeof(tor_socket_t), (int)sizeof(SOCKET)); + } + /* WSAData.iMaxSockets might show the max sockets we're allowed to use. + * We might use it to complain if we're trying to be a server but have + * too few sockets available. */ +#endif /* defined(_WIN32) */ + return 0; +} + +/* When set_max_file_sockets() is called, update this with the max file + * descriptor value so we can use it to check the limit when opening a new + * socket. Default value is what Debian sets as the default hard limit. */ +static int max_sockets = 1024; + +/** Return the maximum number of allowed sockets. */ +int +get_max_sockets(void) +{ + return max_sockets; +} + +/** Set the maximum number of allowed sockets to <b>n</b> */ +void +set_max_sockets(int n) +{ + max_sockets = n; +} + +#undef DEBUG_SOCKET_COUNTING +#ifdef DEBUG_SOCKET_COUNTING +#include "lib/container/bitarray.h" + +/** A bitarray of all fds that should be passed to tor_socket_close(). Only + * used if DEBUG_SOCKET_COUNTING is defined. */ +static bitarray_t *open_sockets = NULL; +/** The size of <b>open_sockets</b>, in bits. */ +static int max_socket = -1; +#endif /* defined(DEBUG_SOCKET_COUNTING) */ + +/** Count of number of sockets currently open. (Undercounts sockets opened by + * eventdns and libevent.) */ +static int n_sockets_open = 0; + +/** Mutex to protect open_sockets, max_socket, and n_sockets_open. */ +static tor_mutex_t *socket_accounting_mutex = NULL; + +/** Helper: acquire the socket accounting lock. */ +static inline void +socket_accounting_lock(void) +{ + if (PREDICT_UNLIKELY(!socket_accounting_mutex)) + socket_accounting_mutex = tor_mutex_new(); + tor_mutex_acquire(socket_accounting_mutex); +} + +/** Helper: release the socket accounting lock. */ +static inline void +socket_accounting_unlock(void) +{ + tor_mutex_release(socket_accounting_mutex); +} + +/** As close(), but guaranteed to work for sockets across platforms (including + * Windows, where close()ing a socket doesn't work. Returns 0 on success and + * the socket error code on failure. */ +int +tor_close_socket_simple(tor_socket_t s) +{ + int r = 0; + + /* On Windows, you have to call close() on fds returned by open(), + * and closesocket() on fds returned by socket(). On Unix, everything + * gets close()'d. We abstract this difference by always using + * tor_close_socket to close sockets, and always using close() on + * files. + */ + #if defined(_WIN32) + r = closesocket(s); + #else + r = close(s); + #endif + + if (r != 0) { + int err = tor_socket_errno(-1); + log_info(LD_NET, "Close returned an error: %s", tor_socket_strerror(err)); + return err; + } + + return r; +} + +/** @{ */ +#ifdef DEBUG_SOCKET_COUNTING +/** Helper: if DEBUG_SOCKET_COUNTING is enabled, remember that <b>s</b> is + * now an open socket. */ +static inline void +mark_socket_open(tor_socket_t s) +{ + /* XXXX This bitarray business will NOT work on windows: sockets aren't + small ints there. */ + if (s > max_socket) { + if (max_socket == -1) { + open_sockets = bitarray_init_zero(s+128); + max_socket = s+128; + } else { + open_sockets = bitarray_expand(open_sockets, max_socket, s+128); + max_socket = s+128; + } + } + if (bitarray_is_set(open_sockets, s)) { + log_warn(LD_BUG, "I thought that %d was already open, but socket() just " + "gave it to me!", s); + } + bitarray_set(open_sockets, s); +} +static inline void +mark_socket_closed(tor_socket_t s) +{ + if (s > max_socket || ! bitarray_is_set(open_sockets, s)) { + log_warn(LD_BUG, "Closing a socket (%d) that wasn't returned by tor_open_" + "socket(), or that was already closed or something.", s); + } else { + tor_assert(open_sockets && s <= max_socket); + bitarray_clear(open_sockets, s); + } +} +#else /* !(defined(DEBUG_SOCKET_COUNTING)) */ +#define mark_socket_open(s) ((void) (s)) +#define mark_socket_closed(s) ((void) (s)) +#endif /* defined(DEBUG_SOCKET_COUNTING) */ +/** @} */ + +/** As tor_close_socket_simple(), but keeps track of the number + * of open sockets. Returns 0 on success, -1 on failure. */ +MOCK_IMPL(int, +tor_close_socket,(tor_socket_t s)) +{ + int r = tor_close_socket_simple(s); + + socket_accounting_lock(); + mark_socket_closed(s); + if (r == 0) { + --n_sockets_open; + } else { +#ifdef _WIN32 + if (r != WSAENOTSOCK) + --n_sockets_open; +#else + if (r != EBADF) + --n_sockets_open; // LCOV_EXCL_LINE -- EIO and EINTR too hard to force. +#endif /* defined(_WIN32) */ + r = -1; + } + + tor_assert_nonfatal(n_sockets_open >= 0); + socket_accounting_unlock(); + return r; +} + +/** As socket(), but counts the number of open sockets. */ +MOCK_IMPL(tor_socket_t, +tor_open_socket,(int domain, int type, int protocol)) +{ + return tor_open_socket_with_extensions(domain, type, protocol, 1, 0); +} + +/** Mockable wrapper for connect(). */ +MOCK_IMPL(tor_socket_t, +tor_connect_socket,(tor_socket_t sock, const struct sockaddr *address, + socklen_t address_len)) +{ + return connect(sock,address,address_len); +} + +/** As socket(), but creates a nonblocking socket and + * counts the number of open sockets. */ +tor_socket_t +tor_open_socket_nonblocking(int domain, int type, int protocol) +{ + return tor_open_socket_with_extensions(domain, type, protocol, 1, 1); +} + +/** As socket(), but counts the number of open sockets and handles + * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified. + * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate + * if the corresponding extension should be used.*/ +tor_socket_t +tor_open_socket_with_extensions(int domain, int type, int protocol, + int cloexec, int nonblock) +{ + tor_socket_t s; + + /* We are about to create a new file descriptor so make sure we have + * enough of them. */ + if (get_n_open_sockets() >= max_sockets - 1) { +#ifdef _WIN32 + WSASetLastError(WSAEMFILE); +#else + errno = EMFILE; +#endif + return TOR_INVALID_SOCKET; + } + +#if defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) + int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) | + (nonblock ? SOCK_NONBLOCK : 0); + s = socket(domain, type|ext_flags, protocol); + if (SOCKET_OK(s)) + goto socket_ok; + /* If we got an error, see if it is EINVAL. EINVAL might indicate that, + * even though we were built on a system with SOCK_CLOEXEC and SOCK_NONBLOCK + * support, we are running on one without. */ + if (errno != EINVAL) + return s; +#endif /* defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK) */ + + s = socket(domain, type, protocol); + if (! SOCKET_OK(s)) + return s; + +#if defined(FD_CLOEXEC) + if (cloexec) { + if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) { + log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno)); + tor_close_socket_simple(s); + return TOR_INVALID_SOCKET; + } + } +#else /* !(defined(FD_CLOEXEC)) */ + (void)cloexec; +#endif /* defined(FD_CLOEXEC) */ + + if (nonblock) { + if (set_socket_nonblocking(s) == -1) { + tor_close_socket_simple(s); + return TOR_INVALID_SOCKET; + } + } + + goto socket_ok; /* So that socket_ok will not be unused. */ + + socket_ok: + tor_take_socket_ownership(s); + return s; +} + +/** + * For socket accounting: remember that we are the owner of the socket + * <b>s</b>. This will prevent us from overallocating sockets, and prevent us + * from asserting later when we close the socket <b>s</b>. + */ +void +tor_take_socket_ownership(tor_socket_t s) +{ + socket_accounting_lock(); + ++n_sockets_open; + mark_socket_open(s); + socket_accounting_unlock(); +} + +/** + * For socket accounting: declare that we are no longer the owner of the + * socket <b>s</b>. This will prevent us from overallocating sockets, and + * prevent us from asserting later when we close the socket <b>s</b>. + */ +void +tor_release_socket_ownership(tor_socket_t s) +{ + socket_accounting_lock(); + --n_sockets_open; + mark_socket_closed(s); + socket_accounting_unlock(); +} + +/** As accept(), but counts the number of open sockets. */ +tor_socket_t +tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, socklen_t *len) +{ + return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 0); +} + +/** As accept(), but returns a nonblocking socket and + * counts the number of open sockets. */ +tor_socket_t +tor_accept_socket_nonblocking(tor_socket_t sockfd, struct sockaddr *addr, + socklen_t *len) +{ + return tor_accept_socket_with_extensions(sockfd, addr, len, 1, 1); +} + +/** As accept(), but counts the number of open sockets and handles + * socket creation with either of SOCK_CLOEXEC and SOCK_NONBLOCK specified. + * <b>cloexec</b> and <b>nonblock</b> should be either 0 or 1 to indicate + * if the corresponding extension should be used.*/ +tor_socket_t +tor_accept_socket_with_extensions(tor_socket_t sockfd, struct sockaddr *addr, + socklen_t *len, int cloexec, int nonblock) +{ + tor_socket_t s; + + /* We are about to create a new file descriptor so make sure we have + * enough of them. */ + if (get_n_open_sockets() >= max_sockets - 1) { +#ifdef _WIN32 + WSASetLastError(WSAEMFILE); +#else + errno = EMFILE; +#endif + return TOR_INVALID_SOCKET; + } + +#if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) \ + && defined(SOCK_NONBLOCK) + int ext_flags = (cloexec ? SOCK_CLOEXEC : 0) | + (nonblock ? SOCK_NONBLOCK : 0); + s = accept4(sockfd, addr, len, ext_flags); + if (SOCKET_OK(s)) + goto socket_ok; + /* If we got an error, see if it is ENOSYS. ENOSYS indicates that, + * even though we were built on a system with accept4 support, we + * are running on one without. Also, check for EINVAL, which indicates that + * we are missing SOCK_CLOEXEC/SOCK_NONBLOCK support. */ + if (errno != EINVAL && errno != ENOSYS) + return s; +#endif /* defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) ... */ + + s = accept(sockfd, addr, len); + if (!SOCKET_OK(s)) + return s; + +#if defined(FD_CLOEXEC) + if (cloexec) { + if (fcntl(s, F_SETFD, FD_CLOEXEC) == -1) { + log_warn(LD_NET, "Couldn't set FD_CLOEXEC: %s", strerror(errno)); + tor_close_socket_simple(s); + return TOR_INVALID_SOCKET; + } + } +#else /* !(defined(FD_CLOEXEC)) */ + (void)cloexec; +#endif /* defined(FD_CLOEXEC) */ + + if (nonblock) { + if (set_socket_nonblocking(s) == -1) { + tor_close_socket_simple(s); + return TOR_INVALID_SOCKET; + } + } + + goto socket_ok; /* So that socket_ok will not be unused. */ + + socket_ok: + tor_take_socket_ownership(s); + return s; +} + +/** Return the number of sockets we currently have opened. */ +int +get_n_open_sockets(void) +{ + int n; + socket_accounting_lock(); + n = n_sockets_open; + socket_accounting_unlock(); + return n; +} + +/** + * Allocate a pair of connected sockets. (Like socketpair(family, + * type,protocol,fd), but works on systems that don't have + * socketpair.) + * + * Currently, only (AF_UNIX, SOCK_STREAM, 0) sockets are supported. + * + * Note that on systems without socketpair, this call will fail if + * localhost is inaccessible (for example, if the networking + * stack is down). And even if it succeeds, the socket pair will not + * be able to read while localhost is down later (the socket pair may + * even close, depending on OS-specific timeouts). + * + * Returns 0 on success and -errno on failure; do not rely on the value + * of errno or WSAGetLastError(). + **/ +/* It would be nicer just to set errno, but that won't work for windows. */ +int +tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2]) +{ + int r; +//don't use win32 socketpairs (they are always bad) +#if defined(HAVE_SOCKETPAIR) && !defined(_WIN32) + +#ifdef SOCK_CLOEXEC + r = socketpair(family, type|SOCK_CLOEXEC, protocol, fd); + if (r == 0) + goto sockets_ok; + /* If we got an error, see if it is EINVAL. EINVAL might indicate that, + * even though we were built on a system with SOCK_CLOEXEC support, we + * are running on one without. */ + if (errno != EINVAL) + return -errno; +#endif /* defined(SOCK_CLOEXEC) */ + + r = socketpair(family, type, protocol, fd); + if (r < 0) + return -errno; +#else + r = tor_ersatz_socketpair(family, type, protocol, fd); + if (r < 0) + return -r; +#endif + +#if defined(FD_CLOEXEC) + if (SOCKET_OK(fd[0])) { + r = fcntl(fd[0], F_SETFD, FD_CLOEXEC); + if (r == -1) { + close(fd[0]); + close(fd[1]); + return -errno; + } + } + if (SOCKET_OK(fd[1])) { + r = fcntl(fd[1], F_SETFD, FD_CLOEXEC); + if (r == -1) { + close(fd[0]); + close(fd[1]); + return -errno; + } + } +#endif /* defined(FD_CLOEXEC) */ + goto sockets_ok; /* So that sockets_ok will not be unused. */ + + sockets_ok: + socket_accounting_lock(); + if (SOCKET_OK(fd[0])) { + ++n_sockets_open; + mark_socket_open(fd[0]); + } + if (SOCKET_OK(fd[1])) { + ++n_sockets_open; + mark_socket_open(fd[1]); + } + socket_accounting_unlock(); + + return 0; +} + +/** Mockable wrapper for getsockname(). */ +MOCK_IMPL(int, +tor_getsockname,(tor_socket_t sock, struct sockaddr *address, + socklen_t *address_len)) +{ + return getsockname(sock, address, address_len); +} + +/** + * Find the local address associated with the socket <b>sock</b>, and + * place it in *<b>addr_out</b>. Return 0 on success, -1 on failure. + * + * (As tor_getsockname, but instead places the result in a tor_addr_t.) */ +int +tor_addr_from_getsockname(struct tor_addr_t *addr_out, tor_socket_t sock) +{ + struct sockaddr_storage ss; + socklen_t ss_len = sizeof(ss); + memset(&ss, 0, sizeof(ss)); + + if (tor_getsockname(sock, (struct sockaddr *) &ss, &ss_len) < 0) + return -1; + + return tor_addr_from_sockaddr(addr_out, (struct sockaddr *)&ss, NULL); +} + +/** Turn <b>socket</b> into a nonblocking socket. Return 0 on success, -1 + * on failure. + */ +int +set_socket_nonblocking(tor_socket_t sock) +{ +#if defined(_WIN32) + unsigned long nonblocking = 1; + ioctlsocket(sock, FIONBIO, (unsigned long*) &nonblocking); +#else + int flags; + + flags = fcntl(sock, F_GETFL, 0); + if (flags == -1) { + log_warn(LD_NET, "Couldn't get file status flags: %s", strerror(errno)); + return -1; + } + flags |= O_NONBLOCK; + if (fcntl(sock, F_SETFL, flags) == -1) { + log_warn(LD_NET, "Couldn't set file status flags: %s", strerror(errno)); + return -1; + } +#endif /* defined(_WIN32) */ + + return 0; +} + +/** Read from <b>sock</b> to <b>buf</b>, until we get <b>count</b> bytes or + * reach the end of the file. Return the number of bytes read, or -1 on + * error. Only use if fd is a blocking fd. */ +ssize_t +read_all_from_socket(tor_socket_t sock, char *buf, size_t count) +{ + size_t numread = 0; + ssize_t result; + + if (count > SIZE_T_CEILING || count > SSIZE_MAX) { + errno = EINVAL; + return -1; + } + + while (numread < count) { + result = tor_socket_recv(sock, buf+numread, count-numread, 0); + if (result<0) + return -1; + else if (result == 0) + break; + numread += result; + } + return (ssize_t)numread; +} + +/** Write <b>count</b> bytes from <b>buf</b> to <b>sock</b>. Return the number + * of bytes written, or -1 on error. Only use if fd is a blocking fd. */ +ssize_t +write_all_to_socket(tor_socket_t fd, const char *buf, size_t count) +{ + size_t written = 0; + ssize_t result; + raw_assert(count < SSIZE_MAX); + + while (written != count) { + result = tor_socket_send(fd, buf+written, count-written, 0); + if (result<0) + return -1; + written += result; + } + return (ssize_t)count; +} + +/** + * On Windows, WSAEWOULDBLOCK is not always correct: when you see it, + * you need to ask the socket for its actual errno. Also, you need to + * get your errors from WSAGetLastError, not errno. (If you supply a + * socket of -1, we check WSAGetLastError, but don't correct + * WSAEWOULDBLOCKs.) + * + * The upshot of all of this is that when a socket call fails, you + * should call tor_socket_errno <em>at most once</em> on the failing + * socket to get the error. + */ +#if defined(_WIN32) +int +tor_socket_errno(tor_socket_t sock) +{ + int optval, optvallen=sizeof(optval); + int err = WSAGetLastError(); + if (err == WSAEWOULDBLOCK && SOCKET_OK(sock)) { + if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen)) + return err; + if (optval) + return optval; + } + return err; +} +#endif /* defined(_WIN32) */ + +#if defined(_WIN32) +#define E(code, s) { code, (s " [" #code " ]") } +struct { int code; const char *msg; } windows_socket_errors[] = { + E(WSAEINTR, "Interrupted function call"), + E(WSAEACCES, "Permission denied"), + E(WSAEFAULT, "Bad address"), + E(WSAEINVAL, "Invalid argument"), + E(WSAEMFILE, "Too many open files"), + E(WSAEWOULDBLOCK, "Resource temporarily unavailable"), + E(WSAEINPROGRESS, "Operation now in progress"), + E(WSAEALREADY, "Operation already in progress"), + E(WSAENOTSOCK, "Socket operation on nonsocket"), + E(WSAEDESTADDRREQ, "Destination address required"), + E(WSAEMSGSIZE, "Message too long"), + E(WSAEPROTOTYPE, "Protocol wrong for socket"), + E(WSAENOPROTOOPT, "Bad protocol option"), + E(WSAEPROTONOSUPPORT, "Protocol not supported"), + E(WSAESOCKTNOSUPPORT, "Socket type not supported"), + /* What's the difference between NOTSUPP and NOSUPPORT? :) */ + E(WSAEOPNOTSUPP, "Operation not supported"), + E(WSAEPFNOSUPPORT, "Protocol family not supported"), + E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"), + E(WSAEADDRINUSE, "Address already in use"), + E(WSAEADDRNOTAVAIL, "Cannot assign requested address"), + E(WSAENETDOWN, "Network is down"), + E(WSAENETUNREACH, "Network is unreachable"), + E(WSAENETRESET, "Network dropped connection on reset"), + E(WSAECONNABORTED, "Software caused connection abort"), + E(WSAECONNRESET, "Connection reset by peer"), + E(WSAENOBUFS, "No buffer space available"), + E(WSAEISCONN, "Socket is already connected"), + E(WSAENOTCONN, "Socket is not connected"), + E(WSAESHUTDOWN, "Cannot send after socket shutdown"), + E(WSAETIMEDOUT, "Connection timed out"), + E(WSAECONNREFUSED, "Connection refused"), + E(WSAEHOSTDOWN, "Host is down"), + E(WSAEHOSTUNREACH, "No route to host"), + E(WSAEPROCLIM, "Too many processes"), + /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */ + E(WSASYSNOTREADY, "Network subsystem is unavailable"), + E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"), + E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"), + E(WSAEDISCON, "Graceful shutdown now in progress"), +#ifdef WSATYPE_NOT_FOUND + E(WSATYPE_NOT_FOUND, "Class type not found"), +#endif + E(WSAHOST_NOT_FOUND, "Host not found"), + E(WSATRY_AGAIN, "Nonauthoritative host not found"), + E(WSANO_RECOVERY, "This is a nonrecoverable error"), + E(WSANO_DATA, "Valid name, no data record of requested type)"), + + /* There are some more error codes whose numeric values are marked + * <b>OS dependent</b>. They start with WSA_, apparently for the same + * reason that practitioners of some craft traditions deliberately + * introduce imperfections into their baskets and rugs "to allow the + * evil spirits to escape." If we catch them, then our binaries + * might not report consistent results across versions of Windows. + * Thus, I'm going to let them all fall through. + */ + { -1, NULL }, +}; +/** There does not seem to be a strerror equivalent for Winsock errors. + * Naturally, we have to roll our own. + */ +const char * +tor_socket_strerror(int e) +{ + int i; + for (i=0; windows_socket_errors[i].code >= 0; ++i) { + if (e == windows_socket_errors[i].code) + return windows_socket_errors[i].msg; + } + return strerror(e); +} +#endif /* defined(_WIN32) */ diff --git a/src/lib/net/socket.h b/src/lib/net/socket.h new file mode 100644 index 0000000000..2b87441fc6 --- /dev/null +++ b/src/lib/net/socket.h @@ -0,0 +1,118 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file socket.h + * \brief Header for socket.c + **/ + +#ifndef TOR_SOCKET_H +#define TOR_SOCKET_H + +#include "orconfig.h" +#include "lib/cc/torint.h" +#include "lib/net/nettypes.h" +#include "lib/testsupport/testsupport.h" + +#include <errno.h> + +struct sockaddr; + +int tor_close_socket_simple(tor_socket_t s); +MOCK_DECL(int, tor_close_socket, (tor_socket_t s)); +void tor_take_socket_ownership(tor_socket_t s); +void tor_release_socket_ownership(tor_socket_t s); +tor_socket_t tor_open_socket_with_extensions( + int domain, int type, int protocol, + int cloexec, int nonblock); +MOCK_DECL(tor_socket_t,tor_open_socket,(int domain, int type, int protocol)); +tor_socket_t tor_open_socket_nonblocking(int domain, int type, int protocol); +tor_socket_t tor_accept_socket(tor_socket_t sockfd, struct sockaddr *addr, + socklen_t *len); +tor_socket_t tor_accept_socket_nonblocking(tor_socket_t sockfd, + struct sockaddr *addr, + socklen_t *len); +tor_socket_t tor_accept_socket_with_extensions(tor_socket_t sockfd, + struct sockaddr *addr, + socklen_t *len, + int cloexec, int nonblock); +MOCK_DECL(tor_socket_t, tor_connect_socket,(tor_socket_t socket, + const struct sockaddr *address, + socklen_t address_len)); +int get_n_open_sockets(void); + +MOCK_DECL(int,tor_getsockname,(tor_socket_t socket, struct sockaddr *address, + socklen_t *address_len)); +struct tor_addr_t; +int tor_addr_from_getsockname(struct tor_addr_t *addr_out, tor_socket_t sock); + +#define tor_socket_send(s, buf, len, flags) send(s, buf, len, flags) +#define tor_socket_recv(s, buf, len, flags) recv(s, buf, len, flags) + +int set_socket_nonblocking(tor_socket_t socket); +int tor_socketpair(int family, int type, int protocol, tor_socket_t fd[2]); +int network_init(void); + +int get_max_sockets(void); +void set_max_sockets(int); + +ssize_t write_all_to_socket(tor_socket_t fd, const char *buf, size_t count); +ssize_t read_all_from_socket(tor_socket_t fd, char *buf, size_t count); + +/* For stupid historical reasons, windows sockets have an independent + * set of errnos, and an independent way to get them. Also, you can't + * always believe WSAEWOULDBLOCK. Use the macros below to compare + * errnos against expected values, and use tor_socket_errno to find + * the actual errno after a socket operation fails. + */ +#if defined(_WIN32) +/** Expands to WSA<b>e</b> on Windows, and to <b>e</b> elsewhere. */ +#define SOCK_ERRNO(e) WSA##e +/** Return true if e is EAGAIN or the local equivalent. */ +#define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == WSAEWOULDBLOCK) +/** Return true if e is EINPROGRESS or the local equivalent. */ +#define ERRNO_IS_EINPROGRESS(e) ((e) == WSAEINPROGRESS) +/** Return true if e is EINPROGRESS or the local equivalent as returned by + * a call to connect(). */ +#define ERRNO_IS_CONN_EINPROGRESS(e) \ + ((e) == WSAEINPROGRESS || (e)== WSAEINVAL || (e) == WSAEWOULDBLOCK) +/** Return true if e is EAGAIN or another error indicating that a call to + * accept() has no pending connections to return. */ +#define ERRNO_IS_ACCEPT_EAGAIN(e) ERRNO_IS_EAGAIN(e) +/** Return true if e is EMFILE or another error indicating that a call to + * accept() has failed because we're out of fds or something. */ +#define ERRNO_IS_RESOURCE_LIMIT(e) \ + ((e) == WSAEMFILE || (e) == WSAENOBUFS) +/** Return true if e is EADDRINUSE or the local equivalent. */ +#define ERRNO_IS_EADDRINUSE(e) ((e) == WSAEADDRINUSE) +/** Return true if e is EINTR or the local equivalent */ +#define ERRNO_IS_EINTR(e) ((e) == WSAEINTR || 0) +int tor_socket_errno(tor_socket_t sock); +const char *tor_socket_strerror(int e); +#else /* !(defined(_WIN32)) */ +#define SOCK_ERRNO(e) e +#if EAGAIN == EWOULDBLOCK +/* || 0 is for -Wparentheses-equality (-Wall?) appeasement under clang */ +#define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || 0) +#else +#define ERRNO_IS_EAGAIN(e) ((e) == EAGAIN || (e) == EWOULDBLOCK) +#endif /* EAGAIN == EWOULDBLOCK */ +#define ERRNO_IS_EINTR(e) ((e) == EINTR || 0) +#define ERRNO_IS_EINPROGRESS(e) ((e) == EINPROGRESS || 0) +#define ERRNO_IS_CONN_EINPROGRESS(e) ((e) == EINPROGRESS || 0) +#define ERRNO_IS_ACCEPT_EAGAIN(e) \ + (ERRNO_IS_EAGAIN(e) || (e) == ECONNABORTED) +#define ERRNO_IS_RESOURCE_LIMIT(e) \ + ((e) == EMFILE || (e) == ENFILE || (e) == ENOBUFS || (e) == ENOMEM) +#define ERRNO_IS_EADDRINUSE(e) (((e) == EADDRINUSE) || 0) +#define tor_socket_errno(sock) (errno) +#define tor_socket_strerror(e) strerror(e) +#endif /* defined(_WIN32) */ + +#if defined(_WIN32) && !defined(SIO_IDEAL_SEND_BACKLOG_QUERY) +#define SIO_IDEAL_SEND_BACKLOG_QUERY 0x4004747b +#endif + +#endif diff --git a/src/lib/net/socketpair.c b/src/lib/net/socketpair.c new file mode 100644 index 0000000000..380338f15c --- /dev/null +++ b/src/lib/net/socketpair.c @@ -0,0 +1,214 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ + +#include "lib/cc/torint.h" +#include "lib/net/socketpair.h" +#include "lib/net/inaddr_st.h" +#include "lib/arch/bytes.h" + +#include <errno.h> +#include <string.h> + +#ifdef HAVE_UNISTD_H +#include <unistd.h> +#endif +#ifdef HAVE_NETINET_IN_H +#include <netinet/in.h> +#endif + +#ifdef _WIN32 +#include <winsock2.h> +#include <windows.h> +#define socket_errno() (WSAGetLastError()) +#define SOCKET_EPROTONOSUPPORT WSAEPROTONOSUPPORT +#else +#define closesocket(x) close(x) +#define socket_errno() (errno) +#define SOCKET_EPROTONOSUPPORT EPROTONOSUPPORT +#endif + +#ifdef NEED_ERSATZ_SOCKETPAIR + +// Avoid warning about call to memcmp. +#define raw_memcmp memcmp + +/** + * Return a new socket that is bound and listening on the loopback interface + * of family <b>family</b> for a socket of type <b>type</b>. On failure return + * TOR_INVALID_SOCKET. + */ +static tor_socket_t +get_local_listener(int family, int type) +{ + struct sockaddr_in sin; + struct sockaddr_in6 sin6; + struct sockaddr *sa; + int len; + + memset(&sin, 0, sizeof(sin)); + memset(&sin6, 0, sizeof(sin6)); + + tor_socket_t sock = TOR_INVALID_SOCKET; + sock = socket(family, type, 0); + if (!SOCKET_OK(sock)) { + return TOR_INVALID_SOCKET; + } + + if (family == AF_INET) { + sa = (struct sockaddr *) &sin; + sin.sin_family = AF_INET; + sin.sin_addr.s_addr = tor_htonl(0x7f000001); + len = sizeof(sin); + } else { + sa = (struct sockaddr *) &sin6; + sin6.sin6_family = AF_INET; + sin6.sin6_addr.s6_addr[15] = 1; + len = sizeof(sin6); + } + + if (bind(sock, sa, len) == -1) + goto err; + if (listen(sock, 1) == -1) + goto err; + + return sock; + err: + closesocket(sock); + return TOR_INVALID_SOCKET; +} + +/** + * Return true iff sa1 and sa2 are equivalent AF_INET or AF_INET6 addresses. + */ +static int +sockaddr_eq(struct sockaddr *sa1, struct sockaddr *sa2) +{ + if (sa1->sa_family != sa2->sa_family) + return 0; + + if (sa1->sa_family == AF_INET6) { + struct sockaddr_in6 *sin6_1 = (struct sockaddr_in6 *) sa1; + struct sockaddr_in6 *sin6_2 = (struct sockaddr_in6 *) sa2; + return sin6_1->sin6_port == sin6_2->sin6_port && + 0==raw_memcmp(sin6_1->sin6_addr.s6_addr, sin6_2->sin6_addr.s6_addr, 16); + } else if (sa1->sa_family == AF_INET) { + struct sockaddr_in *sin_1 = (struct sockaddr_in *) sa1; + struct sockaddr_in *sin_2 = (struct sockaddr_in *) sa2; + return sin_1->sin_port == sin_2->sin_port && + sin_1->sin_addr.s_addr == sin_2->sin_addr.s_addr; + } else { + return 0; + } +} + +/** + * Helper used to implement socketpair on systems that lack it, by + * making a direct connection to localhost. + */ +int +tor_ersatz_socketpair(int family, int type, int protocol, tor_socket_t fd[2]) +{ + /* This socketpair does not work when localhost is down. So + * it's really not the same thing at all. But it's close enough + * for now, and really, when localhost is down sometimes, we + * have other problems too. + */ + tor_socket_t listener = TOR_INVALID_SOCKET; + tor_socket_t connector = TOR_INVALID_SOCKET; + tor_socket_t acceptor = TOR_INVALID_SOCKET; + struct sockaddr_storage accepted_addr_ss; + struct sockaddr_storage connect_addr_ss; + struct sockaddr *connect_addr = (struct sockaddr *) &connect_addr_ss; + struct sockaddr *accepted_addr = (struct sockaddr *) &accepted_addr_ss; + socklen_t size; + int saved_errno = -1; + int ersatz_domain = AF_INET; + socklen_t addrlen = sizeof(struct sockaddr_in); + + memset(&accepted_addr_ss, 0, sizeof(accepted_addr_ss)); + memset(&connect_addr_ss, 0, sizeof(connect_addr_ss)); + + if (protocol +#ifdef AF_UNIX + || family != AF_UNIX +#endif + ) { +#ifdef _WIN32 + return -WSAEAFNOSUPPORT; +#else + return -EAFNOSUPPORT; +#endif + } + if (!fd) { + return -EINVAL; + } + + listener = get_local_listener(ersatz_domain, type); + if (!SOCKET_OK(listener)) { + int first_errno = socket_errno(); + if (first_errno == SOCKET_EPROTONOSUPPORT) { + /* Assume we're on an IPv6-only system */ + ersatz_domain = AF_INET6; + addrlen = sizeof(struct sockaddr_in6); + listener = get_local_listener(ersatz_domain, type); + } + if (!SOCKET_OK(listener)) { + /* Keep the previous behaviour, which was to return the IPv4 error. + * (This may be less informative on IPv6-only systems.) + * XX/teor - is there a better way to decide which errno to return? + * (I doubt we care much either way, once there is an error.) + */ + return -first_errno; + } + } + + connector = socket(ersatz_domain, type, 0); + if (!SOCKET_OK(connector)) + goto tidy_up_and_fail; + /* We want to find out the port number to connect to. */ + size = sizeof(connect_addr_ss); + if (getsockname(listener, connect_addr, &size) == -1) + goto tidy_up_and_fail; + if (size != addrlen) + goto abort_tidy_up_and_fail; + if (connect(connector, connect_addr, size) == -1) + goto tidy_up_and_fail; + + size = sizeof(accepted_addr_ss); + acceptor = accept(listener, accepted_addr, &size); + if (!SOCKET_OK(acceptor)) + goto tidy_up_and_fail; + if (size != addrlen) + goto abort_tidy_up_and_fail; + /* Now check we are talking to ourself by matching port and host on the + two sockets. */ + if (getsockname(connector, connect_addr, &size) == -1) + goto tidy_up_and_fail; + /* Set *_tor_addr and *_port to the address and port that was used */ + if (!sockaddr_eq(accepted_addr, connect_addr)) + goto abort_tidy_up_and_fail; + closesocket(listener); + fd[0] = connector; + fd[1] = acceptor; + return 0; + + abort_tidy_up_and_fail: +#ifdef _WIN32 + saved_errno = WSAECONNABORTED; +#else + saved_errno = ECONNABORTED; /* I hope this is portable and appropriate. */ +#endif + tidy_up_and_fail: + if (saved_errno < 0) + saved_errno = errno; + if (SOCKET_OK(listener)) + closesocket(listener); + if (SOCKET_OK(connector)) + closesocket(connector); + if (SOCKET_OK(acceptor)) + closesocket(acceptor); + return -saved_errno; +} + +#endif /* defined(NEED_ERSATZ_SOCKETPAIR) */ diff --git a/src/lib/net/socketpair.h b/src/lib/net/socketpair.h new file mode 100644 index 0000000000..6eecc0737a --- /dev/null +++ b/src/lib/net/socketpair.h @@ -0,0 +1,19 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +#ifndef TOR_SOCKETPAIR_H +#define TOR_SOCKETPAIR_H + +#include "orconfig.h" +#include "lib/testsupport/testsupport.h" +#include "lib/net/nettypes.h" + +#if !defined(HAVE_SOCKETPAIR) || defined(_WIN32) || defined(TOR_UNIT_TESTS) +#define NEED_ERSATZ_SOCKETPAIR +int tor_ersatz_socketpair(int family, int type, int protocol, + tor_socket_t fd[2]); +#endif + +#endif diff --git a/src/lib/net/socks5_status.h b/src/lib/net/socks5_status.h new file mode 100644 index 0000000000..0f31132545 --- /dev/null +++ b/src/lib/net/socks5_status.h @@ -0,0 +1,32 @@ +/* Copyright (c) 2003-2004, Roger Dingledine + * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. + * Copyright (c) 2007-2018, The Tor Project, Inc. */ +/* See LICENSE for licensing information */ + +/** + * \file socks5_status.h + * \brief Status codes used by the SOCKS5 protocol. + **/ + +/* NOTE: it probably isn't necessary to put this header in lib/net, but + * we need it in _some_ lower-level layer for now, since it is used by + * tools/tor-resolve.c. + */ + +#ifndef TOR_SOCKS5_STATUS_H +#define TOR_SOCKS5_STATUS_H + +/** Specified SOCKS5 status codes. */ +typedef enum { + SOCKS5_SUCCEEDED = 0x00, + SOCKS5_GENERAL_ERROR = 0x01, + SOCKS5_NOT_ALLOWED = 0x02, + SOCKS5_NET_UNREACHABLE = 0x03, + SOCKS5_HOST_UNREACHABLE = 0x04, + SOCKS5_CONNECTION_REFUSED = 0x05, + SOCKS5_TTL_EXPIRED = 0x06, + SOCKS5_COMMAND_NOT_SUPPORTED = 0x07, + SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED = 0x08, +} socks5_reply_status_t; + +#endif |