userver: userver/engine/io/socket.hpp Source File
Loading...
Searching...
No Matches
socket.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/io/socket.hpp
4/// @brief @copybrief engine::io::Socket
5
6#include <sys/socket.h>
7
8#include <cstddef>
9#include <optional>
10#include <span>
11
12#include <userver/engine/deadline.hpp>
13#include <userver/engine/io/common.hpp>
14#include <userver/engine/io/exception.hpp>
15#include <userver/engine/io/fd_control_holder.hpp>
16#include <userver/engine/io/sockaddr.hpp>
17
18struct iovec;
19
20USERVER_NAMESPACE_BEGIN
21
22namespace engine::ev {
23class ThreadControl;
24} // namespace engine::ev
25
26namespace engine::io {
27
28/// Socket type
29enum class SocketType {
30 kStream = SOCK_STREAM, ///< Stream socket (e.g. TCP)
31 kDgram = SOCK_DGRAM, ///< Datagram socket (e.g. UDP)
32
33 kTcp = kStream,
34 kUdp = kDgram,
35};
36
37/// @brief Socket representation.
38///
39/// It is not thread-safe to concurrently read from socket. It is not
40/// thread-safe to concurrently write to socket. However it is safe to
41/// concurrently read and write into socket:
42/// @snippet core/src/engine/io/socket_test.cpp send self concurrent
43class [[nodiscard]] Socket final : public RwBase {
44public:
46 size_t bytes_received{0};
47 Sockaddr src_addr;
48 };
49
50 /// Constructs an invalid socket.
51 Socket() = default;
52
53 /// Constructs a socket for the address domain of specified type.
55
56 /// @brief Adopts an existing socket for specified address domain.
57 /// @note File descriptor will be silently forced to nonblocking mode.
58 explicit Socket(int fd, AddrDomain domain = AddrDomain::kUnspecified);
59
60 /// Whether the socket is valid.
61 explicit operator bool() const { return IsValid(); }
62
63 /// Whether the socket is valid.
64 bool IsValid() const override;
65
66 /// @brief Connects the socket to a specified endpoint.
67 /// @note Sockaddr domain must match the socket's domain.
68 void Connect(const Sockaddr&, Deadline);
69
70 /// @brief Binds the socket to the specified endpoint.
71 /// @note Sockaddr domain must match the socket's domain.
72 void Bind(const Sockaddr&);
73
74 /// Starts listening for connections on a specified socket (must be bound).
75 void Listen(int backlog = SOMAXCONN);
76
77 /// Suspends current task until the socket has data available.
78 /// @returns false on timeout or on task cancellations; true otherwise.
79 [[nodiscard]] bool WaitReadable(Deadline) override;
80
81 /// Suspends current task until the socket can accept more data.
82 /// @returns false on timeout or on task cancellations; true otherwise.
83 [[nodiscard]] bool WaitWriteable(Deadline) override;
84
85 /// @brief Receives at least one byte from the socket.
86 /// @returns 0 if connection is closed on one side and no data could be
87 /// received any more, received bytes count otherwise.
88 [[nodiscard]] size_t RecvSome(void* buf, size_t len, Deadline deadline);
89
90 /// @brief Receives exactly len bytes from the socket.
91 /// @note Can return less than len if socket is closed by peer.
92 [[nodiscard]] size_t RecvAll(void* buf, size_t len, Deadline deadline);
93
94 /// @brief Receives up to len bytes from the stream
95 /// @returns
96 /// - nullopt on data absence
97 /// - optional{0} if socket is closed by peer.
98 /// - optional{data_bytes_available} otherwise,
99 /// 1 <= data_bytes_available <= len
100 /// @throws IoException if the socket is closed
101 /// @throws IoSystemError on a failed syscall, EINTR is retried transparently
102 [[nodiscard]] std::optional<size_t> RecvNoblock(void* buf, size_t len);
103
104 /// @brief Receives into a buffer list from the stream without waiting.
105 /// @returns
106 /// - nullopt on data absence
107 /// - optional{0} if socket is closed by peer, or if the buffers hold no space at all
108 /// - optional{data_bytes_available} otherwise
109 /// @note The iovec descriptors are not modified. The result counts bytes, not buffers, so
110 /// utils::IovIter and utils::Advance should be used to resume from it.
111 /// @warning At most IOV_MAX buffers are passed to the kernel per call, the rest are filled
112 /// by subsequent calls. Leading empty buffers are skipped and do not count towards that
113 /// limit.
114 /// @note An empty buffer list never reaches the kernel, so on a datagram socket it does not
115 /// consume a datagram.
116 /// @throws IoException if the socket is closed
117 /// @throws IoSystemError on a failed syscall, EINTR is retried transparently
118 [[nodiscard]] std::optional<std::size_t> RecvNoblock(std::span<const struct iovec> list);
119
120 /// @brief Sends up to len bytes to the socket without waiting.
121 /// @returns
122 /// - nullopt on backpressure
123 /// - optional{0} if len is 0
124 /// - optional{bytes_sent} otherwise, 1 <= bytes_sent <= len
125 /// @throws IoException if the socket is closed
126 /// @throws IoSystemError on a failed syscall, EINTR is retried transparently
127 [[nodiscard]] std::optional<std::size_t> SendNoblock(const void* buf, std::size_t len);
128
129 /// @brief Sends a buffer list to the socket without waiting.
130 /// @returns
131 /// - nullopt on backpressure
132 /// - optional{0} if the buffers hold no bytes at all
133 /// - optional{bytes_sent} otherwise
134 /// @note The iovec descriptors are not modified. The result counts bytes, not buffers, so
135 /// utils::IovIter and utils::Advance should be used to resume from it.
136 /// @warning At most IOV_MAX buffers are passed to the kernel per call, the rest have to be
137 /// sent by subsequent calls. Leading empty buffers are skipped and do not count towards
138 /// that limit.
139 /// @note An empty buffer list never reaches the kernel, so on a datagram socket it does not
140 /// send an empty datagram.
141 /// @throws IoException if the socket is closed
142 /// @throws IoSystemError on a failed syscall, EINTR is retried transparently
143 [[nodiscard]] std::optional<std::size_t> SendNoblock(std::span<const struct iovec> list);
144
145 /// @brief Sends a buffer vector to the socket.
146 /// @note Can return less than len if socket is closed by peer.
147 /// @snippet core/src/engine/io/socket_test.cpp send vector data in socket
148 [[nodiscard]] size_t SendAll(std::initializer_list<IoData> list, Deadline deadline);
149
150 [[nodiscard]] size_t SendAll(std::span<const IoData> list, Deadline deadline);
151
152 [[nodiscard]] size_t WriteAll(std::span<const IoData> list, Deadline deadline) override {
153 return SendAll(list, deadline);
154 }
155
156 /// @brief Sends exactly list_size IoData to the socket.
157 /// @note Can return less than len if socket is closed by peer.
158 [[nodiscard]] size_t SendAll(const IoData* list, std::size_t list_size, Deadline deadline);
159
160 /// @brief Sends exactly list_size iovec to the socket, has no IOV_MAX limits on list_size
161 /// @note Can return less than len if socket is closed by peer.
162 [[nodiscard]] size_t SendAll(const struct iovec* list, std::size_t list_size, Deadline deadline);
163
164 /// @brief Sends exactly len bytes to the socket.
165 /// @note Can return less than len if socket is closed by peer.
166 [[nodiscard]] size_t SendAll(const void* buf, size_t len, Deadline deadline);
167
168 /// @brief Accepts a connection from a listening socket.
169 /// @see engine::io::Listen
170 [[nodiscard]] Socket Accept(Deadline);
171
172 /// @brief Receives at least one byte from the socket, returning source
173 /// address.
174 /// @returns 0 in bytes_sent if connection is closed on one side and no data
175 /// could be received any more, received bytes count otherwise + source
176 /// address.
177 [[nodiscard]] RecvFromResult RecvSomeFrom(void* buf, size_t len, Deadline deadline);
178
179 /// @brief Sends exactly len bytes to the specified address via the socket.
180 /// @note Can return less than len in bytes_sent if socket is closed by peer.
181 /// @note Sockaddr domain must match the socket's domain.
182 /// @note Not for SocketType::kStream connections, see `man sendto`.
183 [[nodiscard]] size_t SendAllTo(const Sockaddr& dest_addr, const void* buf, size_t len, Deadline deadline);
184
185 /// File descriptor corresponding to this socket.
186 int Fd() const;
187
188 /// Address of a remote peer.
189 const Sockaddr& Getpeername();
190
191 /// Local socket address.
192 const Sockaddr& Getsockname();
193
194 /// Releases file descriptor and invalidates the socket.
195 [[nodiscard]] int Release() && noexcept;
196
197 /// @brief Closes and invalidates the socket.
198 /// @warning You should not call Close with pending I/O. This may work okay
199 /// sometimes but it's loosely predictable.
200 void Close();
201
202 /// Retrieves a socket option.
203 int GetOption(int layer, int optname) const;
204
205 /// Sets a socket option.
206 void SetOption(int layer, int optname, int optval);
207
208 /// Sets a socket option with non-trivial optval.
209 void SetOption(int layer, int optname, const void* optval, socklen_t optlen);
210
211 /// @brief Receives at least one byte from the socket.
212 /// @returns 0 if connection is closed on one side and no data could be
213 /// received any more, received bytes count otherwise.
214 [[nodiscard]] size_t ReadSome(void* buf, size_t len, Deadline deadline) override {
215 return RecvSome(buf, len, deadline);
216 }
217
218 /// @brief Receives exactly len bytes from the socket.
219 /// @note Can return less than len if socket is closed by peer.
220 [[nodiscard]] size_t ReadAll(void* buf, size_t len, Deadline deadline) override {
221 return RecvAll(buf, len, deadline);
222 }
223
224 /// @brief Receives up to len bytes from the stream
225 /// @returns
226 /// - nullopt on data absence
227 /// - optional{0} if socket is closed by peer.
228 /// - optional{data_bytes_available} otherwise,
229 /// 1 <= data_bytes_available <= len
230 [[nodiscard]] std::optional<size_t> ReadNoblock(void* buf, size_t len) override { return RecvNoblock(buf, len); }
231
232 /// @brief Writes exactly len bytes to the socket.
233 /// @note Can return less than len if socket is closed by peer.
234 [[nodiscard]] size_t WriteAll(const void* buf, size_t len, Deadline deadline) override {
235 return SendAll(buf, len, deadline);
236 }
237
238private:
240
241 impl::FdControlHolder fd_control_;
242 Sockaddr peername_;
243 Sockaddr sockname_;
244};
245
246} // namespace engine::io
247
248USERVER_NAMESPACE_END