/* * Copyright (c) 2021, sin-ack * Copyright (c) 2022, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Core::Stream { template T> class Handle { public: template U> Handle(NonnullOwnPtr handle) : m_handle(adopt_own(*handle.leak_ptr())) { } // This is made `explicit` to not accidentally create a non-owning Handle, // which may not always be intended. explicit Handle(T& handle) : m_handle(&handle) { } T* ptr() { if (m_handle.template has()) return m_handle.template get(); else return m_handle.template get>(); } T const* ptr() const { if (m_handle.template has()) return m_handle.template get(); else return m_handle.template get>(); } T* operator->() { return ptr(); } T const* operator->() const { return ptr(); } T& operator*() { return *ptr(); } T const& operator*() const { return *ptr(); } private: Variant, T*> m_handle; }; /// The base, abstract class for stream operations. This class defines the /// operations one can perform on every stream in LibCore. class Stream { public: /// Reads into a buffer, with the maximum size being the size of the buffer. /// The amount of bytes read can be smaller than the size of the buffer. /// Returns either the bytes that were read, or an errno in the case of /// failure. virtual ErrorOr read(Bytes) = 0; /// Tries to fill the entire buffer through reading. Returns whether the /// buffer was filled without an error. virtual ErrorOr read_entire_buffer(Bytes); /// Reads the stream until EOF, storing the contents into a ByteBuffer which /// is returned once EOF is encountered. The block size determines the size /// of newly allocated chunks while reading. virtual ErrorOr read_until_eof(size_t block_size = 4096); /// Discards the given number of bytes from the stream. As this is usually used /// as an efficient version of `read_entire_buffer`, it returns an error /// if reading failed or if not all bytes could be discarded. /// Unless specifically overwritten, this just uses read() to read into an /// internal stack-based buffer. virtual ErrorOr discard(size_t discarded_bytes); /// Tries to write the entire contents of the buffer. It is possible for /// less than the full buffer to be written. Returns either the amount of /// bytes written into the stream, or an errno in the case of failure. virtual ErrorOr write(ReadonlyBytes) = 0; /// Same as write, but does not return until either the entire buffer /// contents are written or an error occurs. virtual ErrorOr write_entire_buffer(ReadonlyBytes); // This is a wrapper around `write_entire_buffer` that is compatible with // `write_or_error`. This is required by some templated code in LibProtocol // that needs to work with either type of stream. // TODO: Fully port or wrap `Request::stream_into_impl` into `Core::Stream` and remove this. bool write_or_error(ReadonlyBytes buffer) { return !write_entire_buffer(buffer).is_error(); } template requires(IsTriviallyDestructible) ErrorOr read_trivial_value() { alignas(T) u8 buffer[sizeof(T)] = {}; TRY(read_entire_buffer(buffer)); return *bit_cast(buffer); } template requires(IsTriviallyDestructible) ErrorOr write_trivial_value(T const& value) { return write_entire_buffer({ &value, sizeof(value) }); } /// Returns whether the stream has reached the end of file. For sockets, /// this most likely means that the protocol has disconnected (in the case /// of TCP). For seekable streams, this means the end of the file. Note that /// is_eof will only return true _after_ a read with 0 length, so this /// method should be called after a read. virtual bool is_eof() const = 0; virtual bool is_open() const = 0; virtual void close() = 0; virtual ~Stream() { } protected: /// Provides a default implementation of read_until_eof that works for streams /// that behave like POSIX file descriptors. expected_file_size can be /// passed as a heuristic for what the Stream subclass expects the file /// content size to be in order to reduce allocations (does not affect /// actual reading). ErrorOr read_until_eof_impl(size_t block_size, size_t expected_file_size = 0); }; enum class SeekMode { SetPosition, FromCurrentPosition, FromEndPosition, }; /// Adds seekability to Core::Stream. Classes inheriting from SeekableStream /// will be seekable to any point in the stream. class SeekableStream : public Stream { public: /// Seeks to the given position in the given mode. Returns either the /// current position of the file, or an errno in the case of an error. virtual ErrorOr seek(i64 offset, SeekMode) = 0; /// Returns the current position of the file, or an errno in the case of /// an error. virtual ErrorOr tell() const; /// Returns the total size of the stream, or an errno in the case of an /// error. May not preserve the original position on the stream on failure. virtual ErrorOr size(); /// Shrinks or extends the stream to the given size. Returns an errno in /// the case of an error. virtual ErrorOr truncate(off_t length) = 0; /// Seeks until after the given amount of bytes to be discarded instead of /// reading and discarding everything manually; virtual ErrorOr discard(size_t discarded_bytes) override; }; enum class PreventSIGPIPE { No, Yes, }; /// The Socket class is the base class for all concrete BSD-style socket /// classes. Sockets are non-seekable streams which can be read byte-wise. class Socket : public Stream { public: Socket(Socket&&) = default; Socket& operator=(Socket&&) = default; /// Checks how many bytes of data are currently available to read on the /// socket. For datagram-based socket, this is the size of the first /// datagram that can be read. Returns either the amount of bytes, or an /// errno in the case of failure. virtual ErrorOr pending_bytes() const = 0; /// Returns whether there's any data that can be immediately read, or an /// errno on failure. virtual ErrorOr can_read_without_blocking(int timeout = 0) const = 0; // Sets the blocking mode of the socket. If blocking mode is disabled, reads // will fail with EAGAIN when there's no data available to read, and writes // will fail with EAGAIN when the data cannot be written without blocking // (due to the send buffer being full, for example). virtual ErrorOr set_blocking(bool enabled) = 0; // Sets the close-on-exec mode of the socket. If close-on-exec mode is // enabled, then the socket will be automatically closed by the kernel when // an exec call happens. virtual ErrorOr set_close_on_exec(bool enabled) = 0; /// Disables any listening mechanisms that this socket uses. /// Can be called with 'false' when `on_ready_to_read` notifications are no longer needed. /// Conversely, set_notifications_enabled(true) will re-enable notifications. virtual void set_notifications_enabled(bool) { } Function on_ready_to_read; protected: enum class SocketDomain { Local, Inet, }; enum class SocketType { Stream, Datagram, }; Socket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::No) : m_prevent_sigpipe(prevent_sigpipe == PreventSIGPIPE::Yes) { } static ErrorOr create_fd(SocketDomain, SocketType); // FIXME: This will need to be updated when IPv6 socket arrives. Perhaps a // base class for all address types is appropriate. static ErrorOr resolve_host(DeprecatedString const&, SocketType); static ErrorOr connect_local(int fd, DeprecatedString const& path); static ErrorOr connect_inet(int fd, SocketAddress const&); int default_flags() const { int flags = 0; if (m_prevent_sigpipe) flags |= MSG_NOSIGNAL; return flags; } private: bool m_prevent_sigpipe { false }; }; /// A reusable socket maintains state about being connected in addition to /// normal Socket capabilities, and can be reconnected once disconnected. class ReusableSocket : public Socket { public: /// Returns whether the socket is currently connected. virtual bool is_connected() = 0; /// Reconnects the socket to the given host and port. Returns EALREADY if /// is_connected() is true. virtual ErrorOr reconnect(DeprecatedString const& host, u16 port) = 0; /// Connects the socket to the given socket address (IP address + port). /// Returns EALREADY is_connected() is true. virtual ErrorOr reconnect(SocketAddress const&) = 0; }; // Concrete classes. enum class OpenMode : unsigned { NotOpen = 0, Read = 1, Write = 2, ReadWrite = 3, Append = 4, Truncate = 8, MustBeNew = 16, KeepOnExec = 32, Nonblocking = 64, }; enum class ShouldCloseFileDescriptor { Yes, No, }; AK_ENUM_BITWISE_OPERATORS(OpenMode) class File final : public SeekableStream { AK_MAKE_NONCOPYABLE(File); public: static ErrorOr> open(StringView filename, OpenMode, mode_t = 0644); static ErrorOr> adopt_fd(int fd, OpenMode, ShouldCloseFileDescriptor = ShouldCloseFileDescriptor::Yes); static ErrorOr> standard_input(); static ErrorOr> standard_output(); static ErrorOr> standard_error(); static ErrorOr> open_file_or_standard_stream(StringView filename, OpenMode mode); File(File&& other) { operator=(move(other)); } File& operator=(File&& other) { if (&other == this) return *this; m_mode = exchange(other.m_mode, OpenMode::NotOpen); m_fd = exchange(other.m_fd, -1); m_last_read_was_eof = exchange(other.m_last_read_was_eof, false); return *this; } virtual ErrorOr read(Bytes) override; virtual ErrorOr read_until_eof(size_t block_size = 4096) override; virtual ErrorOr write(ReadonlyBytes) override; virtual bool is_eof() const override; virtual bool is_open() const override; virtual void close() override; virtual ErrorOr seek(i64 offset, SeekMode) override; virtual ErrorOr truncate(off_t length) override; int leak_fd(Badge<::IPC::File>) { m_should_close_file_descriptor = ShouldCloseFileDescriptor::No; return m_fd; } virtual ~File() override { if (m_should_close_file_descriptor == ShouldCloseFileDescriptor::Yes) close(); } static int open_mode_to_options(OpenMode mode); private: File(OpenMode mode, ShouldCloseFileDescriptor should_close = ShouldCloseFileDescriptor::Yes) : m_mode(mode) , m_should_close_file_descriptor(should_close) { } ErrorOr open_path(StringView filename, mode_t); OpenMode m_mode { OpenMode::NotOpen }; int m_fd { -1 }; bool m_last_read_was_eof { false }; ShouldCloseFileDescriptor m_should_close_file_descriptor { ShouldCloseFileDescriptor::Yes }; }; class PosixSocketHelper { AK_MAKE_NONCOPYABLE(PosixSocketHelper); public: template PosixSocketHelper(Badge) requires(IsBaseOf) { } PosixSocketHelper(PosixSocketHelper&& other) { operator=(move(other)); } PosixSocketHelper& operator=(PosixSocketHelper&& other) { m_fd = exchange(other.m_fd, -1); m_last_read_was_eof = exchange(other.m_last_read_was_eof, false); m_notifier = move(other.m_notifier); return *this; } int fd() const { return m_fd; } void set_fd(int fd) { m_fd = fd; } ErrorOr read(Bytes, int flags); ErrorOr write(ReadonlyBytes, int flags); bool is_eof() const { return !is_open() || m_last_read_was_eof; } bool is_open() const { return m_fd != -1; } void close(); ErrorOr pending_bytes() const; ErrorOr can_read_without_blocking(int timeout) const; ErrorOr set_blocking(bool enabled); ErrorOr set_close_on_exec(bool enabled); ErrorOr set_receive_timeout(Time timeout); void setup_notifier(); RefPtr notifier() { return m_notifier; } private: int m_fd { -1 }; bool m_last_read_was_eof { false }; RefPtr m_notifier; }; class TCPSocket final : public Socket { public: static ErrorOr> connect(DeprecatedString const& host, u16 port); static ErrorOr> connect(SocketAddress const& address); static ErrorOr> adopt_fd(int fd); TCPSocket(TCPSocket&& other) : Socket(static_cast(other)) , m_helper(move(other.m_helper)) { if (is_open()) setup_notifier(); } TCPSocket& operator=(TCPSocket&& other) { Socket::operator=(static_cast(other)); m_helper = move(other.m_helper); if (is_open()) setup_notifier(); return *this; } virtual ErrorOr read(Bytes buffer) override { return m_helper.read(buffer, default_flags()); } virtual ErrorOr write(ReadonlyBytes buffer) override { return m_helper.write(buffer, default_flags()); } virtual bool is_eof() const override { return m_helper.is_eof(); } virtual bool is_open() const override { return m_helper.is_open(); }; virtual void close() override { m_helper.close(); }; virtual ErrorOr pending_bytes() const override { return m_helper.pending_bytes(); } virtual ErrorOr can_read_without_blocking(int timeout = 0) const override { return m_helper.can_read_without_blocking(timeout); } virtual void set_notifications_enabled(bool enabled) override { if (auto notifier = m_helper.notifier()) notifier->set_enabled(enabled); } ErrorOr set_blocking(bool enabled) override { return m_helper.set_blocking(enabled); } ErrorOr set_close_on_exec(bool enabled) override { return m_helper.set_close_on_exec(enabled); } virtual ~TCPSocket() override { close(); } private: TCPSocket(PreventSIGPIPE prevent_sigpipe = PreventSIGPIPE::No) : Socket(prevent_sigpipe) { } void setup_notifier() { VERIFY(is_open()); m_helper.setup_notifier(); m_helper.notifier()->on_ready_to_read = [this] { if (on_ready_to_read) on_ready_to_read(); }; } PosixSocketHelper m_helper { Badge {} }; }; class UDPSocket final : public Socket { public: static ErrorOr> connect(DeprecatedString const& host, u16 port, Optional