LCOV - code coverage report
Current view: top level - src - netbase.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 29 382 7.6 %
Date: 2023-09-26 12:08:55 Functions: 8 31 25.8 %

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

Generated by: LCOV version 1.14