Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
sock.h
Go to the documentation of this file.
1// Copyright (c) 2020-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_UTIL_SOCK_H
6#define BITCOIN_UTIL_SOCK_H
7
8#include <compat/compat.h>
9#include <util/time.h>
10
11#include <cstdint>
12#include <limits>
13#include <memory>
14#include <span>
15#include <string>
16#include <unordered_map>
17
19
24inline constexpr auto MAX_WAIT_FOR_IO = 1s;
25
26inline bool IOErrorIsPermanent(int err)
27{
28 return err != WSAEAGAIN && err != WSAEINTR && err != WSAEWOULDBLOCK && err != WSAEINPROGRESS;
29}
30
34class Sock
35{
36public:
37 Sock() = delete;
38
42 explicit Sock(SOCKET s);
43
47 Sock(const Sock&) = delete;
48
52 Sock(Sock&& other);
53
57 virtual ~Sock();
58
62 Sock& operator=(const Sock&) = delete;
63
67 virtual Sock& operator=(Sock&& other);
68
73 [[nodiscard]] virtual ssize_t Send(const void* data, size_t len, int flags) const;
74
79 [[nodiscard]] virtual ssize_t Recv(void* buf, size_t len, int flags) const;
80
85 [[nodiscard]] virtual int Connect(const sockaddr* addr, socklen_t addr_len) const;
86
91 [[nodiscard]] virtual int Bind(const sockaddr* addr, socklen_t addr_len) const;
92
97 [[nodiscard]] virtual int Listen(int backlog) const;
98
105 [[nodiscard]] virtual std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const;
106
112 [[nodiscard]] virtual int GetSockOpt(int level,
113 int opt_name,
114 void* opt_val,
115 socklen_t* opt_len) const;
116
122 [[nodiscard]] virtual int SetSockOpt(int level,
123 int opt_name,
124 const void* opt_val,
125 socklen_t opt_len) const;
126
132 [[nodiscard]] virtual int GetSockName(sockaddr* name, socklen_t* name_len) const;
133
138 [[nodiscard]] virtual bool SetNonBlocking() const;
139
144 [[nodiscard]] virtual bool IsSelectable() const;
145
146 using Event = uint8_t;
147
151 static constexpr Event RecvEvent = 0b001;
152
156 static constexpr Event SendEvent = 0b010;
157
162 static constexpr Event ErrorEvent = 0b100;
163
170 static constexpr std::chrono::seconds MAX_WAIT_TIMEOUT{std::numeric_limits<int>::max() / 1000};
171
183 [[nodiscard]] virtual bool Wait(std::chrono::milliseconds timeout,
184 Event requested,
185 Event* occurred = nullptr) const;
186
190 struct Events {
191 explicit Events(Event req) : requested{req} {}
194 };
195
197 size_t operator()(const std::shared_ptr<const Sock>& s) const
198 {
199 return s ? s->m_socket : std::numeric_limits<SOCKET>::max();
200 }
201 };
202
204 bool operator()(const std::shared_ptr<const Sock>& lhs,
205 const std::shared_ptr<const Sock>& rhs) const
206 {
207 if (lhs && rhs) {
208 return lhs->m_socket == rhs->m_socket;
209 }
210 if (!lhs && !rhs) {
211 return true;
212 }
213 return false;
214 }
215 };
216
225 using EventsPerSock = std::unordered_map<std::shared_ptr<const Sock>, Events, HashSharedPtrSock, EqualSharedPtrSock>;
226
236 [[nodiscard]] virtual bool WaitMany(std::chrono::milliseconds timeout,
237 EventsPerSock& events_per_sock) const;
238
239 /* Higher level, convenience, methods. These may throw. */
240
249 virtual void SendComplete(std::span<const unsigned char> data,
250 std::chrono::milliseconds timeout,
251 CThreadInterrupt& interrupt) const;
252
256 virtual void SendComplete(std::span<const char> data,
257 std::chrono::milliseconds timeout,
258 CThreadInterrupt& interrupt) const;
259
272 [[nodiscard]] virtual std::string RecvUntilTerminator(uint8_t terminator,
273 std::chrono::milliseconds timeout,
274 CThreadInterrupt& interrupt,
275 size_t max_data) const;
276
282 [[nodiscard]] virtual bool IsConnected(std::string& errmsg) const;
283
287 bool operator==(SOCKET s) const;
288
289protected:
294
295private:
299 void Close();
300};
301
303std::string NetworkErrorString(int err);
304
305#endif // BITCOIN_UTIL_SOCK_H
int flags
A helper class for interruptible sleeps.
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition sock.h:35
static constexpr Event RecvEvent
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition sock.h:151
virtual std::unique_ptr< Sock > Accept(sockaddr *addr, socklen_t *addr_len) const
accept(2) wrapper.
Definition sock.cpp:72
virtual ssize_t Send(const void *data, size_t len, int flags) const
send(2) wrapper.
Definition sock.cpp:47
SOCKET m_socket
Contained socket.
Definition sock.h:293
Sock & operator=(const Sock &)=delete
Copy assignment operator, disabled because closing the same socket twice is undesirable.
virtual int Bind(const sockaddr *addr, socklen_t addr_len) const
bind(2) wrapper.
Definition sock.cpp:62
virtual bool Wait(std::chrono::milliseconds timeout, Event requested, Event *occurred=nullptr) const
Wait for readiness for input (recv) or output (send).
Definition sock.cpp:141
virtual ~Sock()
Destructor, close the socket or do nothing if empty.
Definition sock.cpp:37
virtual void SendComplete(std::span< const unsigned char > data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
Definition sock.cpp:253
uint8_t Event
Definition sock.h:146
Sock(const Sock &)=delete
Copy constructor, disabled because closing the same socket twice is undesirable.
static constexpr Event SendEvent
If passed to Wait(), then it will wait for readiness to send to the socket.
Definition sock.h:156
virtual int GetSockName(sockaddr *name, socklen_t *name_len) const
getsockname(2) wrapper.
Definition sock.cpp:108
void Close()
Close m_socket if it is not INVALID_SOCKET.
Definition sock.cpp:409
virtual bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock &events_per_sock) const
Same as Wait(), but wait on many sockets within the same timeout.
Definition sock.cpp:163
virtual bool IsConnected(std::string &errmsg) const
Check if still connected.
Definition sock.cpp:384
virtual int SetSockOpt(int level, int opt_name, const void *opt_val, socklen_t opt_len) const
setsockopt(2) wrapper.
Definition sock.cpp:103
static constexpr Event ErrorEvent
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
Definition sock.h:162
virtual int GetSockOpt(int level, int opt_name, void *opt_val, socklen_t *opt_len) const
getsockopt(2) wrapper.
Definition sock.cpp:98
virtual int Connect(const sockaddr *addr, socklen_t addr_len) const
connect(2) wrapper.
Definition sock.cpp:57
virtual ssize_t Recv(void *buf, size_t len, int flags) const
recv(2) wrapper.
Definition sock.cpp:52
Sock()=delete
virtual std::string RecvUntilTerminator(uint8_t terminator, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt, size_t max_data) const
Read from socket until a terminator character is encountered.
Definition sock.cpp:301
virtual int Listen(int backlog) const
listen(2) wrapper.
Definition sock.cpp:67
virtual bool SetNonBlocking() const
Set the non-blocking option on the socket.
Definition sock.cpp:113
std::unordered_map< std::shared_ptr< const Sock >, Events, HashSharedPtrSock, EqualSharedPtrSock > EventsPerSock
On which socket to wait for what events in WaitMany().
Definition sock.h:225
virtual bool IsSelectable() const
Check if the underlying socket can be used for select(2) (or the Wait() method).
Definition sock.cpp:132
bool operator==(SOCKET s) const
Check if the internal socket is equal to s.
Definition sock.cpp:425
static constexpr std::chrono::seconds MAX_WAIT_TIMEOUT
Maximum timeout supported by Wait() and WaitMany() (about 24.8 days).
Definition sock.h:170
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
#define WSAEWOULDBLOCK
Definition compat.h:61
unsigned int SOCKET
Definition compat.h:57
#define WSAEINPROGRESS
Definition compat.h:65
#define WSAEINTR
Definition compat.h:64
#define WSAEAGAIN
Definition compat.h:62
const char * name
Definition rest.cpp:71
constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition sock.h:24
bool IOErrorIsPermanent(int err)
Definition sock.h:26
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition sock.cpp:430
bool operator()(const std::shared_ptr< const Sock > &lhs, const std::shared_ptr< const Sock > &rhs) const
Definition sock.h:204
Auxiliary requested/occurred events to wait for in WaitMany().
Definition sock.h:190
Event requested
Definition sock.h:192
Events(Event req)
Definition sock.h:191
Event occurred
Definition sock.h:193
size_t operator()(const std::shared_ptr< const Sock > &s) const
Definition sock.h:197
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82