691 lines
18 KiB
C++
691 lines
18 KiB
C++
#include <Void/Net/Server.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <set>
|
|
#include <system_error>
|
|
|
|
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<unsigned char>(lhs)) ==
|
|
std::tolower(static_cast<unsigned char>(rhs));
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] std::optional<std::string_view>
|
|
find_header(const std::vector<Header>& 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<std::string> split_path(std::string_view path)
|
|
{
|
|
std::vector<std::string> 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<unsigned char>(value);
|
|
return std::isalnum(c) != 0 || value == '_';
|
|
});
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<std::vector<std::string>>
|
|
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<std::string, std::less<>> 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<RouteParameters>
|
|
match_route(const std::vector<std::string>& pattern,
|
|
const std::vector<std::string>& 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<std::string>& candidate,
|
|
const std::vector<std::string>& 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<std::string>& left,
|
|
const std::vector<std::string>& 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<std::string>
|
|
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<unsigned char>(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<unsigned char>((high << 4) | low);
|
|
index += 2;
|
|
}
|
|
if (value < 0x20 || value == 0x7f || value == '\\') {
|
|
return Void::Result::fail(
|
|
"Net::StaticFileResolver: unsafe path character");
|
|
}
|
|
decoded += static_cast<char>(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<char>(
|
|
std::tolower(static_cast<unsigned char>(value)));
|
|
});
|
|
return extension;
|
|
}
|
|
} // namespace
|
|
|
|
std::optional<std::string_view>
|
|
ServerRequest::header(std::string_view name) const noexcept
|
|
{
|
|
return find_header(headers, name);
|
|
}
|
|
|
|
std::optional<std::string_view>
|
|
ServerResponse::header(std::string_view name) const noexcept
|
|
{
|
|
return find_header(headers, name);
|
|
}
|
|
|
|
Void::Result::Result<void> 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<std::optional<ServerResponse>>
|
|
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<ServerResponse>{};
|
|
}
|
|
request.parameters = std::move(parameters);
|
|
auto response = handler(request);
|
|
if (!response) {
|
|
return Void::Result::fail(std::move(response).error());
|
|
}
|
|
return std::optional<ServerResponse>{std::move(*response)};
|
|
}
|
|
|
|
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";
|
|
}
|
|
|
|
Void::Result::Result<StaticFileResolver>
|
|
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");
|
|
}
|
|
return StaticFileResolver{std::move(canonical_root),
|
|
std::move(index_file)};
|
|
}
|
|
|
|
Void::Result::Result<std::optional<StaticFile>>
|
|
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<StaticFile>{};
|
|
}
|
|
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<StaticFile>{};
|
|
}
|
|
|
|
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>{
|
|
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<bool>
|
|
WebSocketSessions::open(std::shared_ptr<WebSocketConnection> connection)
|
|
{
|
|
if (!connection) {
|
|
return Void::Result::fail(
|
|
"Net::WebSocketSessions: connection is null");
|
|
}
|
|
|
|
std::function<void(const std::shared_ptr<WebSocketConnection>&)> 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<WebSocketConnection>
|
|
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<WebSocketConnection> connection;
|
|
std::function<void(const std::shared_ptr<WebSocketConnection>&,
|
|
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<const std::byte> message) const
|
|
{
|
|
std::shared_ptr<WebSocketConnection> connection;
|
|
std::function<void(const std::shared_ptr<WebSocketConnection>&,
|
|
std::span<const std::byte>)>
|
|
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<void(WebSocketConnectionId, const Void::Result::Error&)>
|
|
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<void(WebSocketConnectionId, const WebSocketClose&)>
|
|
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<WebSocketConnection> connection;
|
|
std::function<void(WebSocketConnectionId, const WebSocketClose&)>
|
|
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
|