Stream.h 32 KB

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