Stream.h 33 KB

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