1 parent
fa30098129
commit
8583a479dd
11 files changed
+1763
-129
No files matched your search
@@ -0,0 +1,690 @@
|
||||
#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
|
||||
@@ -0,0 +1,178 @@
|
||||
#include <Void/Security/Security.hpp>
|
||||
|
||||
#include <sodium.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Security
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct PasswordLimits {
|
||||
unsigned long long operations;
|
||||
std::size_t memory;
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> ensure_sodium()
|
||||
{
|
||||
static const bool initialized = sodium_init() >= 0;
|
||||
if (!initialized) {
|
||||
return Void::Result::fail(
|
||||
"Security: libsodium initialization failed");
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<PasswordLimits>
|
||||
password_limits(PasswordHashStrength strength) noexcept
|
||||
{
|
||||
switch (strength) {
|
||||
case PasswordHashStrength::Interactive:
|
||||
return PasswordLimits{crypto_pwhash_OPSLIMIT_INTERACTIVE,
|
||||
crypto_pwhash_MEMLIMIT_INTERACTIVE};
|
||||
case PasswordHashStrength::Moderate:
|
||||
return PasswordLimits{crypto_pwhash_OPSLIMIT_MODERATE,
|
||||
crypto_pwhash_MEMLIMIT_MODERATE};
|
||||
case PasswordHashStrength::Sensitive:
|
||||
return PasswordLimits{crypto_pwhash_OPSLIMIT_SENSITIVE,
|
||||
crypto_pwhash_MEMLIMIT_SENSITIVE};
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::array<unsigned char, crypto_generichash_BYTES>
|
||||
token_digest(std::string_view token) noexcept
|
||||
{
|
||||
std::array<unsigned char, crypto_generichash_BYTES> digest{};
|
||||
(void)crypto_generichash(
|
||||
digest.data(), digest.size(),
|
||||
reinterpret_cast<const unsigned char*>(token.data()),
|
||||
token.size(), nullptr, 0);
|
||||
return digest;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Result::Result<std::string> random_token(std::size_t entropy_bytes)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
if (entropy_bytes == 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: entropy must be greater than zero");
|
||||
}
|
||||
if (entropy_bytes >
|
||||
(std::numeric_limits<std::size_t>::max() - 2) / 4 * 3) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: entropy size is too large");
|
||||
}
|
||||
|
||||
std::vector<unsigned char> random(entropy_bytes);
|
||||
randombytes_buf(random.data(), random.size());
|
||||
|
||||
const auto encoded_size = sodium_base64_ENCODED_LEN(
|
||||
random.size(), sodium_base64_VARIANT_URLSAFE_NO_PADDING);
|
||||
std::string encoded(encoded_size, '\0');
|
||||
const auto* result = sodium_bin2base64(
|
||||
encoded.data(), encoded.size(), random.data(), random.size(),
|
||||
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
|
||||
sodium_memzero(random.data(), random.size());
|
||||
if (result == nullptr) {
|
||||
return Void::Result::fail(
|
||||
"Security::random_token: base64 encoding failed");
|
||||
}
|
||||
encoded.resize(std::strlen(encoded.c_str()));
|
||||
return encoded;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string> hash_token(std::string_view token)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
|
||||
const auto digest = token_digest(token);
|
||||
std::array<char, crypto_generichash_BYTES * 2 + 1> encoded{};
|
||||
(void)sodium_bin2hex(encoded.data(), encoded.size(), digest.data(),
|
||||
digest.size());
|
||||
return std::string{encoded.data(), encoded.size() - 1};
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verify_token(std::string_view token,
|
||||
std::string_view encoded_hash)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
|
||||
constexpr auto encoded_length = crypto_generichash_BYTES * 2;
|
||||
if (encoded_hash.size() != encoded_length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::array<unsigned char, crypto_generichash_BYTES> expected{};
|
||||
std::size_t decoded_length = 0;
|
||||
if (sodium_hex2bin(expected.data(), expected.size(),
|
||||
encoded_hash.data(), encoded_hash.size(), nullptr,
|
||||
&decoded_length, nullptr) != 0 ||
|
||||
decoded_length != expected.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto actual = token_digest(token);
|
||||
return sodium_memcmp(actual.data(), expected.data(), actual.size()) ==
|
||||
0;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string>
|
||||
hash_password(std::string_view password, PasswordHashStrength strength)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
if (password.size() > crypto_pwhash_PASSWD_MAX) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: password is too long");
|
||||
}
|
||||
|
||||
const auto limits = password_limits(strength);
|
||||
if (!limits) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: invalid strength");
|
||||
}
|
||||
|
||||
std::array<char, crypto_pwhash_STRBYTES> encoded{};
|
||||
if (crypto_pwhash_str_alg(
|
||||
encoded.data(), password.data(),
|
||||
static_cast<unsigned long long>(password.size()),
|
||||
limits->operations, limits->memory,
|
||||
crypto_pwhash_ALG_ARGON2ID13) != 0) {
|
||||
return Void::Result::fail(
|
||||
"Security::hash_password: Argon2id hashing failed");
|
||||
}
|
||||
return std::string{encoded.data()};
|
||||
}
|
||||
|
||||
Void::Result::Result<bool> verify_password(std::string_view password,
|
||||
std::string_view encoded_hash)
|
||||
{
|
||||
if (const auto initialized = ensure_sodium(); !initialized) {
|
||||
return Void::Result::fail(std::move(initialized).error());
|
||||
}
|
||||
if (password.size() > crypto_pwhash_PASSWD_MAX ||
|
||||
encoded_hash.empty() ||
|
||||
encoded_hash.find('\0') != std::string_view::npos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string terminated_hash{encoded_hash};
|
||||
return crypto_pwhash_str_verify(
|
||||
terminated_hash.c_str(), password.data(),
|
||||
static_cast<unsigned long long>(password.size())) == 0;
|
||||
}
|
||||
|
||||
} // namespace Void::Security
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(Security
|
||||
INTERNAL_DEPS Functional
|
||||
EXTERNAL_DEPS Sodium::Sodium
|
||||
)
|
||||
Reference in new issue
Block a user