Socket.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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(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. int fd() { return m_helper.fd(); }
  165. private:
  166. explicit TCPSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  167. : Socket(prevent_sigpipe)
  168. {
  169. }
  170. void setup_notifier()
  171. {
  172. VERIFY(is_open());
  173. m_helper.setup_notifier();
  174. m_helper.notifier()->on_activation = [this] {
  175. if (on_ready_to_read)
  176. on_ready_to_read();
  177. };
  178. }
  179. PosixSocketHelper m_helper { Badge<TCPSocket> {} };
  180. };
  181. class UDPSocket final : public Socket {
  182. public:
  183. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(ByteString const& host, u16 port, Optional<Duration> timeout = {});
  184. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(SocketAddress const& address, Optional<Duration> timeout = {});
  185. UDPSocket(UDPSocket&& other)
  186. : Socket(static_cast<Socket&&>(other))
  187. , m_helper(move(other.m_helper))
  188. {
  189. if (is_open())
  190. setup_notifier();
  191. }
  192. UDPSocket& operator=(UDPSocket&& other)
  193. {
  194. Socket::operator=(static_cast<Socket&&>(other));
  195. m_helper = move(other.m_helper);
  196. if (is_open())
  197. setup_notifier();
  198. return *this;
  199. }
  200. virtual ErrorOr<Bytes> read_some(Bytes buffer) override
  201. {
  202. auto pending_bytes = TRY(this->pending_bytes());
  203. if (pending_bytes > buffer.size()) {
  204. // With UDP datagrams, reading a datagram into a buffer that's
  205. // smaller than the datagram's size will cause the rest of the
  206. // datagram to be discarded. That's not very nice, so let's bail
  207. // early, telling the caller that he should allocate a bigger
  208. // buffer.
  209. return Error::from_errno(EMSGSIZE);
  210. }
  211. return m_helper.read(buffer, default_flags());
  212. }
  213. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.write(buffer, default_flags()); }
  214. virtual bool is_eof() const override { return m_helper.is_eof(); }
  215. virtual bool is_open() const override { return m_helper.is_open(); }
  216. virtual void close() override { m_helper.close(); }
  217. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  218. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  219. virtual void set_notifications_enabled(bool enabled) override
  220. {
  221. if (auto notifier = m_helper.notifier())
  222. notifier->set_enabled(enabled);
  223. }
  224. ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  225. ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  226. virtual ~UDPSocket() override { close(); }
  227. private:
  228. explicit UDPSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  229. : Socket(prevent_sigpipe)
  230. {
  231. }
  232. void setup_notifier()
  233. {
  234. VERIFY(is_open());
  235. m_helper.setup_notifier();
  236. m_helper.notifier()->on_activation = [this] {
  237. if (on_ready_to_read)
  238. on_ready_to_read();
  239. };
  240. }
  241. PosixSocketHelper m_helper { Badge<UDPSocket> {} };
  242. };
  243. class LocalSocket final : public Socket {
  244. public:
  245. static ErrorOr<NonnullOwnPtr<LocalSocket>> connect(ByteString const& path, PreventSIGPIPE = PreventSIGPIPE::Yes);
  246. static ErrorOr<NonnullOwnPtr<LocalSocket>> adopt_fd(int fd, PreventSIGPIPE = PreventSIGPIPE::Yes);
  247. LocalSocket(LocalSocket&& other)
  248. : Socket(static_cast<Socket&&>(other))
  249. , m_helper(move(other.m_helper))
  250. {
  251. if (is_open())
  252. setup_notifier();
  253. }
  254. LocalSocket& operator=(LocalSocket&& other)
  255. {
  256. Socket::operator=(static_cast<Socket&&>(other));
  257. m_helper = move(other.m_helper);
  258. if (is_open())
  259. setup_notifier();
  260. return *this;
  261. }
  262. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_helper.read(buffer, default_flags()); }
  263. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.write(buffer, default_flags()); }
  264. virtual bool is_eof() const override { return m_helper.is_eof(); }
  265. virtual bool is_open() const override { return m_helper.is_open(); }
  266. virtual void close() override { m_helper.close(); }
  267. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  268. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  269. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  270. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  271. virtual void set_notifications_enabled(bool enabled) override
  272. {
  273. if (auto notifier = m_helper.notifier())
  274. notifier->set_enabled(enabled);
  275. }
  276. ErrorOr<int> receive_fd(int flags);
  277. ErrorOr<void> send_fd(int fd);
  278. ErrorOr<Bytes> receive_message(Bytes buffer, int flags, Vector<int>& fds);
  279. ErrorOr<ssize_t> send_message(ReadonlyBytes msg, int flags, Vector<int, 1> fds = {});
  280. ErrorOr<pid_t> peer_pid() const;
  281. ErrorOr<Bytes> read_without_waiting(Bytes buffer);
  282. /// Release the fd associated with this LocalSocket. After the fd is
  283. /// released, the socket will be considered "closed" and all operations done
  284. /// on it will fail with ENOTCONN. Fails with ENOTCONN if the socket is
  285. /// already closed.
  286. ErrorOr<int> release_fd();
  287. Optional<int> fd() const;
  288. RefPtr<Core::Notifier> notifier() { return m_helper.notifier(); }
  289. virtual ~LocalSocket() { close(); }
  290. private:
  291. explicit LocalSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::Yes)
  292. : Socket(prevent_sigpipe)
  293. {
  294. }
  295. void setup_notifier()
  296. {
  297. VERIFY(is_open());
  298. m_helper.setup_notifier();
  299. m_helper.notifier()->on_activation = [this] {
  300. if (on_ready_to_read)
  301. on_ready_to_read();
  302. };
  303. }
  304. PosixSocketHelper m_helper { Badge<LocalSocket> {} };
  305. };
  306. template<typename T>
  307. concept SocketLike = IsBaseOf<Socket, T>;
  308. class BufferedSocketBase : public Socket {
  309. public:
  310. virtual ErrorOr<StringView> read_line(Bytes buffer) = 0;
  311. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) = 0;
  312. virtual ErrorOr<bool> can_read_line() = 0;
  313. virtual ErrorOr<bool> can_read_up_to_delimiter(ReadonlyBytes delimiter) = 0;
  314. virtual size_t buffer_size() const = 0;
  315. };
  316. template<SocketLike T>
  317. class BufferedSocket final : public BufferedSocketBase {
  318. friend BufferedHelper<T>;
  319. public:
  320. static ErrorOr<NonnullOwnPtr<BufferedSocket<T>>> create(NonnullOwnPtr<T> stream, size_t buffer_size = 16384)
  321. {
  322. return BufferedHelper<T>::template create_buffered<BufferedSocket>(move(stream), buffer_size);
  323. }
  324. BufferedSocket(BufferedSocket&& other)
  325. : BufferedSocketBase(static_cast<BufferedSocketBase&&>(other))
  326. , m_helper(move(other.m_helper))
  327. {
  328. setup_notifier();
  329. }
  330. BufferedSocket& operator=(BufferedSocket&& other)
  331. {
  332. Socket::operator=(static_cast<Socket&&>(other));
  333. m_helper = move(other.m_helper);
  334. setup_notifier();
  335. return *this;
  336. }
  337. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_helper.read(move(buffer)); }
  338. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.stream().write_some(buffer); }
  339. virtual bool is_eof() const override { return m_helper.is_eof(); }
  340. virtual bool is_open() const override { return m_helper.stream().is_open(); }
  341. virtual void close() override { m_helper.stream().close(); }
  342. virtual ErrorOr<size_t> pending_bytes() const override
  343. {
  344. return TRY(m_helper.stream().pending_bytes()) + m_helper.buffered_data_size();
  345. }
  346. 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)); }
  347. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.stream().set_blocking(enabled); }
  348. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.stream().set_close_on_exec(enabled); }
  349. virtual void set_notifications_enabled(bool enabled) override { m_helper.stream().set_notifications_enabled(enabled); }
  350. virtual ErrorOr<StringView> read_line(Bytes buffer) override { return m_helper.read_line(move(buffer)); }
  351. virtual ErrorOr<bool> can_read_line() override
  352. {
  353. return TRY(m_helper.can_read_up_to_delimiter("\n"sv.bytes())) || m_helper.is_eof_with_data_left_over();
  354. }
  355. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) override { return m_helper.read_until(move(buffer), move(candidate)); }
  356. template<size_t N>
  357. ErrorOr<Bytes> read_until_any_of(Bytes buffer, Array<StringView, N> candidates) { return m_helper.read_until_any_of(move(buffer), move(candidates)); }
  358. virtual ErrorOr<bool> can_read_up_to_delimiter(ReadonlyBytes delimiter) override { return m_helper.can_read_up_to_delimiter(delimiter); }
  359. virtual size_t buffer_size() const override { return m_helper.buffer_size(); }
  360. virtual ~BufferedSocket() override = default;
  361. private:
  362. BufferedSocket(NonnullOwnPtr<T> stream, CircularBuffer buffer)
  363. : m_helper(Badge<BufferedSocket<T>> {}, move(stream), move(buffer))
  364. {
  365. setup_notifier();
  366. }
  367. void setup_notifier()
  368. {
  369. m_helper.stream().on_ready_to_read = [this] {
  370. if (on_ready_to_read)
  371. on_ready_to_read();
  372. };
  373. }
  374. BufferedHelper<T> m_helper;
  375. };
  376. using BufferedTCPSocket = BufferedSocket<TCPSocket>;
  377. using BufferedUDPSocket = BufferedSocket<UDPSocket>;
  378. using BufferedLocalSocket = BufferedSocket<LocalSocket>;
  379. /// A BasicReusableSocket allows one to use one of the base Core::Stream classes
  380. /// as a ReusableSocket. It does not preserve any connection state or options,
  381. /// and instead just recreates the stream when reconnecting.
  382. template<SocketLike T>
  383. class BasicReusableSocket final : public ReusableSocket {
  384. public:
  385. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(ByteString const& host, u16 port)
  386. {
  387. return make<BasicReusableSocket<T>>(TRY(T::connect(host, port)));
  388. }
  389. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(SocketAddress const& address)
  390. {
  391. return make<BasicReusableSocket<T>>(TRY(T::connect(address)));
  392. }
  393. virtual bool is_connected() override
  394. {
  395. return m_socket.is_open();
  396. }
  397. virtual ErrorOr<void> reconnect(ByteString const& host, u16 port) override
  398. {
  399. if (is_connected())
  400. return Error::from_errno(EALREADY);
  401. m_socket = TRY(T::connect(host, port));
  402. return {};
  403. }
  404. virtual ErrorOr<void> reconnect(SocketAddress const& address) override
  405. {
  406. if (is_connected())
  407. return Error::from_errno(EALREADY);
  408. m_socket = TRY(T::connect(address));
  409. return {};
  410. }
  411. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_socket.read(move(buffer)); }
  412. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_socket.write(buffer); }
  413. virtual bool is_eof() const override { return m_socket.is_eof(); }
  414. virtual bool is_open() const override { return m_socket.is_open(); }
  415. virtual void close() override { m_socket.close(); }
  416. virtual ErrorOr<size_t> pending_bytes() const override { return m_socket.pending_bytes(); }
  417. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_socket.can_read_without_blocking(timeout); }
  418. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_socket.set_blocking(enabled); }
  419. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_socket.set_close_on_exec(enabled); }
  420. private:
  421. BasicReusableSocket(NonnullOwnPtr<T> socket)
  422. : m_socket(move(socket))
  423. {
  424. }
  425. NonnullOwnPtr<T> m_socket;
  426. };
  427. using ReusableTCPSocket = BasicReusableSocket<TCPSocket>;
  428. using ReusableUDPSocket = BasicReusableSocket<UDPSocket>;
  429. }