netbase.h raw

   1  // Copyright (c) 2009-present The Bitcoin Core developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #ifndef BITCOIN_NETBASE_H
   6  #define BITCOIN_NETBASE_H
   7  
   8  #include <compat/compat.h>
   9  #include <netaddress.h>
  10  #include <serialize.h>
  11  #include <util/sock.h>
  12  #include <util/threadinterrupt.h>
  13  
  14  #include <chrono>
  15  #include <cstdint>
  16  #include <functional>
  17  #include <memory>
  18  #include <optional>
  19  #include <string>
  20  #include <type_traits>
  21  #include <unordered_set>
  22  #include <vector>
  23  
  24  extern int nConnectTimeout;
  25  extern bool fNameLookup;
  26  
  27  //! -timeout default
  28  static const int DEFAULT_CONNECT_TIMEOUT = 5000;
  29  //! -dns default
  30  static const int DEFAULT_NAME_LOOKUP = true;
  31  
  32  /** Prefix for unix domain socket addresses (which are local filesystem paths) */
  33  const std::string ADDR_PREFIX_UNIX = "unix:";
  34  
  35  enum class ConnectionDirection {
  36      None = 0,
  37      In = (1U << 0),
  38      Out = (1U << 1),
  39      Both = (In | Out),
  40  };
  41  static inline ConnectionDirection& operator|=(ConnectionDirection& a, ConnectionDirection b) {
  42      using underlying = std::underlying_type_t<ConnectionDirection>;
  43      a = ConnectionDirection(underlying(a) | underlying(b));
  44      return a;
  45  }
  46  static inline bool operator&(ConnectionDirection a, ConnectionDirection b) {
  47      using underlying = std::underlying_type_t<ConnectionDirection>;
  48      return (underlying(a) & underlying(b));
  49  }
  50  
  51  /**
  52   * Check if a string is a valid UNIX domain socket path
  53   *
  54   * @param      name     The string provided by the user representing a local path
  55   *
  56   * @returns Whether the string has proper format, length, and points to an existing file path
  57   */
  58  bool IsUnixSocketPath(const std::string& name);
  59  
  60  class Proxy
  61  {
  62  public:
  63      Proxy() : m_is_unix_socket(false), m_tor_stream_isolation(false) {}
  64      explicit Proxy(const CService& _proxy, bool tor_stream_isolation = false) : proxy(_proxy), m_is_unix_socket(false), m_tor_stream_isolation(tor_stream_isolation) {}
  65      explicit Proxy(std::string path, bool tor_stream_isolation = false)
  66          : m_unix_socket_path(std::move(path)), m_is_unix_socket(true), m_tor_stream_isolation(tor_stream_isolation) {}
  67  
  68      CService proxy;
  69      std::string m_unix_socket_path;
  70      bool m_is_unix_socket;
  71      bool m_tor_stream_isolation;
  72  
  73      bool IsValid() const
  74      {
  75          if (m_is_unix_socket) return IsUnixSocketPath(m_unix_socket_path);
  76          return proxy.IsValid();
  77      }
  78  
  79      sa_family_t GetFamily() const
  80      {
  81          if (m_is_unix_socket) return AF_UNIX;
  82          return proxy.GetSAFamily();
  83      }
  84  
  85      std::string ToString() const
  86      {
  87          if (m_is_unix_socket) return m_unix_socket_path;
  88          return proxy.ToStringAddrPort();
  89      }
  90  
  91      std::unique_ptr<Sock> Connect() const;
  92  };
  93  
  94  /** Credentials for proxy authentication */
  95  struct ProxyCredentials
  96  {
  97      std::string username;
  98      std::string password;
  99  };
 100  
 101  /**
 102   * List of reachable networks. Everything is reachable by default.
 103   */
 104  class ReachableNets {
 105  public:
 106      void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 107      {
 108          AssertLockNotHeld(m_mutex);
 109          LOCK(m_mutex);
 110          m_reachable.insert(net);
 111      }
 112  
 113      void Remove(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 114      {
 115          AssertLockNotHeld(m_mutex);
 116          LOCK(m_mutex);
 117          m_reachable.erase(net);
 118      }
 119  
 120      void RemoveAll() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 121      {
 122          AssertLockNotHeld(m_mutex);
 123          LOCK(m_mutex);
 124          m_reachable.clear();
 125      }
 126  
 127      void Reset() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 128      {
 129          AssertLockNotHeld(m_mutex);
 130          LOCK(m_mutex);
 131          m_reachable = DefaultNets();
 132      }
 133  
 134      [[nodiscard]] bool Contains(Network net) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 135      {
 136          AssertLockNotHeld(m_mutex);
 137          LOCK(m_mutex);
 138          return m_reachable.contains(net);
 139      }
 140  
 141      [[nodiscard]] bool Contains(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 142      {
 143          AssertLockNotHeld(m_mutex);
 144          return Contains(addr.GetNetwork());
 145      }
 146  
 147      [[nodiscard]] std::unordered_set<Network> All() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
 148      {
 149          AssertLockNotHeld(m_mutex);
 150          LOCK(m_mutex);
 151          return m_reachable;
 152      }
 153  
 154  private:
 155      static std::unordered_set<Network> DefaultNets()
 156      {
 157          return {
 158              NET_UNROUTABLE,
 159              NET_IPV4,
 160              NET_IPV6,
 161              NET_ONION,
 162              NET_I2P,
 163              NET_CJDNS,
 164              NET_INTERNAL
 165          };
 166      };
 167  
 168      mutable Mutex m_mutex;
 169      std::unordered_set<Network> m_reachable GUARDED_BY(m_mutex){DefaultNets()};
 170  };
 171  
 172  extern ReachableNets g_reachable_nets;
 173  
 174  /**
 175   * Wrapper for getaddrinfo(3). Do not use directly: call Lookup/LookupHost/LookupNumeric/LookupSubNet.
 176   */
 177  std::vector<CNetAddr> WrappedGetAddrInfo(const std::string& name, bool allow_lookup);
 178  
 179  enum Network ParseNetwork(const std::string& net);
 180  std::string GetNetworkName(enum Network net);
 181  /** Return a vector of publicly routable Network names; optionally append NET_UNROUTABLE. */
 182  std::vector<std::string> GetNetworkNames(bool append_unroutable = false);
 183  bool SetProxy(enum Network net, const Proxy &addrProxy);
 184  std::optional<Proxy> GetProxy(enum Network net);
 185  bool IsProxy(const CNetAddr &addr);
 186  /**
 187   * Set the name proxy to use for all connections to nodes specified by a
 188   * hostname. After setting this proxy, connecting to a node specified by a
 189   * hostname won't result in a local lookup of said hostname, rather, connect to
 190   * the node by asking the name proxy for a proxy connection to the hostname,
 191   * effectively delegating the hostname lookup to the specified proxy.
 192   *
 193   * This delegation increases privacy for those who set the name proxy as they no
 194   * longer leak their external hostname queries to their DNS servers.
 195   *
 196   * @returns Whether or not the operation succeeded.
 197   *
 198   * @note SOCKS5's support for UDP-over-SOCKS5 has been considered, but no SOCK5
 199   *       server in common use (most notably Tor) actually implements UDP
 200   *       support, and a DNS resolver is beyond the scope of this project.
 201   */
 202  bool SetNameProxy(const Proxy &addrProxy);
 203  bool HaveNameProxy();
 204  std::optional<Proxy> GetNameProxy();
 205  
 206  using DNSLookupFn = std::function<std::vector<CNetAddr>(const std::string&, bool)>;
 207  extern DNSLookupFn g_dns_lookup;
 208  
 209  /**
 210   * Resolve a host string to its corresponding network addresses.
 211   *
 212   * @param name    The string representing a host. Could be a name or a numerical
 213   *                IP address (IPv6 addresses in their bracketed form are
 214   *                allowed).
 215   *
 216   * @returns The resulting network addresses to which the specified host
 217   *          string resolved.
 218   *
 219   * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
 220   *      for additional parameter descriptions.
 221   */
 222  std::vector<CNetAddr> LookupHost(const std::string& name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
 223  
 224  /**
 225   * Resolve a host string to its first corresponding network address.
 226   *
 227   * @returns The resulting network address to which the specified host
 228   *          string resolved or std::nullopt if host does not resolve to an address.
 229   *
 230   * @see LookupHost(const std::string&, unsigned int, bool, DNSLookupFn)
 231   *      for additional parameter descriptions.
 232   */
 233  std::optional<CNetAddr> LookupHost(const std::string& name, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
 234  
 235  /**
 236   * Resolve a service string to its corresponding service.
 237   *
 238   * @param name    The string representing a service. Could be a name or a
 239   *                numerical IP address (IPv6 addresses should be in their
 240   *                disambiguated bracketed form), optionally followed by a uint16_t port
 241   *                number. (e.g. example.com:8333 or
 242   *                [2001:db8:85a3:8d3:1319:8a2e:370:7348]:420)
 243   * @param portDefault The default port for resulting services if not specified
 244   *                    by the service string.
 245   * @param fAllowLookup Whether or not hostname lookups are permitted. If yes,
 246   *                     external queries may be performed.
 247   * @param nMaxSolutions The maximum number of results we want, specifying 0
 248   *                      means "as many solutions as we get."
 249   *
 250   * @returns The resulting services to which the specified service string
 251   *          resolved.
 252   */
 253  std::vector<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function = g_dns_lookup);
 254  
 255  /**
 256   * Resolve a service string to its first corresponding service.
 257   *
 258   * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
 259   *      for additional parameter descriptions.
 260   */
 261  std::optional<CService> Lookup(const std::string& name, uint16_t portDefault, bool fAllowLookup, DNSLookupFn dns_lookup_function = g_dns_lookup);
 262  
 263  /**
 264   * Resolve a service string with a numeric IP to its first corresponding
 265   * service.
 266   *
 267   * @returns The resulting CService if the resolution was successful, [::]:0 otherwise.
 268   *
 269   * @see Lookup(const std::string&, uint16_t, bool, unsigned int, DNSLookupFn)
 270   *      for additional parameter descriptions.
 271   */
 272  CService LookupNumeric(const std::string& name, uint16_t portDefault = 0, DNSLookupFn dns_lookup_function = g_dns_lookup);
 273  
 274  /**
 275   * Parse and resolve a specified subnet string into the appropriate internal
 276   * representation.
 277   *
 278   * @param[in]  subnet_str  A string representation of a subnet of the form
 279   *                         `network address [ "/", ( CIDR-style suffix | netmask ) ]`
 280   *                         e.g. "2001:db8::/32", "192.0.2.0/255.255.255.0" or "8.8.8.8".
 281   * @returns a CSubNet object (that may or may not be valid).
 282   */
 283  CSubNet LookupSubNet(const std::string& subnet_str);
 284  
 285  /**
 286   * Create a real socket from the operating system.
 287   * @param[in] domain Communications domain, first argument to the socket(2) syscall.
 288   * @param[in] type Type of the socket, second argument to the socket(2) syscall.
 289   * @param[in] protocol The particular protocol to be used with the socket, third argument to the socket(2) syscall.
 290   * @return pointer to the created Sock object or unique_ptr that owns nothing in case of failure
 291   */
 292  std::unique_ptr<Sock> CreateSockOS(int domain, int type, int protocol);
 293  
 294  /**
 295   * Socket factory. Defaults to `CreateSockOS()`, but can be overridden by unit tests.
 296   */
 297  extern std::function<std::unique_ptr<Sock>(int, int, int)> CreateSock;
 298  
 299  /**
 300   * Create a socket and try to connect to the specified service.
 301   *
 302   * @param[in] dest The service to which to connect.
 303   * @param[in] manual_connection Whether or not the connection was manually requested (e.g. through the addnode RPC)
 304   *
 305   * @returns the connected socket if the operation succeeded, empty unique_ptr otherwise
 306   */
 307  std::unique_ptr<Sock> ConnectDirectly(const CService& dest, bool manual_connection);
 308  
 309  /** Create a socket and try to connect to the specified service, using the provided timeout. */
 310  std::unique_ptr<Sock> ConnectDirectly(const CService& dest,
 311                                        bool manual_connection,
 312                                        std::chrono::milliseconds timeout);
 313  
 314  /**
 315   * Connect to a specified destination service through a SOCKS5 proxy by first
 316   * connecting to the SOCKS5 proxy.
 317   *
 318   * @param[in] proxy The SOCKS5 proxy.
 319   * @param[in] dest The destination service to which to connect.
 320   * @param[in] port The destination port.
 321   * @param[out] proxy_connection_failed Whether or not the connection to the SOCKS5 proxy failed.
 322   *
 323   * @returns the connected socket if the operation succeeded. Otherwise an empty unique_ptr.
 324   */
 325  std::unique_ptr<Sock> ConnectThroughProxy(const Proxy& proxy,
 326                                            const std::string& dest,
 327                                            uint16_t port,
 328                                            bool& proxy_connection_failed);
 329  
 330  /**
 331   * Interrupt SOCKS5 reads or writes.
 332   */
 333  extern CThreadInterrupt g_socks5_interrupt;
 334  
 335  /**
 336   * Connect to a specified destination service through an already connected
 337   * SOCKS5 proxy.
 338   *
 339   * @param strDest The destination fully-qualified domain name.
 340   * @param port The destination port.
 341   * @param auth The credentials with which to authenticate with the specified
 342   *             SOCKS5 proxy.
 343   * @param socket The SOCKS5 proxy socket.
 344   *
 345   * @returns Whether or not the operation succeeded.
 346   *
 347   * @note The specified SOCKS5 proxy socket must already be connected to the
 348   *       SOCKS5 proxy.
 349   *
 350   * @see <a href="https://www.ietf.org/rfc/rfc1928.txt">RFC1928: SOCKS Protocol
 351   *      Version 5</a>
 352   */
 353  bool Socks5(const std::string& strDest, uint16_t port, const ProxyCredentials* auth, const Sock& socket);
 354  
 355  /**
 356   * Determine if a port is "bad" from the perspective of attempting to connect
 357   * to a node on that port.
 358   * @see doc/p2p-bad-ports.md
 359   * @param[in] port Port to check.
 360   * @returns whether the port is bad
 361   */
 362  bool IsBadPort(uint16_t port);
 363  
 364  /**
 365   * If an IPv6 address belongs to the address range used by the CJDNS network and
 366   * the CJDNS network is reachable (-cjdnsreachable config is set), then change
 367   * the type from NET_IPV6 to NET_CJDNS.
 368   * @param[in] service Address to potentially convert.
 369   * @return a copy of `service` either unmodified or changed to CJDNS.
 370   */
 371  CService MaybeFlipIPv6toCJDNS(const CService& service);
 372  
 373  /** Get the bind address for a socket as CService. */
 374  CService GetBindAddress(const Sock& sock);
 375  
 376  #endif // BITCOIN_NETBASE_H
 377