6#include <bitcoin-build-config.h>
26#ifdef HAVE_SOCKADDR_UN
108 if (
net ==
"cjdns") {
132 std::vector<std::string>
names;
133 for (
int n = 0; n <
NET_MAX; ++n) {
146 if (!ContainsNoNUL(
name))
return {};
175 if (!ContainsNoNUL(
name))
return {};
177 if (
strHost.empty())
return {};
193 if (
name.empty() || !ContainsNoNUL(
name)) {
202 std::vector<CService> services;
205 services.emplace_back(addr, port);
213 return services.empty() ? std::nullopt : std::make_optional(services.front());
218 if (!ContainsNoNUL(
name)) {
228#ifdef HAVE_SOCKADDR_UN
236 if (str.size() + 1 >
sizeof(((
sockaddr_un*)
nullptr)->sun_path))
return false;
327 }
else if (
ret == 0) {
356 return "general failure";
358 return "connection not allowed";
360 return "network unreachable";
362 return "host unreachable";
364 return "connection refused";
366 return "TTL expired";
368 return "protocol error";
370 return "address type not supported";
372 return "onion service descriptor can not be found";
374 return "onion service descriptor is invalid";
376 return "onion service introduction failed";
378 return "onion service rendezvous failed";
380 return "onion service missing client authorization";
382 return "onion service wrong client authorization";
384 return "onion service invalid address";
386 return "onion service introduction timed out";
388 return strprintf(
"unknown (0x%02x)", err);
415 LogInfo(
"Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n",
strDest, port);
419 LogError(
"Proxy failed to initialize\n");
424 std::vector<uint8_t>
vAuth;
425 vAuth.push_back(0x01);
426 if (
auth->username.size() > 255 ||
auth->password.size() > 255) {
427 LogError(
"Proxy username or password too long\n");
438 LogError(
"Error reading proxy authentication response\n");
442 LogError(
"Proxy authentication unsuccessful\n");
448 LogError(
"Proxy requested wrong authentication method %02x\n",
pchRet1[1]);
458 vSocks5.push_back((port >> 8) & 0xFF);
459 vSocks5.push_back((port >> 0) & 0xFF);
469 LogError(
"Error while reading proxy response\n");
474 LogError(
"Proxy failed to accept request\n");
484 LogError(
"Error: malformed proxy response\n");
494 LogError(
"Error reading from proxy\n");
502 LogError(
"Error: malformed proxy response\n");
507 LogError(
"Error reading from proxy\n");
511 LogError(
"Error reading from proxy\n");
516 }
catch (
const std::runtime_error&
e) {
517 LogError(
"Error during SOCKS5 proxy handshake: %s\n",
e.what());
533 auto sock = std::make_unique<Sock>(
hSocket);
541 if (!sock->IsSelectable()) {
542 LogInfo(
"Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
551 LogInfo(
"Error setting SO_NOSIGPIPE on socket: %s, continuing anyway\n",
557 if (!sock->SetNonBlocking()) {
562#ifdef HAVE_SOCKADDR_UN
570 LogDebug(
BCLog::NET,
"Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n");
579template<
typename... Args>
603 if (!sock.
Wait(std::chrono::milliseconds{nConnectTimeout}, requested, &occurred)) {
604 LogInfo(
"wait for connect to %s failed: %s\n",
608 }
else if (occurred == 0) {
626 "connect() to %s failed after wait: %s",
674#ifdef HAVE_SOCKADDR_UN
687 memcpy(
addrun.sun_path, path.c_str(), std::min(
sizeof(
addrun.sun_path) - 1, path.length()));
741 for (
int i = 0; i <
NET_MAX; i++) {
786 const std::string& dest,
805 if (!
Socks5(dest, port,
nullptr, *sock)) {
824 if (addr.has_value()) {
830 subnet =
CSubNet{addr.value(), *netmask};
840 subnet =
CSubNet{addr.value()};
Network m_net
Network to which this address belongs.
bool SetSpecial(std::string_view addr)
Parse a Tor or I2P address and set this object to it.
A combination of a network address (CNetAddr) and a (TCP) port.
bool SetSockAddr(const struct sockaddr *paddr, socklen_t addrlen)
Set CService from a network sockaddr.
sa_family_t GetSAFamily() const
Get the address family.
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
std::string ToStringAddrPort() const
A helper class for interruptible sleeps.
Different type to mark Mutex at global scope.
std::unique_ptr< Sock > Connect() const
bool m_tor_stream_isolation
std::string m_unix_socket_path
List of reachable networks.
bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
static constexpr Event SEND
If passed to Wait(), then it will wait for readiness to send to the socket.
virtual bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const
Wait for readiness for input (recv) or output (send).
virtual void SendComplete(std::span< const unsigned char > data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Generate unique credentials for Tor stream isolation.
std::atomic< uint64_t > m_counter
TorStreamIsolationCredentialsGenerator()
ProxyCredentials Generate()
Return the next unique proxy credentials.
const std::string m_prefix
static std::string GenerateUniquePrefix()
Generate a random prefix for each of the credentials returned by this generator.
static constexpr size_t PREFIX_BYTE_LENGTH
Size of session prefix in bytes.
#define WSAGetLastError()
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
#define LogDebug(category,...)
bool ContainsNoNUL(std::string_view str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
@ NET_MAX
Dummy value to indicate the number of NET_* constants.
@ NET_ONION
TOR (v2 or v3)
@ NET_UNROUTABLE
Addresses from these networks are not publicly routable on the global Internet.
@ NET_INTERNAL
A set of addresses that represent the hash of a string or FQDN.
IntrRecvError
Status codes that can be returned by InterruptibleRecv.
SOCKS5Atyp
Values defined for ATYPE in RFC1928.
CSubNet LookupSubNet(const std::string &subnet_str)
Parse and resolve a specified subnet string into the appropriate internal representation.
SOCKS5Command
Values defined for CMD in RFC1928.
static void LogConnectFailure(bool manual_connection, util::ConstevalFormatString< sizeof...(Args)> fmt, const Args &... args)
std::unique_ptr< Sock > ConnectDirectly(const CService &dest, bool manual_connection)
Create a socket and try to connect to the specified service.
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
std::chrono::milliseconds g_socks5_recv_timeout
std::string GetNetworkName(enum Network net)
static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, std::chrono::milliseconds timeout, const Sock &sock)
Try to read a specified number of bytes from a socket.
CThreadInterrupt g_socks5_interrupt
Interrupt SOCKS5 reads or writes.
SOCKSVersion
SOCKS version.
CService GetBindAddress(const Sock &sock)
Get the bind address for a socket as CService.
bool SetNameProxy(const Proxy &addrProxy)
Set the name proxy to use for all connections to nodes specified by a hostname.
enum Network ParseNetwork(const std::string &net_in)
SOCKS5Method
Values defined for METHOD in RFC1928.
@ NOAUTH
No authentication required.
@ USER_PASS
Username/password.
@ NO_ACCEPTABLE
No acceptable methods.
bool Socks5(const std::string &strDest, uint16_t port, const ProxyCredentials *auth, const Sock &sock)
Connect to a specified destination service through an already connected SOCKS5 proxy.
static std::string Socks5ErrorString(uint8_t err)
Convert SOCKS5 reply to an error message.
bool SetProxy(enum Network net, const Proxy &addrProxy)
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
static std::vector< CNetAddr > LookupIntern(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
SOCKS5Reply
Values defined for REP in RFC1928 and https://spec.torproject.org/socks-extensions....
@ TTLEXPIRED
RFC1928: TTL expired.
@ CMDUNSUPPORTED
RFC1928: Command not supported.
@ TOR_HS_WRONG_CLIENT_AUTH
Tor: Onion service wrong client authorization.
@ TOR_HS_DESC_INVALID
Tor: Onion service descriptor is invalid.
@ NETUNREACHABLE
RFC1928: Network unreachable.
@ GENFAILURE
RFC1928: General failure.
@ TOR_HS_MISSING_CLIENT_AUTH
Tor: Onion service missing client authorization.
@ CONNREFUSED
RFC1928: Connection refused.
@ TOR_HS_BAD_ADDRESS
Tor: Onion service invalid address.
@ SUCCEEDED
RFC1928: Succeeded.
@ ATYPEUNSUPPORTED
RFC1928: Address type not supported.
@ NOTALLOWED
RFC1928: Connection not allowed by ruleset.
@ TOR_HS_INTRO_FAILED
Tor: Onion service introduction failed.
@ TOR_HS_DESC_NOT_FOUND
Tor: Onion service descriptor can not be found.
@ HOSTUNREACHABLE
RFC1928: Network unreachable.
@ TOR_HS_INTRO_TIMEOUT
Tor: Onion service introduction timed out.
@ TOR_HS_REND_FAILED
Tor: Onion service rendezvous failed.
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
static GlobalMutex g_proxyinfo_mutex
ReachableNets g_reachable_nets
std::unique_ptr< Sock > CreateSockOS(int domain, int type, int protocol)
Create a real socket from the operating system.
bool GetProxy(enum Network net, Proxy &proxyInfoOut)
static bool ConnectToSocket(const Sock &sock, struct sockaddr *sockaddr, socklen_t len, const std::string &dest_str, bool manual_connection)
std::unique_ptr< Sock > ConnectThroughProxy(const Proxy &proxy, const std::string &dest, uint16_t port, bool &proxy_connection_failed)
Connect to a specified destination service through a SOCKS5 proxy by first connecting to the SOCKS5 p...
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
bool IsUnixSocketPath(const std::string &name)
Check if a string is a valid UNIX domain socket path.
bool GetNameProxy(Proxy &nameProxyOut)
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
bool IsProxy(const CNetAddr &addr)
bool IsBadPort(uint16_t port)
Determine if a port is "bad" from the perspective of attempting to connect to a node on that port.
std::vector< CNetAddr > WrappedGetAddrInfo(const std::string &name, bool allow_lookup)
Wrapper for getaddrinfo(3).
std::vector< std::string > GetNetworkNames(bool append_unroutable)
Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE.
std::unique_ptr< Sock > ConnectDirectly(const CService &dest, bool manual_connection)
Create a socket and try to connect to the specified service.
static const int DEFAULT_NAME_LOOKUP
-dns default
const std::string ADDR_PREFIX_UNIX
Prefix for unix domain socket addresses (which are local filesystem paths)
std::function< std::vector< CNetAddr >(const std::string &, bool)> DNSLookupFn
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
static const int DEFAULT_CONNECT_TIMEOUT
-timeout default
void GetRandBytes(std::span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Credentials for proxy authentication.
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.