Stream.h 31 KB

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