Stream.h 33 KB

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