#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Net { using RouteParameters = std::map>; struct ServerRequest { Method method{Method::Get}; std::string path; std::vector
headers; std::string body; RouteParameters parameters; std::string query{}; [[nodiscard]] std::optional header(std::string_view name) const noexcept; }; struct ServerResponse { std::uint16_t status{200}; std::vector
headers; std::string body; std::optional file_body{}; [[nodiscard]] static ServerResponse from_file(std::filesystem::path path, std::string content_type = {}, std::uint16_t status = 200); [[nodiscard]] std::optional header(std::string_view name) const noexcept; }; using RouteResult = Void::Result::Result; using RouteHandler = std::function; /// A transport-neutral method/path router. Patterns support exact segments, /// `:name` parameters, and a final `*name` catch-all. Route registration /// and dispatch are thread-safe; handlers run without the router lock held. class Router { public: Router() = default; Router(const Router&) = delete; Router& operator=(const Router&) = delete; Router(Router&&) = delete; Router& operator=(Router&&) = delete; [[nodiscard]] Void::Result::Result add(Method method, std::string pattern, RouteHandler handler); /// A successful empty optional means that no route matched. [[nodiscard]] Void::Result::Result> dispatch(ServerRequest request) const; [[nodiscard]] std::vector allowed_methods(std::string_view path) const; [[nodiscard]] std::size_t size() const; private: struct Route { Method method; std::string pattern; std::vector segments; RouteHandler handler; }; mutable std::shared_mutex mutex_; std::vector routes_; }; struct StaticFile { std::filesystem::path path; std::string_view content_type; std::uintmax_t size{}; }; /// Move-only RAII handle for a regular file opened beneath a pinned root /// directory descriptor using `openat(..., O_NOFOLLOW)` (zero TOCTOU). class OpenedStaticFile final { public: OpenedStaticFile() noexcept = default; OpenedStaticFile(int fd, std::filesystem::path relative_path, std::string_view content_type, std::uint64_t size) noexcept; ~OpenedStaticFile() noexcept; OpenedStaticFile(OpenedStaticFile&& other) noexcept; OpenedStaticFile& operator=(OpenedStaticFile&& other) noexcept; OpenedStaticFile(const OpenedStaticFile&) = delete; OpenedStaticFile& operator=(const OpenedStaticFile&) = delete; [[nodiscard]] bool valid() const noexcept { return fd_ >= 0; } [[nodiscard]] int native_handle() const noexcept { return fd_; } [[nodiscard]] const std::filesystem::path& relative_path() const noexcept { return relative_path_; } [[nodiscard]] std::string_view content_type() const noexcept { return content_type_; } [[nodiscard]] std::uint64_t size() const noexcept { return size_; } [[nodiscard]] Void::Result::Result read_all(std::uint64_t max_bytes = 64ULL * 1024 * 1024) const; void close() noexcept; private: int fd_{-1}; std::filesystem::path relative_path_{}; std::string_view content_type_{}; std::uint64_t size_{0}; }; [[nodiscard]] std::string_view content_type_for(const std::filesystem::path& path); /// Resolves URL paths beneath one canonical document root. Percent-decoded /// traversal, backslashes, control characters, and symlink escapes are /// rejected. Missing files are represented by a successful empty optional. class StaticFileResolver { public: [[nodiscard]] static Void::Result::Result create(std::filesystem::path root, std::string index_file = "index.html"); [[nodiscard]] Void::Result::Result> resolve(std::string_view request_path) const; /// Descriptor-pinned open beneath the retained root directory /// descriptor (`openat` + `O_NOFOLLOW` per component). Rejects /// symlinks, traversal, and non-regular files without TOCTOU races. [[nodiscard]] Void::Result::Result> open_safe(std::string_view request_path) const; [[nodiscard]] const std::filesystem::path& root() const noexcept { return root_; } private: struct DirHandle { int fd{-1}; explicit DirHandle(int d) noexcept : fd(d) {} ~DirHandle() noexcept; DirHandle(const DirHandle&) = delete; DirHandle& operator=(const DirHandle&) = delete; }; StaticFileResolver(std::filesystem::path root, std::string index_file, std::shared_ptr root_dir) : root_(std::move(root)), index_file_(std::move(index_file)), root_dir_(std::move(root_dir)) { } std::filesystem::path root_; std::string index_file_; std::shared_ptr root_dir_; }; struct WebSocketConnectionId { std::uint64_t value{}; auto operator<=>(const WebSocketConnectionId&) const = default; }; struct WebSocketClose { std::uint16_t code{1000}; std::string reason; }; /// Implemented by the concrete WebSocket transport owned by an HTTP server. class WebSocketConnection { public: virtual ~WebSocketConnection() = default; [[nodiscard]] virtual WebSocketConnectionId id() const noexcept = 0; [[nodiscard]] virtual Void::Result::Result send_text(std::string_view message) = 0; [[nodiscard]] virtual Void::Result::Result send_binary(std::span message) = 0; virtual void close(const WebSocketClose& close) noexcept = 0; }; struct WebSocketEvents { std::function&)> opened; std::function&, std::string_view)> text; std::function&, std::span)> binary; std::function closed; std::function error; }; /// Thread-safe connection ownership and lifecycle dispatch. All callbacks /// and transport close operations run without the registry lock held. Call /// shutdown() for close callbacks; destruction performs a best-effort close /// without invoking user code. class WebSocketSessions { public: WebSocketSessions() = default; explicit WebSocketSessions(WebSocketEvents events) : events_(std::move(events)) { } ~WebSocketSessions() noexcept; WebSocketSessions(const WebSocketSessions&) = delete; WebSocketSessions& operator=(const WebSocketSessions&) = delete; WebSocketSessions(WebSocketSessions&&) = delete; WebSocketSessions& operator=(WebSocketSessions&&) = delete; void set_events(WebSocketEvents events); /// Register a transport connection and emit `opened`. Returns false /// for a duplicate connection ID. [[nodiscard]] Void::Result::Result open(std::shared_ptr connection); [[nodiscard]] std::shared_ptr find(WebSocketConnectionId id) const; [[nodiscard]] bool contains(WebSocketConnectionId id) const; [[nodiscard]] std::size_t size() const; [[nodiscard]] bool receive_text(WebSocketConnectionId id, std::string_view message) const; [[nodiscard]] bool receive_binary(WebSocketConnectionId id, std::span message) const; [[nodiscard]] bool fail(WebSocketConnectionId id, const Void::Result::Error& error) const; /// Record a transport-initiated close without closing it again. [[nodiscard]] bool disconnect(WebSocketConnectionId id, WebSocketClose close = {}); /// Remove and actively close one connection. [[nodiscard]] bool close(WebSocketConnectionId id, WebSocketClose close = {}); /// Remove and actively close every connection. Returns the count. std::size_t shutdown(WebSocketClose close = {1001, "server shutdown"}); private: using Connections = std::map>; [[nodiscard]] bool remove(WebSocketConnectionId id, const WebSocketClose& close, bool close_transport); [[nodiscard]] Connections take_all(bool stop_accepting = false); mutable std::mutex mutex_; Connections connections_; WebSocketEvents events_; bool accepting_{true}; }; } // namespace Void::Net