aboutsummaryrefslogtreecommitdiff
path: root/src/netbase.h
diff options
context:
space:
mode:
authorVasil Dimov <vd@FreeBSD.org>2020-12-23 16:40:11 +0100
committerVasil Dimov <vd@FreeBSD.org>2021-02-10 13:30:08 +0100
commitba9d73268f9585d4b9254adcf54708f88222798b (patch)
tree7817023a5deab6c4bcb0de90b748e49dc026f1ab /src/netbase.h
parentdec9b5e850c6aad989e814aea5b630b36f55d580 (diff)
downloadbitcoin-ba9d73268f9585d4b9254adcf54708f88222798b.tar.xz
net: add RAII socket and use it instead of bare SOCKET
Introduce a class to manage the lifetime of a socket - when the object that contains the socket goes out of scope, the underlying socket will be closed. In addition, the new `Sock` class has a `Send()`, `Recv()` and `Wait()` methods that can be overridden by unit tests to mock the socket operations. The `Wait()` method also hides the `#ifdef USE_POLL poll() #else select() #endif` technique from higher level code.
Diffstat (limited to 'src/netbase.h')
-rw-r--r--src/netbase.h17
1 files changed, 16 insertions, 1 deletions
diff --git a/src/netbase.h b/src/netbase.h
index 38d33e475b..d906888235 100644
--- a/src/netbase.h
+++ b/src/netbase.h
@@ -12,7 +12,10 @@
#include <compat.h>
#include <netaddress.h>
#include <serialize.h>
+#include <util/sock.h>
+#include <functional>
+#include <memory>
#include <stdint.h>
#include <string>
#include <vector>
@@ -51,7 +54,19 @@ bool Lookup(const std::string& name, CService& addr, int portDefault, bool fAllo
bool Lookup(const std::string& name, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions);
CService LookupNumeric(const std::string& name, int portDefault = 0);
bool LookupSubNet(const std::string& strSubnet, CSubNet& subnet);
-SOCKET CreateSocket(const CService &addrConnect);
+
+/**
+ * Create a TCP socket in the given address family.
+ * @param[in] address_family The socket is created in the same address family as this address.
+ * @return pointer to the created Sock object or unique_ptr that owns nothing in case of failure
+ */
+std::unique_ptr<Sock> CreateSockTCP(const CService& address_family);
+
+/**
+ * Socket factory. Defaults to `CreateSockTCP()`, but can be overridden by unit tests.
+ */
+extern std::function<std::unique_ptr<Sock>(const CService&)> CreateSock;
+
bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET& hSocketRet, int nTimeout, bool manual_connection);
bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, const SOCKET& hSocketRet, int nTimeout, bool& outProxyConnectionFailed);
/** Disable or enable blocking-mode for a socket */