#include #if !defined(_WIN32) #include #include #include #endif #include #include #include #include #include #include #include #include #include namespace Void::Net { namespace { [[nodiscard]] bool equal_ascii_case_insensitive(std::string_view left, std::string_view right) noexcept { return left.size() == right.size() && std::ranges::equal(left, right, [](char lhs, char rhs) { return std::tolower(static_cast(lhs)) == std::tolower(static_cast(rhs)); }); } [[nodiscard]] std::optional find_header(const std::vector
& headers, std::string_view name) noexcept { for (const auto& header : headers) { if (equal_ascii_case_insensitive(header.name, name)) { return header.value; } } return std::nullopt; } [[nodiscard]] std::string_view path_only(std::string_view path) noexcept { const auto end = path.find_first_of("?#"); return path.substr(0, end); } [[nodiscard]] std::vector split_path(std::string_view path) { std::vector segments; std::size_t begin = path.starts_with('/') ? 1 : 0; while (begin < path.size()) { const auto end = path.find('/', begin); const auto segment = path.substr(begin, end - begin); if (!segment.empty()) { segments.emplace_back(segment); } if (end == std::string_view::npos) { break; } begin = end + 1; } return segments; } [[nodiscard]] bool valid_parameter_name(std::string_view name) noexcept { return !name.empty() && std::ranges::all_of(name, [](char value) { const auto c = static_cast(value); return std::isalnum(c) != 0 || value == '_'; }); } [[nodiscard]] Void::Result::Result> compile_pattern(std::string_view pattern) { if (pattern.empty() || !pattern.starts_with('/') || pattern.find_first_of("?#") != std::string_view::npos) { return Void::Result::fail( "Net::Router: route patterns must be absolute URL paths"); } auto segments = split_path(pattern); std::set> names; for (std::size_t index = 0; index < segments.size(); ++index) { const auto& segment = segments[index]; if (!segment.starts_with(':') && !segment.starts_with('*')) { continue; } const auto name = std::string_view{segment}.substr(1); if (!valid_parameter_name(name)) { return Void::Result::fail( "Net::Router: invalid route parameter name"); } if (!names.emplace(name).second) { return Void::Result::fail( "Net::Router: duplicate route parameter name"); } if (segment.starts_with('*') && index + 1 != segments.size()) { return Void::Result::fail( "Net::Router: catch-all parameter must be final"); } } return segments; } [[nodiscard]] std::optional match_route(const std::vector& pattern, const std::vector& path) { RouteParameters parameters; std::size_t path_index = 0; for (const auto& segment : pattern) { if (segment.starts_with('*')) { std::string value; for (; path_index < path.size(); ++path_index) { if (!value.empty()) { value += '/'; } value += path[path_index]; } parameters.emplace(segment.substr(1), std::move(value)); return parameters; } if (path_index >= path.size()) { return std::nullopt; } if (segment.starts_with(':')) { parameters.emplace(segment.substr(1), path[path_index]); } else if (segment != path[path_index]) { return std::nullopt; } ++path_index; } if (path_index != path.size()) { return std::nullopt; } return parameters; } [[nodiscard]] int segment_specificity(std::string_view segment) noexcept { if (segment.starts_with('*')) { return 0; } if (segment.starts_with(':')) { return 1; } return 2; } [[nodiscard]] bool more_specific(const std::vector& candidate, const std::vector& current) noexcept { const auto shared = std::min(candidate.size(), current.size()); for (std::size_t index = 0; index < shared; ++index) { const auto candidate_rank = segment_specificity(candidate[index]); const auto current_rank = segment_specificity(current[index]); if (candidate_rank != current_rank) { return candidate_rank > current_rank; } } return candidate.size() > current.size(); } [[nodiscard]] bool same_route_shape(const std::vector& left, const std::vector& right) noexcept { if (left.size() != right.size()) { return false; } for (std::size_t index = 0; index < left.size(); ++index) { const auto left_rank = segment_specificity(left[index]); const auto right_rank = segment_specificity(right[index]); if (left_rank != right_rank || (left_rank == 2 && left[index] != right[index])) { return false; } } return true; } [[nodiscard]] int hex_value(char value) noexcept { if (value >= '0' && value <= '9') { return value - '0'; } if (value >= 'a' && value <= 'f') { return value - 'a' + 10; } if (value >= 'A' && value <= 'F') { return value - 'A' + 10; } return -1; } [[nodiscard]] Void::Result::Result decode_url_path(std::string_view request_path) { const auto path = path_only(request_path); if (path.empty() || !path.starts_with('/')) { return Void::Result::fail( "Net::StaticFileResolver: request path must be absolute"); } std::string decoded; decoded.reserve(path.size()); for (std::size_t index = 0; index < path.size(); ++index) { unsigned char value = static_cast(path[index]); if (value == '%') { if (index + 2 >= path.size()) { return Void::Result::fail("Net::StaticFileResolver: " "invalid percent encoding"); } const auto high = hex_value(path[index + 1]); const auto low = hex_value(path[index + 2]); if (high < 0 || low < 0) { return Void::Result::fail("Net::StaticFileResolver: " "invalid percent encoding"); } value = static_cast((high << 4) | low); index += 2; } if (value < 0x20 || value == 0x7f || value == '\\') { return Void::Result::fail( "Net::StaticFileResolver: unsafe path character"); } decoded += static_cast(value); } return decoded; } [[nodiscard]] bool path_is_within(const std::filesystem::path& root, const std::filesystem::path& candidate) noexcept { auto root_part = root.begin(); auto candidate_part = candidate.begin(); for (; root_part != root.end(); ++root_part, ++candidate_part) { if (candidate_part == candidate.end() || *root_part != *candidate_part) { return false; } } return true; } [[nodiscard]] std::string lowercase_extension(const std::filesystem::path& path) { auto extension = path.extension().string(); std::ranges::transform( extension, extension.begin(), [](char value) { return static_cast( std::tolower(static_cast(value))); }); return extension; } } // namespace std::optional ServerRequest::header(std::string_view name) const noexcept { return find_header(headers, name); } ServerResponse ServerResponse::from_file(std::filesystem::path path, std::string content_type, std::uint16_t status) { if (content_type.empty()) { content_type = std::string{content_type_for(path)}; } return ServerResponse{ .status = status, .headers = {Header{"Content-Type", std::move(content_type)}}, .body = {}, .file_body = std::move(path), }; } std::optional ServerResponse::header(std::string_view name) const noexcept { return find_header(headers, name); } Void::Result::Result Router::add(Method method, std::string pattern, RouteHandler handler) { if (!handler) { return Void::Result::fail("Net::Router: route handler is empty"); } auto segments = compile_pattern(pattern); if (!segments) { return Void::Result::fail(std::move(segments).error()); } std::unique_lock lock{mutex_}; const auto duplicate = std::ranges::find_if(routes_, [&](const Route& route) { return route.method == method && same_route_shape(route.segments, *segments); }); if (duplicate != routes_.end()) { return Void::Result::fail("Net::Router: duplicate route"); } routes_.push_back(Route{method, std::move(pattern), std::move(*segments), std::move(handler)}); return {}; } Void::Result::Result> Router::dispatch(ServerRequest request) const { if (request.path.empty() || !request.path.starts_with('/')) { return Void::Result::fail( "Net::Router: request path must be absolute"); } const auto path = split_path(path_only(request.path)); RouteHandler handler; RouteParameters parameters; { std::shared_lock lock{mutex_}; const Route* best_route = nullptr; for (const auto& route : routes_) { if (route.method != request.method) { continue; } auto matched = match_route(route.segments, path); if (!matched) { continue; } if (best_route == nullptr || more_specific(route.segments, best_route->segments)) { best_route = &route; parameters = std::move(*matched); } } if (best_route != nullptr) { handler = best_route->handler; } } if (!handler) { return std::optional{}; } request.parameters = std::move(parameters); auto response = handler(request); if (!response) { return Void::Result::fail(std::move(response).error()); } return std::optional{std::move(*response)}; } std::vector Router::allowed_methods(std::string_view path) const { if (path.empty() || !path.starts_with('/')) { return {}; } const auto segments = split_path(path_only(path)); std::vector methods; { std::shared_lock lock{mutex_}; for (const auto& route : routes_) { if (match_route(route.segments, segments).has_value() && std::ranges::find(methods, route.method) == methods.end()) { methods.push_back(route.method); } } } return methods; } std::size_t Router::size() const { std::shared_lock lock{mutex_}; return routes_.size(); } std::string_view content_type_for(const std::filesystem::path& path) { const auto extension = lowercase_extension(path); if (extension == ".html" || extension == ".htm") { return "text/html; charset=utf-8"; } if (extension == ".css") { return "text/css; charset=utf-8"; } if (extension == ".js" || extension == ".mjs") { return "text/javascript; charset=utf-8"; } if (extension == ".json" || extension == ".map") { return "application/json; charset=utf-8"; } if (extension == ".txt") { return "text/plain; charset=utf-8"; } if (extension == ".xml") { return "application/xml; charset=utf-8"; } if (extension == ".svg") { return "image/svg+xml"; } if (extension == ".png") { return "image/png"; } if (extension == ".jpg" || extension == ".jpeg") { return "image/jpeg"; } if (extension == ".gif") { return "image/gif"; } if (extension == ".webp") { return "image/webp"; } if (extension == ".ico") { return "image/x-icon"; } if (extension == ".wasm") { return "application/wasm"; } if (extension == ".woff") { return "font/woff"; } if (extension == ".woff2") { return "font/woff2"; } if (extension == ".ttf") { return "font/ttf"; } if (extension == ".mp3") { return "audio/mpeg"; } if (extension == ".ogg") { return "audio/ogg"; } if (extension == ".mp4") { return "video/mp4"; } if (extension == ".webm") { return "video/webm"; } return "application/octet-stream"; } OpenedStaticFile::OpenedStaticFile(int fd, std::filesystem::path relative_path, std::string_view content_type, std::uint64_t size) noexcept : fd_(fd), relative_path_(std::move(relative_path)), content_type_(content_type), size_(size) { } OpenedStaticFile::~OpenedStaticFile() noexcept { close(); } OpenedStaticFile::OpenedStaticFile(OpenedStaticFile&& other) noexcept : fd_(std::exchange(other.fd_, -1)), relative_path_(std::move(other.relative_path_)), content_type_(std::exchange(other.content_type_, {})), size_(std::exchange(other.size_, 0)) { } OpenedStaticFile& OpenedStaticFile::operator=(OpenedStaticFile&& other) noexcept { if (this != &other) { close(); fd_ = std::exchange(other.fd_, -1); relative_path_ = std::move(other.relative_path_); content_type_ = std::exchange(other.content_type_, {}); size_ = std::exchange(other.size_, 0); } return *this; } void OpenedStaticFile::close() noexcept { #if !defined(_WIN32) if (fd_ >= 0) { (void)::close(fd_); fd_ = -1; } #endif } Void::Result::Result OpenedStaticFile::read_all(std::uint64_t max_bytes) const { #if !defined(_WIN32) if (fd_ < 0) { return Void::Result::fail( "Net::OpenedStaticFile: file descriptor is closed"); } if (size_ > max_bytes) { return std::unexpected{make_net_error( NetErrorCode::payload_too_large, "Net::OpenedStaticFile: file size exceeds max_bytes")}; } std::string out; out.reserve(static_cast(size_)); std::array buf{}; std::uint64_t offset = 0; for (;;) { const ssize_t n = ::pread(fd_, buf.data(), buf.size(), static_cast(offset)); if (n < 0) { if (errno == EINTR) continue; return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net::OpenedStaticFile: pread failed: {}", std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } if (n == 0) { break; } const auto un = static_cast(n); if (un > max_bytes || offset > max_bytes - un) { return std::unexpected{make_net_error( NetErrorCode::payload_too_large, "Net::OpenedStaticFile: read exceeds max_bytes")}; } out.append(buf.data(), static_cast(n)); offset += un; } return out; #else (void)max_bytes; return Void::Result::fail( "Net::OpenedStaticFile: unsupported platform"); #endif } StaticFileResolver::DirHandle::~DirHandle() noexcept { #if !defined(_WIN32) if (fd >= 0) { (void)::close(fd); fd = -1; } #endif } Void::Result::Result StaticFileResolver::create(std::filesystem::path root, std::string index_file) { if (index_file.empty() || std::filesystem::path{index_file}.filename() != index_file || index_file == "." || index_file == "..") { return Void::Result::fail( "Net::StaticFileResolver: index file must be one filename"); } std::error_code error; auto canonical_root = std::filesystem::weakly_canonical(root, error); if (error || !std::filesystem::is_directory(canonical_root, error) || error) { return Void::Result::fail( "Net::StaticFileResolver: document root is not a directory"); } std::shared_ptr root_handle; #if !defined(_WIN32) const int dir_fd = ::open(canonical_root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (dir_fd < 0) { return std::unexpected{make_net_error( NetErrorCode::io_error, std::format( "Net::StaticFileResolver: cannot open root directory: {}", std::strerror(errno)), std::error_code{errno, std::generic_category()})}; } root_handle = std::make_shared(dir_fd); #endif return StaticFileResolver{std::move(canonical_root), std::move(index_file), std::move(root_handle)}; } Void::Result::Result> StaticFileResolver::open_safe(std::string_view request_path) const { #if !defined(_WIN32) if (!root_dir_ || root_dir_->fd < 0) { return Void::Result::fail( "Net::StaticFileResolver: root directory handle unavailable"); } auto decoded = decode_url_path(request_path); if (!decoded) { return Void::Result::fail(std::move(decoded).error()); } const auto segments = split_path(*decoded); for (const auto& seg : segments) { if (seg == "." || seg == ".." || seg.find('/') != std::string::npos) { return Void::Result::fail( "Net::StaticFileResolver: path traversal rejected"); } } struct ScopedFd { int fd{-1}; bool owned{false}; ~ScopedFd() noexcept { if (owned && fd >= 0) { (void)::close(fd); } } }; ScopedFd cur{root_dir_->fd, false}; std::filesystem::path rel_path; // Walk intermediate directories strictly via openat + O_NOFOLLOW. for (std::size_t i = 0; i + 1U < segments.size(); ++i) { const int next = ::openat(cur.fd, segments[i].c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (next < 0) { const int err = errno; if (err == ENOENT || err == ENOTDIR) { return std::optional{}; } if (err == ELOOP) { return Void::Result::fail( "Net::StaticFileResolver: symlink directory rejected"); } return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net::StaticFileResolver: openat dir failed: " "{}", std::strerror(err)), std::error_code{err, std::generic_category()})}; } if (cur.owned && cur.fd >= 0) { (void)::close(cur.fd); } cur.fd = next; cur.owned = true; rel_path /= segments[i]; } // Open leaf (or index_file_ if root or directory). int file_fd = -1; if (segments.empty()) { file_fd = ::openat(cur.fd, index_file_.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC); rel_path /= index_file_; } else { const std::string& leaf = segments.back(); file_fd = ::openat(cur.fd, leaf.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC); if (file_fd >= 0) { struct stat st{}; if (::fstat(file_fd, &st) == 0 && S_ISDIR(st.st_mode)) { const int idx_fd = ::openat( file_fd, index_file_.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC); (void)::close(file_fd); file_fd = idx_fd; rel_path /= leaf; rel_path /= index_file_; } else { rel_path /= leaf; } } else if (errno == EISDIR) { const int dir_fd = ::openat(cur.fd, leaf.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (dir_fd >= 0) { file_fd = ::openat(dir_fd, index_file_.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC); (void)::close(dir_fd); rel_path /= leaf; rel_path /= index_file_; } } } if (file_fd < 0) { const int err = errno; if (err == ENOENT || err == ENOTDIR) { return std::optional{}; } if (err == ELOOP) { return Void::Result::fail( "Net::StaticFileResolver: symlink file rejected"); } return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net::StaticFileResolver: openat file failed: {}", std::strerror(err)), std::error_code{err, std::generic_category()})}; } struct stat st{}; if (::fstat(file_fd, &st) != 0) { const int err = errno; (void)::close(file_fd); return std::unexpected{make_net_error( NetErrorCode::io_error, std::format("Net::StaticFileResolver: fstat failed: {}", std::strerror(err)), std::error_code{err, std::generic_category()})}; } if (!S_ISREG(st.st_mode)) { (void)::close(file_fd); return std::optional{}; } const auto ct = content_type_for(rel_path); return std::optional{OpenedStaticFile{ file_fd, std::move(rel_path), ct, static_cast(st.st_size)}}; #else (void)request_path; return Void::Result::fail( "Net::StaticFileResolver::open_safe: unsupported platform"); #endif } Void::Result::Result> StaticFileResolver::resolve(std::string_view request_path) const { auto decoded = decode_url_path(request_path); if (!decoded) { return Void::Result::fail(std::move(decoded).error()); } auto candidate = root_; for (const auto& segment : split_path(*decoded)) { if (segment == "." || segment == "..") { return Void::Result::fail( "Net::StaticFileResolver: path traversal rejected"); } candidate /= segment; } std::error_code error; candidate = std::filesystem::weakly_canonical(candidate, error); if (error) { return Void::Result::fail( "Net::StaticFileResolver: path canonicalization failed"); } if (!path_is_within(root_, candidate)) { return Void::Result::fail( "Net::StaticFileResolver: path escapes document root"); } if (!std::filesystem::exists(candidate, error)) { if (error) { return Void::Result::fail( "Net::StaticFileResolver: file status failed"); } return std::optional{}; } if (std::filesystem::is_directory(candidate, error)) { candidate = std::filesystem::weakly_canonical( candidate / index_file_, error); if (error || !path_is_within(root_, candidate)) { return Void::Result::fail( "Net::StaticFileResolver: unsafe index path"); } } if (!std::filesystem::is_regular_file(candidate, error)) { if (error) { return Void::Result::fail( "Net::StaticFileResolver: file status failed"); } return std::optional{}; } const auto size = std::filesystem::file_size(candidate, error); if (error) { return Void::Result::fail( "Net::StaticFileResolver: file size failed"); } const auto content_type = content_type_for(candidate); return std::optional{ StaticFile{std::move(candidate), content_type, size}}; } WebSocketSessions::~WebSocketSessions() noexcept { try { auto connections = take_all(true); const WebSocketClose close{1001, "server shutdown"}; for (const auto& [id, connection] : connections) { (void)id; connection->close(close); } } catch (...) { } } void WebSocketSessions::set_events(WebSocketEvents events) { std::lock_guard lock{mutex_}; events_ = std::move(events); } Void::Result::Result WebSocketSessions::open(std::shared_ptr connection) { if (!connection) { return Void::Result::fail( "Net::WebSocketSessions: connection is null"); } std::function&)> opened; { std::lock_guard lock{mutex_}; if (!accepting_) { return false; } if (!connections_.emplace(connection->id(), connection).second) { return false; } opened = events_.opened; } if (opened) { opened(connection); } return true; } std::shared_ptr WebSocketSessions::find(WebSocketConnectionId id) const { std::lock_guard lock{mutex_}; const auto found = connections_.find(id); return found == connections_.end() ? nullptr : found->second; } bool WebSocketSessions::contains(WebSocketConnectionId id) const { std::lock_guard lock{mutex_}; return connections_.contains(id); } std::size_t WebSocketSessions::size() const { std::lock_guard lock{mutex_}; return connections_.size(); } bool WebSocketSessions::receive_text(WebSocketConnectionId id, std::string_view message) const { std::shared_ptr connection; std::function&, std::string_view)> callback; { std::lock_guard lock{mutex_}; const auto found = connections_.find(id); if (found == connections_.end()) { return false; } connection = found->second; callback = events_.text; } if (callback) { callback(connection, message); } return true; } bool WebSocketSessions::receive_binary( WebSocketConnectionId id, std::span message) const { std::shared_ptr connection; std::function&, std::span)> callback; { std::lock_guard lock{mutex_}; const auto found = connections_.find(id); if (found == connections_.end()) { return false; } connection = found->second; callback = events_.binary; } if (callback) { callback(connection, message); } return true; } bool WebSocketSessions::fail(WebSocketConnectionId id, const Void::Result::Error& error) const { std::function callback; { std::lock_guard lock{mutex_}; if (!connections_.contains(id)) { return false; } callback = events_.error; } if (callback) { callback(id, error); } return true; } bool WebSocketSessions::disconnect(WebSocketConnectionId id, WebSocketClose close) { return remove(id, close, false); } bool WebSocketSessions::close(WebSocketConnectionId id, WebSocketClose close) { return remove(id, close, true); } std::size_t WebSocketSessions::shutdown(WebSocketClose close) { auto connections = take_all(true); std::function closed; { std::lock_guard lock{mutex_}; closed = events_.closed; } for (const auto& [id, connection] : connections) { (void)id; connection->close(close); } if (closed) { for (const auto& [id, connection] : connections) { (void)connection; closed(id, close); } } return connections.size(); } bool WebSocketSessions::remove(WebSocketConnectionId id, const WebSocketClose& close, bool close_transport) { std::shared_ptr connection; std::function closed; { std::lock_guard lock{mutex_}; const auto found = connections_.find(id); if (found == connections_.end()) { return false; } connection = std::move(found->second); connections_.erase(found); closed = events_.closed; } if (close_transport) { connection->close(close); } if (closed) { closed(id, close); } return true; } WebSocketSessions::Connections WebSocketSessions::take_all(bool stop_accepting) { std::lock_guard lock{mutex_}; if (stop_accepting) { accepting_ = false; } Connections connections; connections.swap(connections_); return connections; } } // namespace Void::Net