LCOV - code coverage report
Current view: top level - src - netbase.cpp (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 186 433 43.0 %
Date: 2026-06-25 07:23:51 Functions: 25 35 71.4 %

          Line data    Source code
       1             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2             : // Copyright (c) 2009-2021 The Bitcoin Core developers
       3             : // Distributed under the MIT software license, see the accompanying
       4             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5             : 
       6             : #if defined(HAVE_CONFIG_H)
       7             : #include <config/bitcoin-config.h>
       8             : #endif
       9             : 
      10             : #include <netbase.h>
      11             : 
      12             : #include <compat/compat.h>
      13             : #include <sync.h>
      14             : #include <tinyformat.h>
      15             : #include <util/sock.h>
      16             : #include <util/strencodings.h>
      17             : #include <util/string.h>
      18             : #include <util/system.h>
      19             : #include <util/time.h>
      20             : 
      21             : #include <atomic>
      22             : #include <chrono>
      23             : #include <cstdint>
      24             : #include <functional>
      25             : #include <memory>
      26             : 
      27             : #if HAVE_SOCKADDR_UN
      28             : #include <sys/un.h>
      29             : #endif
      30             : 
      31             : // Settings
      32             : static GlobalMutex g_proxyinfo_mutex;
      33        1526 : static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);
      34         218 : static Proxy nameProxy GUARDED_BY(g_proxyinfo_mutex);
      35             : int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
      36             : bool fNameLookup = DEFAULT_NAME_LOOKUP;
      37             : 
      38             : // Need ample time for negotiation for very slow proxies such as Tor
      39             : std::chrono::milliseconds g_socks5_recv_timeout = 20s;
      40             : static std::atomic<bool> interruptSocks5Recv(false);
      41             : 
      42         218 : ReachableNets g_reachable_nets;
      43             : 
      44       13920 : std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup)
      45             : {
      46       13920 :     addrinfo ai_hint{};
      47             :     // We want a TCP port, which is a streaming socket type
      48       13920 :     ai_hint.ai_socktype = SOCK_STREAM;
      49       13920 :     ai_hint.ai_protocol = IPPROTO_TCP;
      50             :     // We don't care which address family (IPv4 or IPv6) is returned
      51       13920 :     ai_hint.ai_family = AF_UNSPEC;
      52             : 
      53             :     // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only
      54             :     // return addresses whose family we have an address configured for.
      55             :     //
      56             :     // If we don't allow lookups, then use the AI_NUMERICHOST flag for
      57             :     // getaddrinfo to only decode numerical network addresses and suppress
      58             :     // hostname lookups.
      59       13920 :     ai_hint.ai_flags = allow_lookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
      60             : 
      61       13920 :     addrinfo* ai_res{nullptr};
      62       13920 :     const int n_err{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
      63       13920 :     if (n_err != 0) {
      64          14 :         if ((ai_hint.ai_flags & AI_ADDRCONFIG) == AI_ADDRCONFIG) {
      65             :             // AI_ADDRCONFIG on some systems may exclude loopback-only addresses
      66             :             // If first lookup failed we perform a second lookup without AI_ADDRCONFIG
      67           0 :             ai_hint.ai_flags = (ai_hint.ai_flags & ~AI_ADDRCONFIG);
      68           0 :             const int n_err_retry{getaddrinfo(name.c_str(), nullptr, &ai_hint, &ai_res)};
      69           0 :             if (n_err_retry != 0) {
      70           0 :                 return {};
      71             :             }
      72           0 :         } else {
      73          14 :             return {};
      74             :         }
      75           0 :     }
      76             : 
      77             :     // Traverse the linked list starting with ai_trav.
      78       13906 :     addrinfo* ai_trav{ai_res};
      79       13906 :     std::vector<CNetAddr> resolved_addresses;
      80       27822 :     while (ai_trav != nullptr) {
      81       13916 :         if (ai_trav->ai_family == AF_INET) {
      82       13784 :             assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in));
      83       13784 :             resolved_addresses.emplace_back(reinterpret_cast<sockaddr_in*>(ai_trav->ai_addr)->sin_addr);
      84       13784 :         }
      85       13916 :         if (ai_trav->ai_family == AF_INET6) {
      86         132 :             assert(ai_trav->ai_addrlen >= sizeof(sockaddr_in6));
      87         132 :             const sockaddr_in6* s6{reinterpret_cast<sockaddr_in6*>(ai_trav->ai_addr)};
      88         132 :             resolved_addresses.emplace_back(s6->sin6_addr, s6->sin6_scope_id);
      89         132 :         }
      90       13916 :         ai_trav = ai_trav->ai_next;
      91             :     }
      92       13906 :     freeaddrinfo(ai_res);
      93             : 
      94       13906 :     return resolved_addresses;
      95       27826 : }
      96             : 
      97         218 : DNSLookupFn g_dns_lookup{WrappedGetAddrInfo};
      98             : 
      99          14 : enum Network ParseNetwork(const std::string& net_in) {
     100          14 :     std::string net = ToLower(net_in);
     101          14 :     if (net == "ipv4") return NET_IPV4;
     102          12 :     if (net == "ipv6") return NET_IPV6;
     103          10 :     if (net == "onion") return NET_ONION;
     104           8 :     if (net == "tor") {
     105           2 :         LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n");
     106           2 :         return NET_ONION;
     107             :     }
     108           6 :     if (net == "i2p") {
     109           0 :         return NET_I2P;
     110             :     }
     111           6 :     if (net == "cjdns") {
     112           2 :         return NET_CJDNS;
     113             :     }
     114           4 :     return NET_UNROUTABLE;
     115          14 : }
     116             : 
     117        5557 : std::string GetNetworkName(enum Network net)
     118             : {
     119        5557 :     switch (net) {
     120          92 :     case NET_UNROUTABLE: return "not_publicly_routable";
     121        1093 :     case NET_IPV4: return "ipv4";
     122        1093 :     case NET_IPV6: return "ipv6";
     123        1093 :     case NET_ONION: return "onion";
     124        1093 :     case NET_I2P: return "i2p";
     125        1093 :     case NET_CJDNS: return "cjdns";
     126           0 :     case NET_INTERNAL: return "internal";
     127           0 :     case NET_MAX: assert(false);
     128             :     } // no default case, so the compiler can warn about missing cases
     129             : 
     130           0 :     assert(false);
     131        5557 : }
     132             : 
     133        1090 : std::vector<std::string> GetNetworkNames(bool append_unroutable)
     134             : {
     135        1090 :     std::vector<std::string> names;
     136        8720 :     for (int n = 0; n < NET_MAX; ++n) {
     137        7630 :         const enum Network network{static_cast<Network>(n)};
     138        7630 :         if (network == NET_UNROUTABLE || network == NET_INTERNAL) continue;
     139        5450 :         names.emplace_back(GetNetworkName(network));
     140        5450 :     }
     141        1090 :     if (append_unroutable) {
     142          92 :         names.emplace_back(GetNetworkName(NET_UNROUTABLE));
     143          92 :     }
     144        1090 :     return names;
     145        1090 : }
     146             : 
     147       13931 : static std::vector<CNetAddr> LookupIntern(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
     148             : {
     149       13931 :     if (!ContainsNoNUL(name)) return {};
     150             :     {
     151       13931 :         CNetAddr addr;
     152             :         // From our perspective, onion addresses are not hostnames but rather
     153             :         // direct encodings of CNetAddr much like IPv4 dotted-decimal notation
     154             :         // or IPv6 colon-separated hextet notation. Since we can't use
     155             :         // getaddrinfo to decode them and it wouldn't make sense to resolve
     156             :         // them, we return a network address representing it instead. See
     157             :         // CNetAddr::SetSpecial(const std::string&) for more details.
     158       13931 :         if (addr.SetSpecial(name)) return {addr};
     159       13931 :     }
     160             : 
     161       13920 :     std::vector<CNetAddr> addresses;
     162             : 
     163       27836 :     for (const CNetAddr& resolved : dns_lookup_function(name, fAllowLookup)) {
     164       13916 :         if (nMaxSolutions > 0 && addresses.size() >= nMaxSolutions) {
     165           0 :             break;
     166             :         }
     167             :         /* Never allow resolving to an internal address. Consider any such result invalid */
     168       13916 :         if (!resolved.IsInternal()) {
     169       13915 :             addresses.push_back(resolved);
     170       13915 :         }
     171             :     }
     172             : 
     173       13920 :     return addresses;
     174       27851 : }
     175             : 
     176        7113 : std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
     177             : {
     178        7113 :     if (!ContainsNoNUL(name)) return {};
     179        7110 :     std::string strHost = name;
     180        7110 :     if (strHost.empty()) return {};
     181        7109 :     if (strHost.front() == '[' && strHost.back() == ']') {
     182           0 :         strHost = strHost.substr(1, strHost.size() - 2);
     183           0 :     }
     184             : 
     185        7109 :     return LookupIntern(strHost, nMaxSolutions, fAllowLookup, dns_lookup_function);
     186        7113 : }
     187             : 
     188        7113 : std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function)
     189             : {
     190        7113 :     const std::vector<CNetAddr> addresses{LookupHost(name, 1, fAllowLookup, dns_lookup_function)};
     191        7113 :     return addresses.empty() ? std::nullopt : std::make_optional(addresses.front());
     192        7113 : }
     193             : 
     194        6858 : std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
     195             : {
     196        6858 :     if (name.empty() || !ContainsNoNUL(name)) {
     197          36 :         return {};
     198             :     }
     199        6822 :     uint16_t port{portDefault};
     200        6822 :     std::string hostname;
     201        6822 :     SplitHostPort(name, port, hostname);
     202             : 
     203        6822 :     const std::vector<CNetAddr> addresses{LookupIntern(hostname, nMaxSolutions, fAllowLookup, dns_lookup_function)};
     204        6822 :     if (addresses.empty()) return {};
     205        6817 :     std::vector<CService> services;
     206        6817 :     services.reserve(addresses.size());
     207       13644 :     for (const auto& addr : addresses)
     208        6827 :         services.emplace_back(addr, port);
     209        6817 :     return services;
     210       13675 : }
     211             : 
     212        6848 : std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function)
     213             : {
     214        6848 :     const std::vector<CService> services{Lookup(name, portDefault, fAllowLookup, 1, dns_lookup_function)};
     215             : 
     216        6848 :     return services.empty() ? std::nullopt : std::make_optional(services.front());
     217        6848 : }
     218             : 
     219          50 : CService LookupNumeric(const std::string& name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
     220             : {
     221          50 :     if (!ContainsNoNUL(name)) {
     222           0 :         return {};
     223             :     }
     224             :     // "1.2:345" will fail to resolve the ip, but will still set the port.
     225             :     // If the ip fails to resolve, re-init the result.
     226          50 :     return Lookup(name, portDefault, /*fAllowLookup=*/false, dns_lookup_function).value_or(CService{});
     227          50 : }
     228             : 
     229           0 : bool IsUnixSocketPath(const std::string& name)
     230             : {
     231             : #if HAVE_SOCKADDR_UN
     232           0 :     if (name.find(ADDR_PREFIX_UNIX) != 0) return false;
     233             : 
     234             :     // Split off "unix:" prefix
     235           0 :     std::string str{name.substr(ADDR_PREFIX_UNIX.length())};
     236             : 
     237             :     // Path size limit is platform-dependent
     238             :     // see https://manpages.ubuntu.com/manpages/xenial/en/man7/unix.7.html
     239           0 :     if (str.size() + 1 > sizeof(((sockaddr_un*)nullptr)->sun_path)) return false;
     240             : 
     241           0 :     return true;
     242             : #else
     243             :     return false;
     244             : #endif
     245           0 : }
     246             : 
     247             : /** SOCKS version */
     248             : enum SOCKSVersion: uint8_t {
     249             :     SOCKS4 = 0x04,
     250             :     SOCKS5 = 0x05
     251             : };
     252             : 
     253             : /** Values defined for METHOD in RFC1928 */
     254             : enum SOCKS5Method: uint8_t {
     255             :     NOAUTH = 0x00,        //!< No authentication required
     256             :     GSSAPI = 0x01,        //!< GSSAPI
     257             :     USER_PASS = 0x02,     //!< Username/password
     258             :     NO_ACCEPTABLE = 0xff, //!< No acceptable methods
     259             : };
     260             : 
     261             : /** Values defined for CMD in RFC1928 */
     262             : enum SOCKS5Command: uint8_t {
     263             :     CONNECT = 0x01,
     264             :     BIND = 0x02,
     265             :     UDP_ASSOCIATE = 0x03
     266             : };
     267             : 
     268             : /** Values defined for REP in RFC1928 */
     269             : enum SOCKS5Reply: uint8_t {
     270             :     SUCCEEDED = 0x00,        //!< Succeeded
     271             :     GENFAILURE = 0x01,       //!< General failure
     272             :     NOTALLOWED = 0x02,       //!< Connection not allowed by ruleset
     273             :     NETUNREACHABLE = 0x03,   //!< Network unreachable
     274             :     HOSTUNREACHABLE = 0x04,  //!< Network unreachable
     275             :     CONNREFUSED = 0x05,      //!< Connection refused
     276             :     TTLEXPIRED = 0x06,       //!< TTL expired
     277             :     CMDUNSUPPORTED = 0x07,   //!< Command not supported
     278             :     ATYPEUNSUPPORTED = 0x08, //!< Address type not supported
     279             : };
     280             : 
     281             : /** Values defined for ATYPE in RFC1928 */
     282             : enum SOCKS5Atyp: uint8_t {
     283             :     IPV4 = 0x01,
     284             :     DOMAINNAME = 0x03,
     285             :     IPV6 = 0x04,
     286             : };
     287             : 
     288             : /** Status codes that can be returned by InterruptibleRecv */
     289             : enum class IntrRecvError {
     290             :     OK,
     291             :     Timeout,
     292             :     Disconnected,
     293             :     NetworkError,
     294             :     Interrupted
     295             : };
     296             : 
     297             : /**
     298             :  * Try to read a specified number of bytes from a socket. Please read the "see
     299             :  * also" section for more detail.
     300             :  *
     301             :  * @param data The buffer where the read bytes should be stored.
     302             :  * @param len The number of bytes to read into the specified buffer.
     303             :  * @param timeout The total timeout for this read.
     304             :  * @param sock The socket (has to be in non-blocking mode) from which to read bytes.
     305             :  *
     306             :  * @returns An IntrRecvError indicating the resulting status of this read.
     307             :  *          IntrRecvError::OK only if all of the specified number of bytes were
     308             :  *          read.
     309             :  *
     310             :  * @see This function can be interrupted by calling InterruptSocks5(bool).
     311             :  *      Sockets can be made non-blocking with Sock::SetNonBlocking().
     312             :  */
     313           0 : static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, std::chrono::milliseconds timeout, const Sock& sock)
     314             : {
     315           0 :     auto curTime{Now<SteadyMilliseconds>()};
     316           0 :     const auto endTime{curTime + timeout};
     317           0 :     while (len > 0 && curTime < endTime) {
     318           0 :         ssize_t ret = sock.Recv(data, len, 0); // Optimistically try the recv first
     319           0 :         if (ret > 0) {
     320           0 :             len -= ret;
     321           0 :             data += ret;
     322           0 :         } else if (ret == 0) { // Unexpected disconnection
     323           0 :             return IntrRecvError::Disconnected;
     324             :         } else { // Other error or blocking
     325           0 :             int nErr = WSAGetLastError();
     326           0 :             if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
     327             :                 // Only wait at most MAX_WAIT_FOR_IO at a time, unless
     328             :                 // we're approaching the end of the specified total timeout
     329           0 :                 const auto remaining = std::chrono::milliseconds{endTime - curTime};
     330           0 :                 const auto timeout = std::min(remaining, std::chrono::milliseconds{MAX_WAIT_FOR_IO});
     331           0 :                 if (!sock.Wait(timeout, Sock::RECV, SocketEventsParams{::g_socket_events_mode})) {
     332           0 :                     return IntrRecvError::NetworkError;
     333             :                 }
     334           0 :             } else {
     335           0 :                 return IntrRecvError::NetworkError;
     336             :             }
     337             :         }
     338           0 :         if (interruptSocks5Recv)
     339           0 :             return IntrRecvError::Interrupted;
     340           0 :         curTime = Now<SteadyMilliseconds>();
     341             :     }
     342           0 :     return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout;
     343           0 : }
     344             : 
     345             : /** Convert SOCKS5 reply to an error message */
     346           0 : static std::string Socks5ErrorString(uint8_t err)
     347             : {
     348           0 :     switch(err) {
     349             :         case SOCKS5Reply::GENFAILURE:
     350           0 :             return "general failure";
     351             :         case SOCKS5Reply::NOTALLOWED:
     352           0 :             return "connection not allowed";
     353             :         case SOCKS5Reply::NETUNREACHABLE:
     354           0 :             return "network unreachable";
     355             :         case SOCKS5Reply::HOSTUNREACHABLE:
     356           0 :             return "host unreachable";
     357             :         case SOCKS5Reply::CONNREFUSED:
     358           0 :             return "connection refused";
     359             :         case SOCKS5Reply::TTLEXPIRED:
     360           0 :             return "TTL expired";
     361             :         case SOCKS5Reply::CMDUNSUPPORTED:
     362           0 :             return "protocol error";
     363             :         case SOCKS5Reply::ATYPEUNSUPPORTED:
     364           0 :             return "address type not supported";
     365             :         default:
     366           0 :             return "unknown";
     367             :     }
     368           0 : }
     369             : 
     370           0 : bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& sock)
     371             : {
     372             :     IntrRecvError recvr;
     373           0 :     LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest);
     374           0 :     if (strDest.size() > 255) {
     375           0 :         return error("Hostname too long");
     376             :     }
     377             :     // Construct the version identifier/method selection message
     378           0 :     std::vector<uint8_t> vSocks5Init;
     379           0 :     vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol
     380           0 :     if (auth) {
     381           0 :         vSocks5Init.push_back(0x02); // 2 method identifiers follow...
     382           0 :         vSocks5Init.push_back(SOCKS5Method::NOAUTH);
     383           0 :         vSocks5Init.push_back(SOCKS5Method::USER_PASS);
     384           0 :     } else {
     385           0 :         vSocks5Init.push_back(0x01); // 1 method identifier follows...
     386           0 :         vSocks5Init.push_back(SOCKS5Method::NOAUTH);
     387             :     }
     388           0 :     ssize_t ret = sock.Send(vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
     389           0 :     if (ret != (ssize_t)vSocks5Init.size()) {
     390           0 :         return error("Error sending to proxy");
     391             :     }
     392             :     uint8_t pchRet1[2];
     393           0 :     if (InterruptibleRecv(pchRet1, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
     394           0 :         LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port);
     395           0 :         return false;
     396             :     }
     397           0 :     if (pchRet1[0] != SOCKSVersion::SOCKS5) {
     398           0 :         return error("Proxy failed to initialize");
     399             :     }
     400           0 :     if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) {
     401             :         // Perform username/password authentication (as described in RFC1929)
     402           0 :         std::vector<uint8_t> vAuth;
     403           0 :         vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation
     404           0 :         if (auth->username.size() > 255 || auth->password.size() > 255)
     405           0 :             return error("Proxy username or password too long");
     406           0 :         vAuth.push_back(auth->username.size());
     407           0 :         vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
     408           0 :         vAuth.push_back(auth->password.size());
     409           0 :         vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
     410           0 :         ret = sock.Send(vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
     411           0 :         if (ret != (ssize_t)vAuth.size()) {
     412           0 :             return error("Error sending authentication to proxy");
     413             :         }
     414           0 :         LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
     415             :         uint8_t pchRetA[2];
     416           0 :         if (InterruptibleRecv(pchRetA, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
     417           0 :             return error("Error reading proxy authentication response");
     418             :         }
     419           0 :         if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
     420           0 :             return error("Proxy authentication unsuccessful");
     421             :         }
     422           0 :     } else if (pchRet1[1] == SOCKS5Method::NOAUTH) {
     423             :         // Perform no authentication
     424           0 :     } else {
     425           0 :         return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
     426             :     }
     427           0 :     std::vector<uint8_t> vSocks5;
     428           0 :     vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version
     429           0 :     vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT
     430           0 :     vSocks5.push_back(0x00); // RSV Reserved must be 0
     431           0 :     vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME
     432           0 :     vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
     433           0 :     vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
     434           0 :     vSocks5.push_back((port >> 8) & 0xFF);
     435           0 :     vSocks5.push_back((port >> 0) & 0xFF);
     436           0 :     ret = sock.Send(vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
     437           0 :     if (ret != (ssize_t)vSocks5.size()) {
     438           0 :         return error("Error sending to proxy");
     439             :     }
     440             :     uint8_t pchRet2[4];
     441           0 :     if ((recvr = InterruptibleRecv(pchRet2, 4, g_socks5_recv_timeout, sock)) != IntrRecvError::OK) {
     442           0 :         if (recvr == IntrRecvError::Timeout) {
     443             :             /* If a timeout happens here, this effectively means we timed out while connecting
     444             :              * to the remote node. This is very common for Tor, so do not print an
     445             :              * error message. */
     446           0 :             return false;
     447             :         } else {
     448           0 :             return error("Error while reading proxy response");
     449             :         }
     450             :     }
     451           0 :     if (pchRet2[0] != SOCKSVersion::SOCKS5) {
     452           0 :         return error("Proxy failed to accept request");
     453             :     }
     454           0 :     if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) {
     455             :         // Failures to connect to a peer that are not proxy errors
     456           0 :         LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1]));
     457           0 :         return false;
     458             :     }
     459           0 :     if (pchRet2[2] != 0x00) { // Reserved field must be 0
     460           0 :         return error("Error: malformed proxy response");
     461             :     }
     462             :     uint8_t pchRet3[256];
     463           0 :     switch (pchRet2[3])
     464             :     {
     465           0 :         case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, g_socks5_recv_timeout, sock); break;
     466           0 :         case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, g_socks5_recv_timeout, sock); break;
     467             :         case SOCKS5Atyp::DOMAINNAME:
     468             :         {
     469           0 :             recvr = InterruptibleRecv(pchRet3, 1, g_socks5_recv_timeout, sock);
     470           0 :             if (recvr != IntrRecvError::OK) {
     471           0 :                 return error("Error reading from proxy");
     472             :             }
     473           0 :             int nRecv = pchRet3[0];
     474           0 :             recvr = InterruptibleRecv(pchRet3, nRecv, g_socks5_recv_timeout, sock);
     475           0 :             break;
     476             :         }
     477           0 :         default: return error("Error: malformed proxy response");
     478             :     }
     479           0 :     if (recvr != IntrRecvError::OK) {
     480           0 :         return error("Error reading from proxy");
     481             :     }
     482           0 :     if (InterruptibleRecv(pchRet3, 2, g_socks5_recv_timeout, sock) != IntrRecvError::OK) {
     483           0 :         return error("Error reading from proxy");
     484             :     }
     485           0 :     LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest);
     486           0 :     return true;
     487           0 : }
     488             : 
     489           0 : std::unique_ptr<Sock> CreateSockOS(sa_family_t address_family)
     490             : {
     491             :     // Not IPv4, IPv6 or UNIX
     492           0 :     if (address_family == AF_UNSPEC) return nullptr;
     493             : 
     494           0 :     int protocol{IPPROTO_TCP};
     495             : #if HAVE_SOCKADDR_UN
     496           0 :     if (address_family == AF_UNIX) protocol = 0;
     497             : #endif
     498             : 
     499             :     // Create a socket in the specified address family.
     500           0 :     SOCKET hSocket = socket(address_family, SOCK_STREAM, protocol);
     501           0 :     if (hSocket == INVALID_SOCKET) {
     502           0 :         return nullptr;
     503             :     }
     504             : 
     505           0 :     auto sock = std::make_unique<Sock>(hSocket);
     506             : 
     507             :     // Ensure that waiting for I/O on this socket won't result in undefined
     508             :     // behavior.
     509           0 :     if (!sock->IsSelectable(/*is_select=*/::g_socket_events_mode == SocketEventsMode::Select)) {
     510           0 :         LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
     511           0 :         return nullptr;
     512             :     }
     513             : 
     514             : #ifdef SO_NOSIGPIPE
     515           0 :     int set = 1;
     516             :     // Set the no-sigpipe option on the socket for BSD systems, other UNIXes
     517             :     // should use the MSG_NOSIGNAL flag for every send.
     518           0 :     if (sock->SetSockOpt(SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)) == SOCKET_ERROR) {
     519           0 :         LogPrintf("Error setting SO_NOSIGPIPE on socket: %s, continuing anyway\n",
     520             :                   NetworkErrorString(WSAGetLastError()));
     521           0 :     }
     522             : #endif
     523             : 
     524             :     // Set the non-blocking option on the socket.
     525           0 :     if (!sock->SetNonBlocking()) {
     526           0 :         LogPrintf("Error setting socket to non-blocking: %s\n", NetworkErrorString(WSAGetLastError()));
     527           0 :         return nullptr;
     528             :     }
     529             : 
     530             : #if HAVE_SOCKADDR_UN
     531           0 :     if (address_family == AF_UNIX) return sock;
     532             : #endif
     533             : 
     534             :     // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
     535           0 :     const int on{1};
     536           0 :     if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) == SOCKET_ERROR) {
     537           0 :         LogPrint(BCLog::NET, "Unable to set TCP_NODELAY on a newly created socket, continuing anyway\n");
     538           0 :     }
     539           0 :     return sock;
     540           0 : }
     541             : 
     542         218 : std::function<std::unique_ptr<Sock>(const sa_family_t&)> CreateSock = CreateSockOS;
     543             : 
     544             : template<typename... Args>
     545           0 : static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) {
     546           0 :     std::string error_message = tfm::format(fmt, args...);
     547           0 :     if (manual_connection) {
     548           0 :         LogPrintf("%s\n", error_message);
     549           0 :     } else {
     550           0 :         LogPrint(BCLog::NET, "%s\n", error_message);
     551             :     }
     552           0 : }
     553             : 
     554          16 : static bool ConnectToSocket(const Sock& sock, struct sockaddr* sockaddr, socklen_t len, const std::string& dest_str, bool manual_connection)
     555             : {
     556             :     // Connect to `sockaddr` using `sock`.
     557          16 :     if (sock.Connect(sockaddr, len) == SOCKET_ERROR) {
     558           0 :         int nErr = WSAGetLastError();
     559             :         // WSAEINVAL is here because some legacy version of winsock uses it
     560           0 :         if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
     561             :         {
     562             :             // Connection didn't actually fail, but is being established
     563             :             // asynchronously. Thus, use async I/O api (select/poll)
     564             :             // synchronously to check for successful connection with a timeout.
     565           0 :             const Sock::Event requested = Sock::RECV | Sock::SEND;
     566             :             Sock::Event occurred;
     567           0 :             if (!sock.Wait(std::chrono::milliseconds{nConnectTimeout}, requested, SocketEventsParams{::g_socket_events_mode}, &occurred)) {
     568           0 :                 LogPrintf("wait for connect to %s failed: %s\n",
     569             :                           dest_str,
     570             :                           NetworkErrorString(WSAGetLastError()));
     571           0 :                 return false;
     572           0 :             } else if (occurred == 0) {
     573           0 :                 LogPrint(BCLog::NET, "connection attempt to %s timed out\n", dest_str);
     574           0 :                 return false;
     575             :             }
     576             : 
     577             :             // Even if the wait was successful, the connect might not
     578             :             // have been successful. The reason for this failure is hidden away
     579             :             // in the SO_ERROR for the socket in modern systems. We read it into
     580             :             // sockerr here.
     581             :             int sockerr;
     582           0 :             socklen_t sockerr_len = sizeof(sockerr);
     583           0 :             if (sock.GetSockOpt(SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&sockerr, &sockerr_len) ==
     584             :                 SOCKET_ERROR) {
     585           0 :                 LogPrintf("getsockopt() for %s failed: %s\n", dest_str, NetworkErrorString(WSAGetLastError()));
     586           0 :                 return false;
     587             :             }
     588           0 :             if (sockerr != 0) {
     589           0 :                 LogConnectFailure(manual_connection,
     590             :                                   "connect() to %s failed after wait: %s",
     591           0 :                                   dest_str,
     592           0 :                                   NetworkErrorString(sockerr));
     593           0 :                 return false;
     594             :             }
     595           0 :         }
     596             : #ifdef WIN32
     597             :         else if (WSAGetLastError() != WSAEISCONN)
     598             : #else
     599             :         else
     600             : #endif
     601             :         {
     602           0 :             LogConnectFailure(manual_connection, "connect() to %s failed: %s", dest_str, NetworkErrorString(WSAGetLastError()));
     603           0 :             return false;
     604             :         }
     605           0 :     }
     606          16 :     return true;
     607          16 : }
     608             : 
     609          16 : std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection)
     610             : {
     611          16 :     auto sock = CreateSock(dest.GetSAFamily());
     612          16 :     if (!sock) {
     613           0 :         LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Cannot create a socket for connecting to %s\n", dest.ToStringAddrPort());
     614           0 :         return {};
     615             :     }
     616             : 
     617             :     // Create a sockaddr from the specified service.
     618             :     struct sockaddr_storage sockaddr;
     619          16 :     socklen_t len = sizeof(sockaddr);
     620          16 :     if (!dest.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
     621           0 :         LogPrintf("Cannot get sockaddr for %s: unsupported network\n", dest.ToStringAddrPort());
     622           0 :         return {};
     623             :     }
     624             : 
     625          16 :     if (!ConnectToSocket(*sock, (struct sockaddr*)&sockaddr, len, dest.ToStringAddrPort(), manual_connection)) {
     626           0 :         return {};
     627             :     }
     628             : 
     629          16 :     return sock;
     630          16 : }
     631             : 
     632          16 : std::unique_ptr<Sock> Proxy::Connect() const
     633             : {
     634          16 :     if (!IsValid()) return {};
     635             : 
     636          16 :     if (!m_is_unix_socket) return ConnectDirectly(proxy, /*manual_connection=*/true);
     637             : 
     638             : #if HAVE_SOCKADDR_UN
     639           0 :     auto sock = CreateSock(AF_UNIX);
     640           0 :     if (!sock) {
     641           0 :         LogPrintLevel(BCLog::NET, BCLog::Level::Error, "Cannot create a socket for connecting to %s\n", m_unix_socket_path);
     642           0 :         return {};
     643             :     }
     644             : 
     645           0 :     const std::string path{m_unix_socket_path.substr(ADDR_PREFIX_UNIX.length())};
     646             : 
     647             :     struct sockaddr_un addrun;
     648           0 :     memset(&addrun, 0, sizeof(addrun));
     649           0 :     addrun.sun_family = AF_UNIX;
     650             :     // leave the last char in addrun.sun_path[] to be always '\0'
     651           0 :     memcpy(addrun.sun_path, path.c_str(), std::min(sizeof(addrun.sun_path) - 1, path.length()));
     652           0 :     socklen_t len = sizeof(addrun);
     653             : 
     654           0 :     if(!ConnectToSocket(*sock, (struct sockaddr*)&addrun, len, path, /*manual_connection=*/true)) {
     655           0 :         return {};
     656             :     }
     657             : 
     658           0 :     return sock;
     659             : #else
     660             :     return {};
     661             : #endif
     662          16 : }
     663             : 
     664           0 : bool SetProxy(enum Network net, const Proxy &addrProxy) {
     665           0 :     assert(net >= 0 && net < NET_MAX);
     666           0 :     if (!addrProxy.IsValid())
     667           0 :         return false;
     668           0 :     LOCK(g_proxyinfo_mutex);
     669           0 :     proxyInfo[net] = addrProxy;
     670           0 :     return true;
     671           0 : }
     672             : 
     673          15 : bool GetProxy(enum Network net, Proxy &proxyInfoOut) {
     674          15 :     assert(net >= 0 && net < NET_MAX);
     675          15 :     LOCK(g_proxyinfo_mutex);
     676          15 :     if (!proxyInfo[net].IsValid())
     677          15 :         return false;
     678           0 :     proxyInfoOut = proxyInfo[net];
     679           0 :     return true;
     680          15 : }
     681             : 
     682           0 : bool SetNameProxy(const Proxy &addrProxy) {
     683           0 :     if (!addrProxy.IsValid())
     684           0 :         return false;
     685           0 :     LOCK(g_proxyinfo_mutex);
     686           0 :     nameProxy = addrProxy;
     687           0 :     return true;
     688           0 : }
     689             : 
     690           0 : bool GetNameProxy(Proxy &nameProxyOut) {
     691           0 :     LOCK(g_proxyinfo_mutex);
     692           0 :     if(!nameProxy.IsValid())
     693           0 :         return false;
     694           0 :     nameProxyOut = nameProxy;
     695           0 :     return true;
     696           0 : }
     697             : 
     698          10 : bool HaveNameProxy() {
     699          10 :     LOCK(g_proxyinfo_mutex);
     700          10 :     return nameProxy.IsValid();
     701          10 : }
     702             : 
     703          20 : bool IsProxy(const CNetAddr &addr) {
     704          20 :     LOCK(g_proxyinfo_mutex);
     705         160 :     for (int i = 0; i < NET_MAX; i++) {
     706         140 :         if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
     707           0 :             return true;
     708         140 :     }
     709          20 :     return false;
     710          20 : }
     711             : 
     712           0 : std::unique_ptr<Sock> ConnectThroughProxy(const Proxy& proxy,
     713             :                                           const std::string& dest,
     714             :                                           uint16_t port,
     715             :                                           bool& proxy_connection_failed)
     716             : {
     717             :     // first connect to proxy server
     718           0 :     auto sock = proxy.Connect();
     719           0 :     if (!sock) {
     720           0 :         proxy_connection_failed = true;
     721           0 :         return {};
     722             :     }
     723             : 
     724             :     // do socks negotiation
     725           0 :     if (proxy.m_randomize_credentials) {
     726           0 :         ProxyCredentials random_auth;
     727             :         static std::atomic_int counter(0);
     728           0 :         random_auth.username = random_auth.password = strprintf("%i", counter++);
     729           0 :         if (!Socks5(dest, port, &random_auth, *sock)) {
     730           0 :             return {};
     731             :         }
     732           0 :     } else {
     733           0 :         if (!Socks5(dest, port, nullptr, *sock)) {
     734           0 :             return {};
     735             :         }
     736             :     }
     737           0 :     return sock;
     738           0 : }
     739             : 
     740          97 : CSubNet LookupSubNet(const std::string& subnet_str)
     741             : {
     742          97 :     CSubNet subnet;
     743          97 :     assert(!subnet.IsValid());
     744          97 :     if (!ContainsNoNUL(subnet_str)) {
     745           6 :         return subnet;
     746             :     }
     747             : 
     748          91 :     const size_t slash_pos{subnet_str.find_last_of('/')};
     749          91 :     const std::string str_addr{subnet_str.substr(0, slash_pos)};
     750          91 :     std::optional<CNetAddr> addr{LookupHost(str_addr, /*fAllowLookup=*/false)};
     751             : 
     752          91 :     if (addr.has_value()) {
     753          85 :         addr = static_cast<CNetAddr>(MaybeFlipIPv6toCJDNS(CService{addr.value(), /*port=*/0}));
     754          85 :         if (slash_pos != subnet_str.npos) {
     755          78 :             const std::string netmask_str{subnet_str.substr(slash_pos + 1)};
     756             :             uint8_t netmask;
     757          78 :             if (ParseUInt8(netmask_str, &netmask)) {
     758             :                 // Valid number; assume CIDR variable-length subnet masking.
     759          32 :                 subnet = CSubNet{addr.value(), netmask};
     760          32 :             } else {
     761             :                 // Invalid number; try full netmask syntax. Never allow lookup for netmask.
     762          46 :                 const std::optional<CNetAddr> full_netmask{LookupHost(netmask_str, /*fAllowLookup=*/false)};
     763          46 :                 if (full_netmask.has_value()) {
     764          44 :                     subnet = CSubNet{addr.value(), full_netmask.value()};
     765          44 :                 }
     766          46 :             }
     767          78 :         } else {
     768             :             // Single IP subnet (<ipv4>/32 or <ipv6>/128).
     769           7 :             subnet = CSubNet{addr.value()};
     770             :         }
     771          85 :     }
     772             : 
     773          91 :     return subnet;
     774          97 : }
     775             : 
     776         631 : void InterruptSocks5(bool interrupt)
     777             : {
     778         631 :     interruptSocks5Recv = interrupt;
     779         631 : }
     780             : 
     781       70021 : bool IsBadPort(uint16_t port)
     782             : {
     783             :     /* Don't forget to update doc/p2p-bad-ports.md if you change this list. */
     784             : 
     785       70021 :     if (port > 0 && port <= PRIVILEGED_PORTS_THRESHOLD) return true;
     786       68987 :     switch (port) {
     787             :     case 1719:  // h323gatestat
     788             :     case 1720:  // h323hostcall
     789             :     case 1723:  // pptp
     790             :     case 2049:  // nfs
     791             :     case 3659:  // apple-sasl / PasswordServer
     792             :     case 4045:  // lockd
     793             :     case 5060:  // sip
     794             :     case 5061:  // sips
     795             :     case 6000:  // X11
     796             :     case 6566:  // sane-port
     797             :     case 6665:  // Alternate IRC
     798             :     case 6666:  // Alternate IRC
     799             :     case 6667:  // Standard IRC
     800             :     case 6668:  // Alternate IRC
     801             :     case 6669:  // Alternate IRC
     802             :     case 6697:  // IRC + TLS
     803             :     case 8332:  // Bitcoin RPC
     804             :     case 8333:  // Bitcoin P2P
     805             :     case 10080: // Amanda
     806             :     case 18332: // Bitcoin testnet RPC
     807             :     case 18333: // Bitcoin testnet RPC
     808          26 :         return true;
     809             :     }
     810       68961 :     return false;
     811       70021 : }
     812             : 
     813         158 : CService MaybeFlipIPv6toCJDNS(const CService& service)
     814             : {
     815         158 :     CService ret{service};
     816         158 :     if (ret.IsIPv6() && ret.HasCJDNSPrefix() && g_reachable_nets.Contains(NET_CJDNS)) {
     817           6 :         ret.m_net = NET_CJDNS;
     818           6 :     }
     819         158 :     return ret;
     820         158 : }

Generated by: LCOV version 1.16