Socket.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /*
  2. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/BufferedStream.h>
  9. #include <AK/Function.h>
  10. #include <AK/Stream.h>
  11. #include <AK/Time.h>
  12. #include <LibCore/Notifier.h>
  13. #include <LibCore/SocketAddress.h>
  14. namespace Core {
  15. /// The Socket class is the base class for all concrete BSD-style socket
  16. /// classes. Sockets are non-seekable streams which can be read byte-wise.
  17. class Socket : public Stream {
  18. public:
  19. enum class PreventSIGPIPE {
  20. No,
  21. Yes,
  22. };
  23. enum class SocketType {
  24. Stream,
  25. Datagram,
  26. };
  27. Socket(Socket&&) = default;
  28. Socket& operator=(Socket&&) = default;
  29. /// Checks how many bytes of data are currently available to read on the
  30. /// socket. For datagram-based socket, this is the size of the first
  31. /// datagram that can be read. Returns either the amount of bytes, or an
  32. /// errno in the case of failure.
  33. virtual ErrorOr<size_t> pending_bytes() const = 0;
  34. /// Returns whether there's any data that can be immediately read, or an
  35. /// errno on failure.
  36. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const = 0;
  37. // Sets the blocking mode of the socket. If blocking mode is disabled, reads
  38. // will fail with EAGAIN when there's no data available to read, and writes
  39. // will fail with EAGAIN when the data cannot be written without blocking
  40. // (due to the send buffer being full, for example).
  41. virtual ErrorOr<void> set_blocking(bool enabled) = 0;
  42. // Sets the close-on-exec mode of the socket. If close-on-exec mode is
  43. // enabled, then the socket will be automatically closed by the kernel when
  44. // an exec call happens.
  45. virtual ErrorOr<void> set_close_on_exec(bool enabled) = 0;
  46. /// Disables any listening mechanisms that this socket uses.
  47. /// Can be called with 'false' when `on_ready_to_read` notifications are no longer needed.
  48. /// Conversely, set_notifications_enabled(true) will re-enable notifications.
  49. virtual void set_notifications_enabled(bool) { }
  50. // FIXME: This will need to be updated when IPv6 socket arrives. Perhaps a
  51. // base class for all address types is appropriate.
  52. static ErrorOr<Variant<IPv4Address, IPv6Address>> resolve_host(ByteString const&, SocketType);
  53. Function<void()> on_ready_to_read;
  54. protected:
  55. enum class SocketDomain {
  56. Local,
  57. Inet,
  58. Inet6,
  59. };
  60. explicit Socket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  61. : m_prevent_sigpipe(prevent_sigpipe == PreventSIGPIPE::Yes)
  62. {
  63. }
  64. static ErrorOr<int> create_fd(SocketDomain, SocketType);
  65. static ErrorOr<void> connect_local(int fd, ByteString const& path);
  66. static ErrorOr<void> connect_inet(int fd, SocketAddress const&);
  67. int default_flags() const
  68. {
  69. int flags = 0;
  70. if (m_prevent_sigpipe)
  71. flags |= MSG_NOSIGNAL;
  72. return flags;
  73. }
  74. private:
  75. bool m_prevent_sigpipe { true };
  76. };
  77. /// A reusable socket maintains state about being connected in addition to
  78. /// normal Socket capabilities, and can be reconnected once disconnected.
  79. class ReusableSocket : public Socket {
  80. public:
  81. /// Returns whether the socket is currently connected.
  82. virtual bool is_connected() = 0;
  83. /// Reconnects the socket to the given host and port. Returns EALREADY if
  84. /// is_connected() is true.
  85. virtual ErrorOr<void> reconnect(ByteString const& host, u16 port) = 0;
  86. /// Connects the socket to the given socket address (IP address + port).
  87. /// Returns EALREADY is_connected() is true.
  88. virtual ErrorOr<void> reconnect(SocketAddress const&) = 0;
  89. };
  90. class PosixSocketHelper {
  91. AK_MAKE_NONCOPYABLE(PosixSocketHelper);
  92. public:
  93. template<typename T>
  94. PosixSocketHelper(Badge<T>)
  95. requires(IsBaseOf<Socket, T>)
  96. {
  97. }
  98. PosixSocketHelper(PosixSocketHelper&& other)
  99. {
  100. operator=(move(other));
  101. }
  102. PosixSocketHelper& operator=(PosixSocketHelper&& other)
  103. {
  104. m_fd = exchange(other.m_fd, -1);
  105. m_last_read_was_eof = exchange(other.m_last_read_was_eof, false);
  106. m_notifier = move(other.m_notifier);
  107. return *this;
  108. }
  109. int fd() const { return m_fd; }
  110. void set_fd(int fd) { m_fd = fd; }
  111. ErrorOr<Bytes> read(Bytes, int flags);
  112. ErrorOr<size_t> write(ReadonlyBytes, int flags);
  113. bool is_eof() const { return !is_open() || m_last_read_was_eof; }
  114. void did_reach_eof_on_read();
  115. bool is_open() const { return m_fd != -1; }
  116. void close();
  117. ErrorOr<size_t> pending_bytes() const;
  118. ErrorOr<bool> can_read_without_blocking(int timeout) const;
  119. ErrorOr<void> set_blocking(bool enabled);
  120. ErrorOr<void> set_close_on_exec(bool enabled);
  121. ErrorOr<void> set_receive_timeout(AK::Duration timeout);
  122. void setup_notifier();
  123. RefPtr<Core::Notifier> notifier() { return m_notifier; }
  124. private:
  125. int m_fd { -1 };
  126. bool m_last_read_was_eof { false };
  127. RefPtr<Core::Notifier> m_notifier;
  128. };
  129. class TCPSocket final : public Socket {
  130. public:
  131. static ErrorOr<NonnullOwnPtr<TCPSocket>> connect(ByteString const& host, u16 port);
  132. static ErrorOr<NonnullOwnPtr<TCPSocket>> connect(SocketAddress const& address);
  133. static ErrorOr<NonnullOwnPtr<TCPSocket>> adopt_fd(int fd);
  134. TCPSocket(TCPSocket&& other)
  135. : Socket(static_cast<Socket&&>(other))
  136. , m_helper(move(other.m_helper))
  137. {
  138. if (is_open())
  139. setup_notifier();
  140. }
  141. TCPSocket& operator=(TCPSocket&& other)
  142. {
  143. Socket::operator=(static_cast<Socket&&>(other));
  144. m_helper = move(other.m_helper);
  145. if (is_open())
  146. setup_notifier();
  147. return *this;
  148. }
  149. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_helper.read(buffer, default_flags()); }
  150. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.write(buffer, default_flags()); }
  151. virtual bool is_eof() const override { return m_helper.is_eof(); }
  152. virtual bool is_open() const override { return m_helper.is_open(); }
  153. virtual void close() override { m_helper.close(); }
  154. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  155. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  156. virtual void set_notifications_enabled(bool enabled) override
  157. {
  158. if (auto notifier = m_helper.notifier())
  159. notifier->set_enabled(enabled);
  160. }
  161. ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  162. ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  163. virtual ~TCPSocket() override { close(); }
  164. private:
  165. explicit TCPSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  166. : Socket(prevent_sigpipe)
  167. {
  168. }
  169. void setup_notifier()
  170. {
  171. VERIFY(is_open());
  172. m_helper.setup_notifier();
  173. m_helper.notifier()->on_activation = [this] {
  174. if (on_ready_to_read)
  175. on_ready_to_read();
  176. };
  177. }
  178. PosixSocketHelper m_helper { Badge<TCPSocket> {} };
  179. };
  180. class UDPSocket final : public Socket {
  181. public:
  182. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(ByteString const& host, u16 port, Optional<AK::Duration> timeout = {});
  183. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(SocketAddress const& address, Optional<AK::Duration> timeout = {});
  184. UDPSocket(UDPSocket&& other)
  185. : Socket(static_cast<Socket&&>(other))
  186. , m_helper(move(other.m_helper))
  187. {
  188. if (is_open())
  189. setup_notifier();
  190. }
  191. UDPSocket& operator=(UDPSocket&& other)
  192. {
  193. Socket::operator=(static_cast<Socket&&>(other));
  194. m_helper = move(other.m_helper);
  195. if (is_open())
  196. setup_notifier();
  197. return *this;
  198. }
  199. virtual ErrorOr<Bytes> read_some(Bytes buffer) override
  200. {
  201. auto pending_bytes = TRY(this->pending_bytes());
  202. if (pending_bytes > buffer.size()) {
  203. // With UDP datagrams, reading a datagram into a buffer that's
  204. // smaller than the datagram's size will cause the rest of the
  205. // datagram to be discarded. That's not very nice, so let's bail
  206. // early, telling the caller that he should allocate a bigger
  207. // buffer.
  208. return Error::from_errno(EMSGSIZE);
  209. }
  210. return m_helper.read(buffer, default_flags());
  211. }
  212. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.write(buffer, default_flags()); }
  213. virtual bool is_eof() const override { return m_helper.is_eof(); }
  214. virtual bool is_open() const override { return m_helper.is_open(); }
  215. virtual void close() override { m_helper.close(); }
  216. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  217. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  218. virtual void set_notifications_enabled(bool enabled) override
  219. {
  220. if (auto notifier = m_helper.notifier())
  221. notifier->set_enabled(enabled);
  222. }
  223. ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  224. ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  225. virtual ~UDPSocket() override { close(); }
  226. private:
  227. explicit UDPSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  228. : Socket(prevent_sigpipe)
  229. {
  230. }
  231. void setup_notifier()
  232. {
  233. VERIFY(is_open());
  234. m_helper.setup_notifier();
  235. m_helper.notifier()->on_activation = [this] {
  236. if (on_ready_to_read)
  237. on_ready_to_read();
  238. };
  239. }
  240. PosixSocketHelper m_helper { Badge<UDPSocket> {} };
  241. };
  242. class LocalSocket final : public Socket {
  243. public:
  244. static ErrorOr<NonnullOwnPtr<LocalSocket>> connect(ByteString const& path, PreventSIGPIPE = PreventSIGPIPE::Yes);
  245. static ErrorOr<NonnullOwnPtr<LocalSocket>> adopt_fd(int fd, PreventSIGPIPE = PreventSIGPIPE::Yes);
  246. LocalSocket(LocalSocket&& other)
  247. : Socket(static_cast<Socket&&>(other))
  248. , m_helper(move(other.m_helper))
  249. {
  250. if (is_open())
  251. setup_notifier();
  252. }
  253. LocalSocket& operator=(LocalSocket&& other)
  254. {
  255. Socket::operator=(static_cast<Socket&&>(other));
  256. m_helper = move(other.m_helper);
  257. if (is_open())
  258. setup_notifier();
  259. return *this;
  260. }
  261. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_helper.read(buffer, default_flags()); }
  262. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.write(buffer, default_flags()); }
  263. virtual bool is_eof() const override { return m_helper.is_eof(); }
  264. virtual bool is_open() const override { return m_helper.is_open(); }
  265. virtual void close() override { m_helper.close(); }
  266. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  267. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  268. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  269. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  270. virtual void set_notifications_enabled(bool enabled) override
  271. {
  272. if (auto notifier = m_helper.notifier())
  273. notifier->set_enabled(enabled);
  274. }
  275. ErrorOr<int> receive_fd(int flags);
  276. ErrorOr<void> send_fd(int fd);
  277. ErrorOr<Bytes> receive_message(Bytes buffer, int flags, Vector<int>& fds);
  278. ErrorOr<ssize_t> send_message(ReadonlyBytes msg, int flags, Vector<int, 1> fds = {});
  279. ErrorOr<pid_t> peer_pid() const;
  280. ErrorOr<Bytes> read_without_waiting(Bytes buffer);
  281. /// Release the fd associated with this LocalSocket. After the fd is
  282. /// released, the socket will be considered "closed" and all operations done
  283. /// on it will fail with ENOTCONN. Fails with ENOTCONN if the socket is
  284. /// already closed.
  285. ErrorOr<int> release_fd();
  286. Optional<int> fd() const;
  287. RefPtr<Core::Notifier> notifier() { return m_helper.notifier(); }
  288. virtual ~LocalSocket() { close(); }
  289. private:
  290. explicit LocalSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  291. : Socket(prevent_sigpipe)
  292. {
  293. }
  294. void setup_notifier()
  295. {
  296. VERIFY(is_open());
  297. m_helper.setup_notifier();
  298. m_helper.notifier()->on_activation = [this] {
  299. if (on_ready_to_read)
  300. on_ready_to_read();
  301. };
  302. }
  303. PosixSocketHelper m_helper { Badge<LocalSocket> {} };
  304. };
  305. template<typename T>
  306. concept SocketLike = IsBaseOf<Socket, T>;
  307. class BufferedSocketBase : public Socket {
  308. public:
  309. virtual ErrorOr<StringView> read_line(Bytes buffer) = 0;
  310. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) = 0;
  311. virtual ErrorOr<bool> can_read_line() = 0;
  312. virtual ErrorOr<bool> can_read_up_to_delimiter(ReadonlyBytes delimiter) = 0;
  313. virtual size_t buffer_size() const = 0;
  314. };
  315. template<SocketLike T>
  316. class BufferedSocket final : public BufferedSocketBase {
  317. friend BufferedHelper<T>;
  318. public:
  319. static ErrorOr<NonnullOwnPtr<BufferedSocket<T>>> create(NonnullOwnPtr<T> stream, size_t buffer_size = 16384)
  320. {
  321. return BufferedHelper<T>::template create_buffered<BufferedSocket>(move(stream), buffer_size);
  322. }
  323. BufferedSocket(BufferedSocket&& other)
  324. : BufferedSocketBase(static_cast<BufferedSocketBase&&>(other))
  325. , m_helper(move(other.m_helper))
  326. {
  327. setup_notifier();
  328. }
  329. BufferedSocket& operator=(BufferedSocket&& other)
  330. {
  331. Socket::operator=(static_cast<Socket&&>(other));
  332. m_helper = move(other.m_helper);
  333. setup_notifier();
  334. return *this;
  335. }
  336. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_helper.read(move(buffer)); }
  337. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.stream().write_some(buffer); }
  338. virtual bool is_eof() const override { return m_helper.is_eof(); }
  339. virtual bool is_open() const override { return m_helper.stream().is_open(); }
  340. virtual void close() override { m_helper.stream().close(); }
  341. virtual ErrorOr<size_t> pending_bytes() const override
  342. {
  343. return TRY(m_helper.stream().pending_bytes()) + m_helper.buffered_data_size();
  344. }
  345. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.buffered_data_size() > 0 || TRY(m_helper.stream().can_read_without_blocking(timeout)); }
  346. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.stream().set_blocking(enabled); }
  347. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.stream().set_close_on_exec(enabled); }
  348. virtual void set_notifications_enabled(bool enabled) override { m_helper.stream().set_notifications_enabled(enabled); }
  349. virtual ErrorOr<StringView> read_line(Bytes buffer) override { return m_helper.read_line(move(buffer)); }
  350. virtual ErrorOr<bool> can_read_line() override
  351. {
  352. return TRY(m_helper.can_read_up_to_delimiter("\n"sv.bytes())) || m_helper.is_eof_with_data_left_over();
  353. }
  354. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) override { return m_helper.read_until(move(buffer), move(candidate)); }
  355. template<size_t N>
  356. ErrorOr<Bytes> read_until_any_of(Bytes buffer, Array<StringView, N> candidates) { return m_helper.read_until_any_of(move(buffer), move(candidates)); }
  357. virtual ErrorOr<bool> can_read_up_to_delimiter(ReadonlyBytes delimiter) override { return m_helper.can_read_up_to_delimiter(delimiter); }
  358. virtual size_t buffer_size() const override { return m_helper.buffer_size(); }
  359. virtual ~BufferedSocket() override = default;
  360. private:
  361. BufferedSocket(NonnullOwnPtr<T> stream, CircularBuffer buffer)
  362. : m_helper(Badge<BufferedSocket<T>> {}, move(stream), move(buffer))
  363. {
  364. setup_notifier();
  365. }
  366. void setup_notifier()
  367. {
  368. m_helper.stream().on_ready_to_read = [this] {
  369. if (on_ready_to_read)
  370. on_ready_to_read();
  371. };
  372. }
  373. BufferedHelper<T> m_helper;
  374. };
  375. using BufferedTCPSocket = BufferedSocket<TCPSocket>;
  376. using BufferedUDPSocket = BufferedSocket<UDPSocket>;
  377. using BufferedLocalSocket = BufferedSocket<LocalSocket>;
  378. /// A BasicReusableSocket allows one to use one of the base Core::Stream classes
  379. /// as a ReusableSocket. It does not preserve any connection state or options,
  380. /// and instead just recreates the stream when reconnecting.
  381. template<SocketLike T>
  382. class BasicReusableSocket final : public ReusableSocket {
  383. public:
  384. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(ByteString const& host, u16 port)
  385. {
  386. return make<BasicReusableSocket<T>>(TRY(T::connect(host, port)));
  387. }
  388. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(SocketAddress const& address)
  389. {
  390. return make<BasicReusableSocket<T>>(TRY(T::connect(address)));
  391. }
  392. virtual bool is_connected() override
  393. {
  394. return m_socket.is_open();
  395. }
  396. virtual ErrorOr<void> reconnect(ByteString const& host, u16 port) override
  397. {
  398. if (is_connected())
  399. return Error::from_errno(EALREADY);
  400. m_socket = TRY(T::connect(host, port));
  401. return {};
  402. }
  403. virtual ErrorOr<void> reconnect(SocketAddress const& address) override
  404. {
  405. if (is_connected())
  406. return Error::from_errno(EALREADY);
  407. m_socket = TRY(T::connect(address));
  408. return {};
  409. }
  410. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_socket.read(move(buffer)); }
  411. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_socket.write(buffer); }
  412. virtual bool is_eof() const override { return m_socket.is_eof(); }
  413. virtual bool is_open() const override { return m_socket.is_open(); }
  414. virtual void close() override { m_socket.close(); }
  415. virtual ErrorOr<size_t> pending_bytes() const override { return m_socket.pending_bytes(); }
  416. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_socket.can_read_without_blocking(timeout); }
  417. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_socket.set_blocking(enabled); }
  418. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_socket.set_close_on_exec(enabled); }
  419. private:
  420. BasicReusableSocket(NonnullOwnPtr<T> socket)
  421. : m_socket(move(socket))
  422. {
  423. }
  424. NonnullOwnPtr<T> m_socket;
  425. };
  426. using ReusableTCPSocket = BasicReusableSocket<TCPSocket>;
  427. using ReusableUDPSocket = BasicReusableSocket<UDPSocket>;
  428. }