Socket.h 18 KB

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