Stream.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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/EnumBits.h>
  9. #include <AK/Function.h>
  10. #include <AK/IPv4Address.h>
  11. #include <AK/MemMem.h>
  12. #include <AK/Noncopyable.h>
  13. #include <AK/Result.h>
  14. #include <AK/Span.h>
  15. #include <AK/String.h>
  16. #include <AK/Time.h>
  17. #include <AK/Variant.h>
  18. #include <LibCore/Notifier.h>
  19. #include <LibCore/SocketAddress.h>
  20. #include <errno.h>
  21. #include <netdb.h>
  22. namespace Core::Stream {
  23. /// The base, abstract class for stream operations. This class defines the
  24. /// operations one can perform on every stream in LibCore.
  25. class Stream {
  26. public:
  27. virtual bool is_readable() const { return false; }
  28. /// Reads into a buffer, with the maximum size being the size of the buffer.
  29. /// The amount of bytes read can be smaller than the size of the buffer.
  30. /// Returns either the bytes that were read, or an errno in the case of
  31. /// failure.
  32. virtual ErrorOr<Bytes> read(Bytes) = 0;
  33. /// Tries to fill the entire buffer through reading. Returns whether the
  34. /// buffer was filled without an error.
  35. virtual bool read_or_error(Bytes);
  36. /// Reads the stream until EOF, storing the contents into a ByteBuffer which
  37. /// is returned once EOF is encountered. The block size determines the size
  38. /// of newly allocated chunks while reading.
  39. virtual ErrorOr<ByteBuffer> read_all(size_t block_size = 4096);
  40. virtual bool is_writable() const { return false; }
  41. /// Tries to write the entire contents of the buffer. It is possible for
  42. /// less than the full buffer to be written. Returns either the amount of
  43. /// bytes written into the stream, or an errno in the case of failure.
  44. virtual ErrorOr<size_t> write(ReadonlyBytes) = 0;
  45. /// Same as write, but does not return until either the entire buffer
  46. /// contents are written or an error occurs. Returns whether the entire
  47. /// contents were written without an error.
  48. virtual bool write_or_error(ReadonlyBytes);
  49. /// Returns whether the stream has reached the end of file. For sockets,
  50. /// this most likely means that the protocol has disconnected (in the case
  51. /// of TCP). For seekable streams, this means the end of the file. Note that
  52. /// is_eof will only return true _after_ a read with 0 length, so this
  53. /// method should be called after a read.
  54. virtual bool is_eof() const = 0;
  55. virtual bool is_open() const = 0;
  56. virtual void close() = 0;
  57. virtual ~Stream()
  58. {
  59. }
  60. protected:
  61. /// Provides a default implementation of read_all that works for streams
  62. /// that behave like POSIX file descriptors. expected_file_size can be
  63. /// passed as a heuristic for what the Stream subclass expects the file
  64. /// content size to be in order to reduce allocations (does not affect
  65. /// actual reading).
  66. ErrorOr<ByteBuffer> read_all_impl(size_t block_size, size_t expected_file_size = 0);
  67. };
  68. enum class SeekMode {
  69. SetPosition,
  70. FromCurrentPosition,
  71. FromEndPosition,
  72. };
  73. /// Adds seekability to Core::Stream. Classes inheriting from SeekableStream
  74. /// will be seekable to any point in the stream.
  75. class SeekableStream : public Stream {
  76. public:
  77. /// Seeks to the given position in the given mode. Returns either the
  78. /// current position of the file, or an errno in the case of an error.
  79. virtual ErrorOr<off_t> seek(i64 offset, SeekMode) = 0;
  80. /// Returns the current position of the file, or an errno in the case of
  81. /// an error.
  82. virtual ErrorOr<off_t> tell() const;
  83. /// Returns the total size of the stream, or an errno in the case of an
  84. /// error. May not preserve the original position on the stream on failure.
  85. virtual ErrorOr<off_t> size();
  86. /// Shrinks or extends the stream to the given size. Returns an errno in
  87. /// the case of an error.
  88. virtual ErrorOr<void> truncate(off_t length) = 0;
  89. };
  90. /// The Socket class is the base class for all concrete BSD-style socket
  91. /// classes. Sockets are non-seekable streams which can be read byte-wise.
  92. class Socket : public Stream {
  93. public:
  94. Socket(Socket&&) = default;
  95. Socket& operator=(Socket&&) = default;
  96. /// Checks how many bytes of data are currently available to read on the
  97. /// socket. For datagram-based socket, this is the size of the first
  98. /// datagram that can be read. Returns either the amount of bytes, or an
  99. /// errno in the case of failure.
  100. virtual ErrorOr<size_t> pending_bytes() const = 0;
  101. /// Returns whether there's any data that can be immediately read, or an
  102. /// errno on failure.
  103. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const = 0;
  104. // Sets the blocking mode of the socket. If blocking mode is disabled, reads
  105. // will fail with EAGAIN when there's no data available to read, and writes
  106. // will fail with EAGAIN when the data cannot be written without blocking
  107. // (due to the send buffer being full, for example).
  108. virtual ErrorOr<void> set_blocking(bool enabled) = 0;
  109. // Sets the close-on-exec mode of the socket. If close-on-exec mode is
  110. // enabled, then the socket will be automatically closed by the kernel when
  111. // an exec call happens.
  112. virtual ErrorOr<void> set_close_on_exec(bool enabled) = 0;
  113. /// Disables any listening mechanisms that this socket uses.
  114. /// Can be called with 'false' when `on_ready_to_read` notifications are no longer needed.
  115. /// Conversely, set_notifications_enabled(true) will re-enable notifications.
  116. virtual void set_notifications_enabled(bool) { }
  117. Function<void()> on_ready_to_read;
  118. protected:
  119. enum class SocketDomain {
  120. Local,
  121. Inet,
  122. };
  123. enum class SocketType {
  124. Stream,
  125. Datagram,
  126. };
  127. Socket()
  128. {
  129. }
  130. static ErrorOr<int> create_fd(SocketDomain, SocketType);
  131. // FIXME: This will need to be updated when IPv6 socket arrives. Perhaps a
  132. // base class for all address types is appropriate.
  133. static ErrorOr<IPv4Address> resolve_host(String const&, SocketType);
  134. static ErrorOr<void> connect_local(int fd, String const& path);
  135. static ErrorOr<void> connect_inet(int fd, SocketAddress const&);
  136. };
  137. /// A reusable socket maintains state about being connected in addition to
  138. /// normal Socket capabilities, and can be reconnected once disconnected.
  139. class ReusableSocket : public Socket {
  140. public:
  141. /// Returns whether the socket is currently connected.
  142. virtual bool is_connected() = 0;
  143. /// Reconnects the socket to the given host and port. Returns EALREADY if
  144. /// is_connected() is true.
  145. virtual ErrorOr<void> reconnect(String const& host, u16 port) = 0;
  146. /// Connects the socket to the given socket address (IP address + port).
  147. /// Returns EALREADY is_connected() is true.
  148. virtual ErrorOr<void> reconnect(SocketAddress const&) = 0;
  149. };
  150. // Concrete classes.
  151. enum class OpenMode : unsigned {
  152. NotOpen = 0,
  153. Read = 1,
  154. Write = 2,
  155. ReadWrite = 3,
  156. Append = 4,
  157. Truncate = 8,
  158. MustBeNew = 16,
  159. KeepOnExec = 32,
  160. Nonblocking = 64,
  161. };
  162. enum class ShouldCloseFileDescriptor {
  163. Yes,
  164. No,
  165. };
  166. AK_ENUM_BITWISE_OPERATORS(OpenMode)
  167. class File final : public SeekableStream {
  168. AK_MAKE_NONCOPYABLE(File);
  169. public:
  170. static ErrorOr<NonnullOwnPtr<File>> open(StringView filename, OpenMode, mode_t = 0644);
  171. static ErrorOr<NonnullOwnPtr<File>> adopt_fd(int fd, OpenMode, ShouldCloseFileDescriptor = ShouldCloseFileDescriptor::Yes);
  172. static bool exists(StringView filename);
  173. static ErrorOr<NonnullOwnPtr<File>> standard_input();
  174. static ErrorOr<NonnullOwnPtr<File>> standard_output();
  175. static ErrorOr<NonnullOwnPtr<File>> standard_error();
  176. static ErrorOr<NonnullOwnPtr<File>> open_file_or_standard_stream(StringView filename, OpenMode mode);
  177. File(File&& other) { operator=(move(other)); }
  178. File& operator=(File&& other)
  179. {
  180. if (&other == this)
  181. return *this;
  182. m_mode = exchange(other.m_mode, OpenMode::NotOpen);
  183. m_fd = exchange(other.m_fd, -1);
  184. m_last_read_was_eof = exchange(other.m_last_read_was_eof, false);
  185. return *this;
  186. }
  187. virtual bool is_readable() const override;
  188. virtual ErrorOr<Bytes> read(Bytes) override;
  189. virtual ErrorOr<ByteBuffer> read_all(size_t block_size = 4096) override;
  190. virtual bool is_writable() const override;
  191. virtual ErrorOr<size_t> write(ReadonlyBytes) override;
  192. virtual bool is_eof() const override;
  193. virtual bool is_open() const override;
  194. virtual void close() override;
  195. virtual ErrorOr<off_t> seek(i64 offset, SeekMode) override;
  196. virtual ErrorOr<void> truncate(off_t length) override;
  197. virtual ~File() override
  198. {
  199. if (m_should_close_file_descriptor == ShouldCloseFileDescriptor::Yes)
  200. close();
  201. }
  202. static int open_mode_to_options(OpenMode mode);
  203. private:
  204. File(OpenMode mode, ShouldCloseFileDescriptor should_close = ShouldCloseFileDescriptor::Yes)
  205. : m_mode(mode)
  206. , m_should_close_file_descriptor(should_close)
  207. {
  208. }
  209. ErrorOr<void> open_path(StringView filename, mode_t);
  210. OpenMode m_mode { OpenMode::NotOpen };
  211. int m_fd { -1 };
  212. bool m_last_read_was_eof { false };
  213. ShouldCloseFileDescriptor m_should_close_file_descriptor { ShouldCloseFileDescriptor::Yes };
  214. };
  215. class PosixSocketHelper {
  216. AK_MAKE_NONCOPYABLE(PosixSocketHelper);
  217. public:
  218. template<typename T>
  219. PosixSocketHelper(Badge<T>) requires(IsBaseOf<Socket, T>) { }
  220. PosixSocketHelper(PosixSocketHelper&& other)
  221. {
  222. operator=(move(other));
  223. }
  224. PosixSocketHelper& operator=(PosixSocketHelper&& other)
  225. {
  226. m_fd = exchange(other.m_fd, -1);
  227. m_last_read_was_eof = exchange(other.m_last_read_was_eof, false);
  228. m_notifier = move(other.m_notifier);
  229. return *this;
  230. }
  231. int fd() const { return m_fd; }
  232. void set_fd(int fd) { m_fd = fd; }
  233. ErrorOr<Bytes> read(Bytes, int flags = 0);
  234. ErrorOr<size_t> write(ReadonlyBytes);
  235. bool is_eof() const { return !is_open() || m_last_read_was_eof; }
  236. bool is_open() const { return m_fd != -1; }
  237. void close();
  238. ErrorOr<size_t> pending_bytes() const;
  239. ErrorOr<bool> can_read_without_blocking(int timeout) const;
  240. ErrorOr<void> set_blocking(bool enabled);
  241. ErrorOr<void> set_close_on_exec(bool enabled);
  242. ErrorOr<void> set_receive_timeout(Time timeout);
  243. void setup_notifier();
  244. RefPtr<Core::Notifier> notifier() { return m_notifier; }
  245. private:
  246. int m_fd { -1 };
  247. bool m_last_read_was_eof { false };
  248. RefPtr<Core::Notifier> m_notifier;
  249. };
  250. class TCPSocket final : public Socket {
  251. public:
  252. static ErrorOr<NonnullOwnPtr<TCPSocket>> connect(String const& host, u16 port);
  253. static ErrorOr<NonnullOwnPtr<TCPSocket>> connect(SocketAddress const& address);
  254. static ErrorOr<NonnullOwnPtr<TCPSocket>> adopt_fd(int fd);
  255. TCPSocket(TCPSocket&& other)
  256. : Socket(static_cast<Socket&&>(other))
  257. , m_helper(move(other.m_helper))
  258. {
  259. if (is_open())
  260. setup_notifier();
  261. }
  262. TCPSocket& operator=(TCPSocket&& other)
  263. {
  264. Socket::operator=(static_cast<Socket&&>(other));
  265. m_helper = move(other.m_helper);
  266. if (is_open())
  267. setup_notifier();
  268. return *this;
  269. }
  270. virtual bool is_readable() const override { return is_open(); }
  271. virtual bool is_writable() const override { return is_open(); }
  272. virtual ErrorOr<Bytes> read(Bytes buffer) override { return m_helper.read(buffer); }
  273. virtual ErrorOr<size_t> write(ReadonlyBytes buffer) override { return m_helper.write(buffer); }
  274. virtual bool is_eof() const override { return m_helper.is_eof(); }
  275. virtual bool is_open() const override { return m_helper.is_open(); };
  276. virtual void close() override { m_helper.close(); };
  277. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  278. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  279. virtual void set_notifications_enabled(bool enabled) override
  280. {
  281. if (auto notifier = m_helper.notifier())
  282. notifier->set_enabled(enabled);
  283. }
  284. ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  285. ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  286. virtual ~TCPSocket() override { close(); }
  287. private:
  288. TCPSocket()
  289. {
  290. }
  291. void setup_notifier()
  292. {
  293. VERIFY(is_open());
  294. m_helper.setup_notifier();
  295. m_helper.notifier()->on_ready_to_read = [this] {
  296. if (on_ready_to_read)
  297. on_ready_to_read();
  298. };
  299. }
  300. PosixSocketHelper m_helper { Badge<TCPSocket> {} };
  301. };
  302. class UDPSocket final : public Socket {
  303. public:
  304. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(String const& host, u16 port, Optional<Time> timeout = {});
  305. static ErrorOr<NonnullOwnPtr<UDPSocket>> connect(SocketAddress const& address, Optional<Time> timeout = {});
  306. UDPSocket(UDPSocket&& other)
  307. : Socket(static_cast<Socket&&>(other))
  308. , m_helper(move(other.m_helper))
  309. {
  310. if (is_open())
  311. setup_notifier();
  312. }
  313. UDPSocket& operator=(UDPSocket&& other)
  314. {
  315. Socket::operator=(static_cast<Socket&&>(other));
  316. m_helper = move(other.m_helper);
  317. if (is_open())
  318. setup_notifier();
  319. return *this;
  320. }
  321. virtual ErrorOr<Bytes> read(Bytes buffer) override
  322. {
  323. auto pending_bytes = TRY(this->pending_bytes());
  324. if (pending_bytes > buffer.size()) {
  325. // With UDP datagrams, reading a datagram into a buffer that's
  326. // smaller than the datagram's size will cause the rest of the
  327. // datagram to be discarded. That's not very nice, so let's bail
  328. // early, telling the caller that he should allocate a bigger
  329. // buffer.
  330. return Error::from_errno(EMSGSIZE);
  331. }
  332. return m_helper.read(buffer);
  333. }
  334. virtual bool is_readable() const override { return is_open(); }
  335. virtual bool is_writable() const override { return is_open(); }
  336. virtual ErrorOr<size_t> write(ReadonlyBytes buffer) override { return m_helper.write(buffer); }
  337. virtual bool is_eof() const override { return m_helper.is_eof(); }
  338. virtual bool is_open() const override { return m_helper.is_open(); }
  339. virtual void close() override { m_helper.close(); }
  340. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  341. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  342. virtual void set_notifications_enabled(bool enabled) override
  343. {
  344. if (auto notifier = m_helper.notifier())
  345. notifier->set_enabled(enabled);
  346. }
  347. ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  348. ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  349. virtual ~UDPSocket() override { close(); }
  350. private:
  351. UDPSocket() = default;
  352. void setup_notifier()
  353. {
  354. VERIFY(is_open());
  355. m_helper.setup_notifier();
  356. m_helper.notifier()->on_ready_to_read = [this] {
  357. if (on_ready_to_read)
  358. on_ready_to_read();
  359. };
  360. }
  361. PosixSocketHelper m_helper { Badge<UDPSocket> {} };
  362. };
  363. class LocalSocket final : public Socket {
  364. public:
  365. static ErrorOr<NonnullOwnPtr<LocalSocket>> connect(String const& path);
  366. static ErrorOr<NonnullOwnPtr<LocalSocket>> adopt_fd(int fd);
  367. LocalSocket(LocalSocket&& other)
  368. : Socket(static_cast<Socket&&>(other))
  369. , m_helper(move(other.m_helper))
  370. {
  371. if (is_open())
  372. setup_notifier();
  373. }
  374. LocalSocket& operator=(LocalSocket&& other)
  375. {
  376. Socket::operator=(static_cast<Socket&&>(other));
  377. m_helper = move(other.m_helper);
  378. if (is_open())
  379. setup_notifier();
  380. return *this;
  381. }
  382. virtual bool is_readable() const override { return is_open(); }
  383. virtual bool is_writable() const override { return is_open(); }
  384. virtual ErrorOr<Bytes> read(Bytes buffer) override { return m_helper.read(buffer); }
  385. virtual ErrorOr<size_t> write(ReadonlyBytes buffer) override { return m_helper.write(buffer); }
  386. virtual bool is_eof() const override { return m_helper.is_eof(); }
  387. virtual bool is_open() const override { return m_helper.is_open(); }
  388. virtual void close() override { m_helper.close(); }
  389. virtual ErrorOr<size_t> pending_bytes() const override { return m_helper.pending_bytes(); }
  390. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); }
  391. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); }
  392. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); }
  393. virtual void set_notifications_enabled(bool enabled) override
  394. {
  395. if (auto notifier = m_helper.notifier())
  396. notifier->set_enabled(enabled);
  397. }
  398. ErrorOr<int> receive_fd(int flags);
  399. ErrorOr<void> send_fd(int fd);
  400. ErrorOr<pid_t> peer_pid() const;
  401. ErrorOr<Bytes> read_without_waiting(Bytes buffer);
  402. /// Release the fd associated with this LocalSocket. After the fd is
  403. /// released, the socket will be considered "closed" and all operations done
  404. /// on it will fail with ENOTCONN. Fails with ENOTCONN if the socket is
  405. /// already closed.
  406. ErrorOr<int> release_fd();
  407. Optional<int> fd() const;
  408. RefPtr<Core::Notifier> notifier() { return m_helper.notifier(); }
  409. virtual ~LocalSocket() { close(); }
  410. private:
  411. LocalSocket() = default;
  412. void setup_notifier()
  413. {
  414. VERIFY(is_open());
  415. m_helper.setup_notifier();
  416. m_helper.notifier()->on_ready_to_read = [this] {
  417. if (on_ready_to_read)
  418. on_ready_to_read();
  419. };
  420. }
  421. PosixSocketHelper m_helper { Badge<LocalSocket> {} };
  422. };
  423. // Buffered stream wrappers
  424. template<typename T>
  425. concept StreamLike = IsBaseOf<Stream, T>;
  426. template<typename T>
  427. concept SeekableStreamLike = IsBaseOf<SeekableStream, T>;
  428. template<typename T>
  429. concept SocketLike = IsBaseOf<Socket, T>;
  430. template<typename T>
  431. class BufferedHelper {
  432. AK_MAKE_NONCOPYABLE(BufferedHelper);
  433. public:
  434. template<StreamLike U>
  435. BufferedHelper(Badge<U>, NonnullOwnPtr<T> stream, ByteBuffer buffer)
  436. : m_stream(move(stream))
  437. , m_buffer(move(buffer))
  438. {
  439. }
  440. BufferedHelper(BufferedHelper&& other)
  441. : m_stream(move(other.m_stream))
  442. , m_buffer(move(other.m_buffer))
  443. , m_buffered_size(exchange(other.m_buffered_size, 0))
  444. {
  445. }
  446. BufferedHelper& operator=(BufferedHelper&& other)
  447. {
  448. m_stream = move(other.m_stream);
  449. m_buffer = move(other.m_buffer);
  450. m_buffered_size = exchange(other.m_buffered_size, 0);
  451. return *this;
  452. }
  453. template<template<typename> typename BufferedType>
  454. static ErrorOr<NonnullOwnPtr<BufferedType<T>>> create_buffered(NonnullOwnPtr<T> stream, size_t buffer_size)
  455. {
  456. if (!buffer_size)
  457. return Error::from_errno(EINVAL);
  458. if (!stream->is_open())
  459. return Error::from_errno(ENOTCONN);
  460. auto buffer = TRY(ByteBuffer::create_uninitialized(buffer_size));
  461. return adopt_nonnull_own_or_enomem(new BufferedType<T>(move(stream), move(buffer)));
  462. }
  463. T& stream() { return *m_stream; }
  464. T const& stream() const { return *m_stream; }
  465. ErrorOr<Bytes> read(Bytes buffer)
  466. {
  467. if (!stream().is_open())
  468. return Error::from_errno(ENOTCONN);
  469. if (!buffer.size())
  470. return Error::from_errno(ENOBUFS);
  471. // Fill the internal buffer if it has run dry.
  472. if (m_buffered_size == 0)
  473. TRY(populate_read_buffer());
  474. // Let's try to take all we can from the buffer first.
  475. size_t buffer_nread = 0;
  476. if (m_buffered_size > 0) {
  477. // FIXME: Use a circular buffer to avoid shifting the buffer
  478. // contents.
  479. size_t amount_to_take = min(buffer.size(), m_buffered_size);
  480. auto slice_to_take = m_buffer.span().slice(0, amount_to_take);
  481. auto slice_to_shift = m_buffer.span().slice(amount_to_take);
  482. slice_to_take.copy_to(buffer);
  483. buffer_nread += amount_to_take;
  484. if (amount_to_take < m_buffered_size) {
  485. m_buffer.overwrite(0, slice_to_shift.data(), m_buffered_size - amount_to_take);
  486. }
  487. m_buffered_size -= amount_to_take;
  488. }
  489. return Bytes { buffer.data(), buffer_nread };
  490. }
  491. // Reads into the buffer until \n is encountered.
  492. // The size of the Bytes object is the maximum amount of bytes that will be
  493. // read. Returns the bytes read as a StringView.
  494. ErrorOr<StringView> read_line(Bytes buffer)
  495. {
  496. return StringView { TRY(read_until(buffer, "\n"sv)) };
  497. }
  498. ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate)
  499. {
  500. return read_until_any_of(buffer, Array { candidate });
  501. }
  502. template<size_t N>
  503. ErrorOr<Bytes> read_until_any_of(Bytes buffer, Array<StringView, N> candidates)
  504. {
  505. if (!stream().is_open())
  506. return Error::from_errno(ENOTCONN);
  507. if (buffer.is_empty())
  508. return Error::from_errno(ENOBUFS);
  509. // We fill the buffer through can_read_line.
  510. if (!TRY(can_read_line()))
  511. return Bytes {};
  512. if (stream().is_eof()) {
  513. if (buffer.size() < m_buffered_size) {
  514. // Normally, reading from an EOFed stream and receiving bytes
  515. // would mean that the stream is no longer EOF. However, it's
  516. // possible with a buffered stream that the user is able to read
  517. // the buffer contents even when the underlying stream is EOF.
  518. // We already violate this invariant once by giving the user the
  519. // chance to read the remaining buffer contents, but if the user
  520. // doesn't give us a big enough buffer, then we would be
  521. // violating the invariant twice the next time the user attempts
  522. // to read, which is No Good. So let's give a descriptive error
  523. // to the caller about why it can't read.
  524. return Error::from_errno(EMSGSIZE);
  525. }
  526. }
  527. auto readable_size = min(m_buffered_size, buffer.size());
  528. // The intention here is to try to match all of the possible
  529. // delimiter candidates and try to find the longest one we can
  530. // remove from the buffer after copying up to the delimiter to the
  531. // user buffer.
  532. Optional<size_t> longest_match;
  533. size_t match_size = 0;
  534. for (auto& candidate : candidates) {
  535. auto result = AK::memmem_optional(m_buffer.data(), readable_size, candidate.bytes().data(), candidate.bytes().size());
  536. if (result.has_value()) {
  537. auto previous_match = longest_match.value_or(*result);
  538. if ((previous_match < *result) || (previous_match == *result && match_size < candidate.length())) {
  539. longest_match = result;
  540. match_size = candidate.length();
  541. }
  542. }
  543. }
  544. if (longest_match.has_value()) {
  545. auto size_written_to_user_buffer = *longest_match;
  546. auto buffer_to_take = m_buffer.span().slice(0, size_written_to_user_buffer);
  547. auto buffer_to_shift = m_buffer.span().slice(size_written_to_user_buffer + match_size);
  548. buffer_to_take.copy_to(buffer);
  549. m_buffer.overwrite(0, buffer_to_shift.data(), buffer_to_shift.size());
  550. m_buffered_size -= size_written_to_user_buffer + match_size;
  551. return buffer.slice(0, size_written_to_user_buffer);
  552. }
  553. // If we still haven't found anything, then it's most likely the case
  554. // that the delimiter ends beyond the length of the caller-passed
  555. // buffer. Let's just fill the caller's buffer up.
  556. auto buffer_to_take = m_buffer.span().slice(0, readable_size);
  557. auto buffer_to_shift = m_buffer.span().slice(readable_size);
  558. buffer_to_take.copy_to(buffer);
  559. m_buffer.overwrite(0, buffer_to_shift.data(), buffer_to_shift.size());
  560. m_buffered_size -= readable_size;
  561. return buffer.slice(0, readable_size);
  562. }
  563. // Returns whether a line can be read, populating the buffer in the process.
  564. ErrorOr<bool> can_read_line()
  565. {
  566. if (stream().is_eof() && m_buffered_size > 0)
  567. return true;
  568. if (m_buffer.span().slice(0, m_buffered_size).contains_slow('\n'))
  569. return true;
  570. if (!stream().is_readable())
  571. return false;
  572. while (m_buffered_size < m_buffer.size()) {
  573. auto populated_slice = TRY(populate_read_buffer());
  574. if (stream().is_eof()) {
  575. // We give the user one last hurrah to read the remaining
  576. // contents as a "line".
  577. return m_buffered_size > 0;
  578. }
  579. if (populated_slice.contains_slow('\n'))
  580. return true;
  581. if (populated_slice.is_empty())
  582. break;
  583. }
  584. return false;
  585. }
  586. bool is_eof() const
  587. {
  588. if (m_buffered_size > 0) {
  589. return false;
  590. }
  591. return stream().is_eof();
  592. }
  593. size_t buffer_size() const
  594. {
  595. return m_buffer.size();
  596. }
  597. size_t buffered_data_size() const
  598. {
  599. return m_buffered_size;
  600. }
  601. void clear_buffer()
  602. {
  603. m_buffered_size = 0;
  604. }
  605. private:
  606. ErrorOr<ReadonlyBytes> populate_read_buffer()
  607. {
  608. if (m_buffered_size == m_buffer.size())
  609. return ReadonlyBytes {};
  610. auto fillable_slice = m_buffer.span().slice(m_buffered_size);
  611. size_t nread = 0;
  612. do {
  613. auto result = stream().read(fillable_slice);
  614. if (result.is_error()) {
  615. if (!result.error().is_errno())
  616. return result.error();
  617. if (result.error().code() == EINTR)
  618. continue;
  619. if (result.error().code() == EAGAIN)
  620. break;
  621. return result.error();
  622. }
  623. auto read_size = result.value().size();
  624. m_buffered_size += read_size;
  625. nread += read_size;
  626. break;
  627. } while (true);
  628. return fillable_slice.slice(0, nread);
  629. }
  630. NonnullOwnPtr<T> m_stream;
  631. // FIXME: Replacing this with a circular buffer would be really nice and
  632. // would avoid excessive copies; however, right now
  633. // AK::CircularDuplexBuffer inlines its entire contents, and that
  634. // would make for a very large object on the stack.
  635. //
  636. // The proper fix is to make a CircularQueue which uses a buffer on
  637. // the heap.
  638. ByteBuffer m_buffer;
  639. size_t m_buffered_size { 0 };
  640. };
  641. // NOTE: A Buffered which accepts any Stream could be added here, but it is not
  642. // needed at the moment.
  643. template<SeekableStreamLike T>
  644. class BufferedSeekable final : public SeekableStream {
  645. friend BufferedHelper<T>;
  646. public:
  647. static ErrorOr<NonnullOwnPtr<BufferedSeekable<T>>> create(NonnullOwnPtr<T> stream, size_t buffer_size = 16384)
  648. {
  649. return BufferedHelper<T>::template create_buffered<BufferedSeekable>(move(stream), buffer_size);
  650. }
  651. BufferedSeekable(BufferedSeekable&& other) = default;
  652. BufferedSeekable& operator=(BufferedSeekable&& other) = default;
  653. virtual bool is_readable() const override { return m_helper.stream().is_readable(); }
  654. virtual ErrorOr<Bytes> read(Bytes buffer) override { return m_helper.read(move(buffer)); }
  655. virtual bool is_writable() const override { return m_helper.stream().is_writable(); }
  656. virtual ErrorOr<size_t> write(ReadonlyBytes buffer) override { return m_helper.stream().write(buffer); }
  657. virtual bool is_eof() const override { return m_helper.is_eof(); }
  658. virtual bool is_open() const override { return m_helper.stream().is_open(); }
  659. virtual void close() override { m_helper.stream().close(); }
  660. virtual ErrorOr<off_t> seek(i64 offset, SeekMode mode) override
  661. {
  662. auto result = TRY(m_helper.stream().seek(offset, mode));
  663. m_helper.clear_buffer();
  664. return result;
  665. }
  666. virtual ErrorOr<void> truncate(off_t length) override
  667. {
  668. return m_helper.stream().truncate(length);
  669. }
  670. ErrorOr<StringView> read_line(Bytes buffer) { return m_helper.read_line(move(buffer)); }
  671. ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) { return m_helper.read_until(move(buffer), move(candidate)); }
  672. template<size_t N>
  673. ErrorOr<Bytes> read_until_any_of(Bytes buffer, Array<StringView, N> candidates) { return m_helper.read_until_any_of(move(buffer), move(candidates)); }
  674. ErrorOr<bool> can_read_line() { return m_helper.can_read_line(); }
  675. size_t buffer_size() const { return m_helper.buffer_size(); }
  676. virtual ~BufferedSeekable() override = default;
  677. private:
  678. BufferedSeekable(NonnullOwnPtr<T> stream, ByteBuffer buffer)
  679. : m_helper(Badge<BufferedSeekable<T>> {}, move(stream), buffer)
  680. {
  681. }
  682. BufferedHelper<T> m_helper;
  683. };
  684. class BufferedSocketBase : public Socket {
  685. public:
  686. virtual ErrorOr<StringView> read_line(Bytes buffer) = 0;
  687. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) = 0;
  688. virtual ErrorOr<bool> can_read_line() = 0;
  689. virtual size_t buffer_size() const = 0;
  690. };
  691. template<SocketLike T>
  692. class BufferedSocket final : public BufferedSocketBase {
  693. friend BufferedHelper<T>;
  694. public:
  695. static ErrorOr<NonnullOwnPtr<BufferedSocket<T>>> create(NonnullOwnPtr<T> stream, size_t buffer_size = 16384)
  696. {
  697. return BufferedHelper<T>::template create_buffered<BufferedSocket>(move(stream), buffer_size);
  698. }
  699. BufferedSocket(BufferedSocket&& other)
  700. : BufferedSocketBase(static_cast<BufferedSocketBase&&>(other))
  701. , m_helper(move(other.m_helper))
  702. {
  703. setup_notifier();
  704. }
  705. BufferedSocket& operator=(BufferedSocket&& other)
  706. {
  707. Socket::operator=(static_cast<Socket&&>(other));
  708. m_helper = move(other.m_helper);
  709. setup_notifier();
  710. return *this;
  711. }
  712. virtual bool is_readable() const override { return m_helper.stream().is_readable(); }
  713. virtual ErrorOr<Bytes> read(Bytes buffer) override { return m_helper.read(move(buffer)); }
  714. virtual bool is_writable() const override { return m_helper.stream().is_writable(); }
  715. virtual ErrorOr<size_t> write(ReadonlyBytes buffer) override { return m_helper.stream().write(buffer); }
  716. virtual bool is_eof() const override { return m_helper.is_eof(); }
  717. virtual bool is_open() const override { return m_helper.stream().is_open(); }
  718. virtual void close() override { m_helper.stream().close(); }
  719. virtual ErrorOr<size_t> pending_bytes() const override
  720. {
  721. return TRY(m_helper.stream().pending_bytes()) + m_helper.buffered_data_size();
  722. }
  723. 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)); }
  724. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_helper.stream().set_blocking(enabled); }
  725. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_helper.stream().set_close_on_exec(enabled); }
  726. virtual void set_notifications_enabled(bool enabled) override { m_helper.stream().set_notifications_enabled(enabled); }
  727. virtual ErrorOr<StringView> read_line(Bytes buffer) override { return m_helper.read_line(move(buffer)); }
  728. virtual ErrorOr<Bytes> read_until(Bytes buffer, StringView candidate) override { return m_helper.read_until(move(buffer), move(candidate)); }
  729. template<size_t N>
  730. ErrorOr<Bytes> read_until_any_of(Bytes buffer, Array<StringView, N> candidates) { return m_helper.read_until_any_of(move(buffer), move(candidates)); }
  731. virtual ErrorOr<bool> can_read_line() override { return m_helper.can_read_line(); }
  732. virtual size_t buffer_size() const override { return m_helper.buffer_size(); }
  733. virtual ~BufferedSocket() override = default;
  734. private:
  735. BufferedSocket(NonnullOwnPtr<T> stream, ByteBuffer buffer)
  736. : m_helper(Badge<BufferedSocket<T>> {}, move(stream), buffer)
  737. {
  738. setup_notifier();
  739. }
  740. void setup_notifier()
  741. {
  742. m_helper.stream().on_ready_to_read = [this] {
  743. if (on_ready_to_read)
  744. on_ready_to_read();
  745. };
  746. }
  747. BufferedHelper<T> m_helper;
  748. };
  749. using BufferedFile = BufferedSeekable<File>;
  750. using BufferedTCPSocket = BufferedSocket<TCPSocket>;
  751. using BufferedUDPSocket = BufferedSocket<UDPSocket>;
  752. using BufferedLocalSocket = BufferedSocket<LocalSocket>;
  753. /// A BasicReusableSocket allows one to use one of the base Core::Stream classes
  754. /// as a ReusableSocket. It does not preserve any connection state or options,
  755. /// and instead just recreates the stream when reconnecting.
  756. template<SocketLike T>
  757. class BasicReusableSocket final : public ReusableSocket {
  758. public:
  759. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(String const& host, u16 port)
  760. {
  761. return make<BasicReusableSocket<T>>(TRY(T::connect(host, port)));
  762. }
  763. static ErrorOr<NonnullOwnPtr<BasicReusableSocket<T>>> connect(SocketAddress const& address)
  764. {
  765. return make<BasicReusableSocket<T>>(TRY(T::connect(address)));
  766. }
  767. virtual bool is_connected() override
  768. {
  769. return m_socket.is_open();
  770. }
  771. virtual ErrorOr<void> reconnect(String const& host, u16 port) override
  772. {
  773. if (is_connected())
  774. return Error::from_errno(EALREADY);
  775. m_socket = TRY(T::connect(host, port));
  776. return {};
  777. }
  778. virtual ErrorOr<void> reconnect(SocketAddress const& address) override
  779. {
  780. if (is_connected())
  781. return Error::from_errno(EALREADY);
  782. m_socket = TRY(T::connect(address));
  783. return {};
  784. }
  785. virtual bool is_readable() const override { return m_socket.is_readable(); }
  786. virtual ErrorOr<Bytes> read(Bytes buffer) override { return m_socket.read(move(buffer)); }
  787. virtual bool is_writable() const override { return m_socket.is_writable(); }
  788. virtual ErrorOr<size_t> write(ReadonlyBytes buffer) override { return m_socket.write(buffer); }
  789. virtual bool is_eof() const override { return m_socket.is_eof(); }
  790. virtual bool is_open() const override { return m_socket.is_open(); }
  791. virtual void close() override { m_socket.close(); }
  792. virtual ErrorOr<size_t> pending_bytes() const override { return m_socket.pending_bytes(); }
  793. virtual ErrorOr<bool> can_read_without_blocking(int timeout = 0) const override { return m_socket.can_read_without_blocking(timeout); }
  794. virtual ErrorOr<void> set_blocking(bool enabled) override { return m_socket.set_blocking(enabled); }
  795. virtual ErrorOr<void> set_close_on_exec(bool enabled) override { return m_socket.set_close_on_exec(enabled); }
  796. private:
  797. BasicReusableSocket(NonnullOwnPtr<T> socket)
  798. : m_socket(move(socket))
  799. {
  800. }
  801. NonnullOwnPtr<T> m_socket;
  802. };
  803. using ReusableTCPSocket = BasicReusableSocket<TCPSocket>;
  804. using ReusableUDPSocket = BasicReusableSocket<UDPSocket>;
  805. }