#pragma once #include "common.h" #include #include #include #include #include namespace vn::net { #if defined(_WIN32) using Socket = std::uintptr_t; constexpr Socket INVALID_SOCKET_VALUE = static_cast(~0ull); #else using Socket = int; constexpr Socket INVALID_SOCKET_VALUE = -1; #endif // A reliable, ordered byte stream over stdio, a file descriptor/socket, TLS, // or a child process. class Stream { public: enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc }; Stream() = default; ~Stream(); Stream(Stream &&other) noexcept; Stream &operator=(Stream &&other) noexcept; Stream(const Stream &) = delete; Stream &operator=(const Stream &) = delete; static Stream stdio_stream(); static Stream fd_stream(Socket fd); static Stream tls_stream(Socket fd, void *ssl); static std::optional spawn_argv(const std::vector &argv); friend std::optional spawn_argv(const std::vector &argv); [[nodiscard]] Kind kind() const { return kind_; } [[nodiscard]] void *ssl() const { return ssl_; } [[nodiscard]] Socket fd() const { return fd_in_; } [[nodiscard]] bool valid() const { return open_; } // Returns the number of bytes read, 0 at clean end of stream, -1 on error. std::int64_t read(void *buffer, std::size_t count); bool write_all(Bytes data); bool write_all(std::string_view text) { return write_all(Bytes(reinterpret_cast(text.data()), text.size())); } void close(); private: Kind kind_ = Kind::Stdio; Socket fd_in_ = 0; Socket fd_out_ = 0; void *ssl_ = nullptr; #if defined(_WIN32) void *process_ = nullptr; std::uint32_t process_id_ = 0; #else int pid_ = 0; #endif bool open_ = false; }; // Run argv[0] with the given arguments. stdin/stdout are connected to the // stream; stderr is inherited. std::optional spawn_argv(const std::vector &argv); std::optional tcp_connect(std::string_view host, int port); Socket tcp_listen(int port, int backlog = 64); std::optional tcp_accept(Socket listener); void close_socket(Socket socket); void ignore_sigpipe(); fs::path self_exe(); std::string quote_shell(std::string_view word); std::string build_shell_command(const std::vector &parts); // --------------------------------------------------------------------------- // TLS 1.3 // --------------------------------------------------------------------------- void *tls_server_ctx(std::string_view cert_path, std::string_view key_path); void *tls_client_ctx(bool pinned); void *tls_accept(void *ctx, Socket fd); void *tls_connect(void *ctx, Socket fd, std::string_view host); bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len); bool tls_peer_sha256(void *ssl, std::uint8_t *out); void tls_free(void *ssl); void tls_ctx_free(void *ctx); std::string tls_error(); std::string to_hex(Bytes data); bool hex_equal(std::string_view a, std::string_view b); } // namespace vn::net