Socket.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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<IPv4Address> resolve_host(ByteString const&, SocketType);
  53. Function<void()> on_ready_to_read;
  54. protected:
  55. enum class SocketDomain {
  56. Local,
  57. Inet,
  58. };
  59. Socket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::No)
  60. : m_prevent_sigpipe(prevent_sigpipe == PreventSIGPIPE::Yes)
  61. {
  62. }
  63. static ErrorOr<int> create_fd(SocketDomain, SocketType);
  64. static ErrorOr<void> connect_local(int fd, ByteString 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(ByteString 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(Duration 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(ByteString 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_activation = [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(ByteString const& host, u16 port, Optional<Duration> timeout = {});
  181. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(SocketAddress const& address, Optional<Duration> 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_activation = [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(ByteString 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_activation = [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 ErrorOr<bool> can_read_up_to_delimiter(ReadonlyBytes delimiter) = 0;
  309. virtual size_t buffer_size() const = 0;
  310. };
  311. template<SocketLike T>
  312. class BufferedSocket final : public BufferedSocketBase {
  313. friend BufferedHelper<T>;
  314. public:
  315. static ErrorOr<NonnullOwnPtr<BufferedSocket<T>>> create(NonnullOwnPtr<T> stream, size_t buffer_size = 16384)
  316. {
  317. return BufferedHelper<T>::template create_buffered<BufferedSocket>(move(stream), buffer_size);
  318. }
  319. BufferedSocket(BufferedSocket&& other)
  320. : BufferedSocketBase(static_cast<BufferedSocketBase&&>(other))
  321. , m_helper(move(other.m_helper))
  322. {
  323. setup_notifier();
  324. }
  325. BufferedSocket& operator=(BufferedSocket&& other)
  326. {
  327. Socket::operator=(static_cast<Socket&&>(other));
  328. m_helper = move(other.m_helper);
  329. setup_notifier();
  330. return *this;
  331. }
  332. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_helper.read(move(buffer)); }
  333. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_helper.stream().write_some(buffer); }
  334. virtual bool is_eof() const override { return m_helper.is_eof(); }
  335. virtual bool is_open() const override { return m_helper.stream().is_open(); }
  336. virtual void close() override { m_helper.stream().close(); }
  337. virtual ErrorOr<size_t> pending_bytes() const override
  338. {
  339. return TRY(m_helper.stream().pending_bytes()) + m_helper.buffered_data_size();
  340. }
  341. 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)); }
  342. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.stream().set_blocking(enabled); }
  343. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.stream().set_close_on_exec(enabled); }
  344. virtual void set_notifications_enabled(bool enabled) override { m_helper.stream().set_notifications_enabled(enabled); }
  345. virtual ErrorOr<StringView> read_line(Bytes buffer) override { return m_helper.read_line(move(buffer)); }
  346. virtual ErrorOr<bool> can_read_line() override
  347. {
  348. return TRY(m_helper.can_read_up_to_delimiter("\n"sv.bytes())) || m_helper.is_eof_with_data_left_over();
  349. }
  350. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) override { return m_helper.read_until(move(buffer), move(candidate)); }
  351. template<size_t N>
  352. ErrorOr<Bytes> read_until_any_of(Bytes buffer, Array<StringView, N> candidates) { return m_helper.read_until_any_of(move(buffer), move(candidates)); }
  353. virtual ErrorOr<bool> can_read_up_to_delimiter(ReadonlyBytes delimiter) override { return m_helper.can_read_up_to_delimiter(delimiter); }
  354. virtual size_t buffer_size() const override { return m_helper.buffer_size(); }
  355. virtual ~BufferedSocket() override = default;
  356. private:
  357. BufferedSocket(NonnullOwnPtr<T> stream, CircularBuffer buffer)
  358. : m_helper(Badge<BufferedSocket<T>> {}, move(stream), move(buffer))
  359. {
  360. setup_notifier();
  361. }
  362. void setup_notifier()
  363. {
  364. m_helper.stream().on_ready_to_read = [this] {
  365. if (on_ready_to_read)
  366. on_ready_to_read();
  367. };
  368. }
  369. BufferedHelper<T> m_helper;
  370. };
  371. using BufferedTCPSocket = BufferedSocket<TCPSocket>;
  372. using BufferedUDPSocket = BufferedSocket<UDPSocket>;
  373. using BufferedLocalSocket = BufferedSocket<LocalSocket>;
  374. /// A BasicReusableSocket allows one to use one of the base Core::Stream classes
  375. /// as a ReusableSocket. It does not preserve any connection state or options,
  376. /// and instead just recreates the stream when reconnecting.
  377. template<SocketLike T>
  378. class BasicReusableSocket final : public ReusableSocket {
  379. public:
  380. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(ByteString const& host, u16 port)
  381. {
  382. return make<BasicReusableSocket<T>>(TRY(T::connect(host, port)));
  383. }
  384. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(SocketAddress const& address)
  385. {
  386. return make<BasicReusableSocket<T>>(TRY(T::connect(address)));
  387. }
  388. virtual bool is_connected() override
  389. {
  390. return m_socket.is_open();
  391. }
  392. virtual ErrorOr<void> reconnect(ByteString const& host, u16 port) override
  393. {
  394. if (is_connected())
  395. return Error::from_errno(EALREADY);
  396. m_socket = TRY(T::connect(host, port));
  397. return {};
  398. }
  399. virtual ErrorOr<void> reconnect(SocketAddress const& address) override
  400. {
  401. if (is_connected())
  402. return Error::from_errno(EALREADY);
  403. m_socket = TRY(T::connect(address));
  404. return {};
  405. }
  406. virtual ErrorOr<Bytes> read_some(Bytes buffer) override { return m_socket.read(move(buffer)); }
  407. virtual ErrorOr<size_t> write_some(ReadonlyBytes buffer) override { return m_socket.write(buffer); }
  408. virtual bool is_eof() const override { return m_socket.is_eof(); }
  409. virtual bool is_open() const override { return m_socket.is_open(); }
  410. virtual void close() override { m_socket.close(); }
  411. virtual ErrorOr<size_t> pending_bytes() const override { return m_socket.pending_bytes(); }
  412. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_socket.can_read_without_blocking(timeout); }
  413. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_socket.set_blocking(enabled); }
  414. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_socket.set_close_on_exec(enabled); }
  415. private:
  416. BasicReusableSocket(NonnullOwnPtr<T> socket)
  417. : m_socket(move(socket))
  418. {
  419. }
  420. NonnullOwnPtr<T> m_socket;
  421. };
  422. using ReusableTCPSocket = BasicReusableSocket<TCPSocket>;
  423. using ReusableUDPSocket = BasicReusableSocket<UDPSocket>;
  424. }