feat(net): complete P2 M-NET-01..05 codec, pool, safe static open, redirects, and RFC 6455 WebSocket
This commit is contained in:
1 parent
700024a24d
commit
86d777eae6
14 files changed
+4346
-19
No files matched your search
+54
-15
@@ -917,9 +917,15 @@ namespace Void::Net
|
||||
HttpClient::send(const Request& req) const
|
||||
{
|
||||
std::string target_url = req.url;
|
||||
Method active_method = req.method;
|
||||
std::optional<std::string> active_body = req.body;
|
||||
std::vector<Header> active_headers = req.headers;
|
||||
int redirects = 0;
|
||||
|
||||
const auto overall_start = std::chrono::steady_clock::now();
|
||||
const bool has_deadline = req.timeout > std::chrono::seconds::zero();
|
||||
const auto overall_deadline = overall_start + req.timeout;
|
||||
|
||||
while (true) {
|
||||
const auto url = Url::parse(target_url);
|
||||
if (!url) {
|
||||
@@ -928,11 +934,25 @@ namespace Void::Net
|
||||
std::format("Net: invalid URL '{}'",
|
||||
sanitize_url_for_log(target_url)))};
|
||||
}
|
||||
std::chrono::seconds remaining_timeout = req.timeout;
|
||||
if (has_deadline) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now >= overall_deadline) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::timeout,
|
||||
std::format("Net: request to '{}' timed out across "
|
||||
"redirects",
|
||||
sanitize_url_for_log(target_url)))};
|
||||
}
|
||||
const auto rem_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
overall_deadline - now);
|
||||
remaining_timeout = std::chrono::seconds{
|
||||
std::max<long long>(1, (rem_ms.count() + 999) / 1000)};
|
||||
}
|
||||
bool cancelled = false;
|
||||
bool timed_out = false;
|
||||
try {
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
|
||||
asio::io_context ioc;
|
||||
ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file);
|
||||
|
||||
@@ -945,26 +965,26 @@ namespace Void::Net
|
||||
asio::connect(socket, resolver.resolve(
|
||||
m_proxy.host,
|
||||
std::to_string(m_proxy.port)));
|
||||
DeadlineGuard deadline{socket, req.timeout};
|
||||
DeadlineGuard deadline{socket, remaining_timeout};
|
||||
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
||||
socks5_connect(socket, *url, m_proxy);
|
||||
response = finish(socket, tls, ctx, *url, req.method,
|
||||
active_headers, req.body,
|
||||
response = finish(socket, tls, ctx, *url, active_method,
|
||||
active_headers, active_body,
|
||||
m_user_agent, m_max_body,
|
||||
m_verify_tls);
|
||||
} else {
|
||||
if (url->is_tls) {
|
||||
http_connect_tunnel(socket, *url, m_proxy);
|
||||
response = finish(socket, tls, ctx, *url,
|
||||
req.method, active_headers,
|
||||
req.body, m_user_agent,
|
||||
active_method, active_headers,
|
||||
active_body, m_user_agent,
|
||||
m_max_body, m_verify_tls);
|
||||
} else {
|
||||
const std::string absolute = std::format(
|
||||
"{}://{}{}", url->scheme, url->host,
|
||||
url->target);
|
||||
auto rq = build_request(*url, req.method,
|
||||
active_headers, req.body,
|
||||
auto rq = build_request(*url, active_method,
|
||||
active_headers, active_body,
|
||||
m_user_agent, absolute);
|
||||
if (m_proxy.has_auth()) {
|
||||
const auto enc = Void::Encoding::Base64::encode(
|
||||
@@ -981,17 +1001,21 @@ namespace Void::Net
|
||||
} else {
|
||||
asio::connect(socket,
|
||||
resolver.resolve(url->host, url->port));
|
||||
DeadlineGuard deadline{socket, req.timeout};
|
||||
DeadlineGuard deadline{socket, remaining_timeout};
|
||||
response =
|
||||
finish(socket, tls, ctx, *url, req.method,
|
||||
active_headers, req.body, m_user_agent,
|
||||
finish(socket, tls, ctx, *url, active_method,
|
||||
active_headers, active_body, m_user_agent,
|
||||
m_max_body, m_verify_tls);
|
||||
timed_out = deadline.timed_out();
|
||||
cancelled = deadline.cancelled();
|
||||
}
|
||||
|
||||
if (m_max_redirects > 0 && response.status >= 300 &&
|
||||
response.status < 400 && redirects < m_max_redirects) {
|
||||
const bool is_redirect_status =
|
||||
response.status == 301 || response.status == 302 ||
|
||||
response.status == 303 || response.status == 307 ||
|
||||
response.status == 308;
|
||||
if (m_max_redirects > 0 && is_redirect_status &&
|
||||
redirects < m_max_redirects) {
|
||||
if (auto loc = response.header("location")) {
|
||||
const std::string next_url =
|
||||
resolve_redirect(*url, *loc);
|
||||
@@ -1011,6 +1035,21 @@ namespace Void::Net
|
||||
if (!same_origin(*url, *next_parsed)) {
|
||||
strip_sensitive_headers(active_headers);
|
||||
}
|
||||
// RFC 9110 §15.4.4: 303 changes non-HEAD to GET and
|
||||
// drops body + representation headers.
|
||||
if (response.status == 303 &&
|
||||
active_method != Method::Head) {
|
||||
active_method = Method::Get;
|
||||
active_body.reset();
|
||||
std::erase_if(active_headers, [](const Header& h) {
|
||||
return equal_ascii_ci(h.name,
|
||||
"Content-Length") ||
|
||||
equal_ascii_ci(h.name,
|
||||
"Content-Type") ||
|
||||
equal_ascii_ci(h.name,
|
||||
"Transfer-Encoding");
|
||||
});
|
||||
}
|
||||
target_url = next_url;
|
||||
++redirects;
|
||||
continue;
|
||||
@@ -1019,7 +1058,7 @@ namespace Void::Net
|
||||
|
||||
response.elapsed =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - start);
|
||||
std::chrono::steady_clock::now() - overall_start);
|
||||
return response;
|
||||
} catch (const TlsError& e) {
|
||||
return std::unexpected{make_net_error(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -882,6 +882,138 @@ namespace Void::Net
|
||||
std::atomic<bool> finished{false};
|
||||
std::thread thread{};
|
||||
};
|
||||
|
||||
struct WebSocketRoute {
|
||||
std::string pattern;
|
||||
std::vector<std::string> segments;
|
||||
WebSocketSessions* sessions{nullptr};
|
||||
WebSocketUpgradeOptions options{};
|
||||
};
|
||||
|
||||
class TcpWebSocketConnection final : public WebSocketConnection
|
||||
{
|
||||
public:
|
||||
|
||||
TcpWebSocketConnection(WebSocketConnectionId id, int fd,
|
||||
WebSocketLimits limits) noexcept
|
||||
: m_id(id), m_fd(fd), m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] WebSocketConnectionId id() const noexcept override
|
||||
{
|
||||
return m_id;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_text(std::string_view message) override
|
||||
{
|
||||
if (!is_valid_utf8(message)) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::WebSocket: invalid UTF-8 in server text")};
|
||||
}
|
||||
if (message.size() > m_limits.max_message_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::WebSocket: message exceeds max_message_bytes")};
|
||||
}
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Text;
|
||||
f.masked = false;
|
||||
f.payload.resize(message.size());
|
||||
if (!message.empty()) {
|
||||
std::memcpy(f.payload.data(), message.data(),
|
||||
message.size());
|
||||
}
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_binary(std::span<const std::byte> message) override
|
||||
{
|
||||
if (message.size() > m_limits.max_message_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::WebSocket: binary message exceeds limit")};
|
||||
}
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Binary;
|
||||
f.masked = false;
|
||||
f.payload.assign(message.begin(), message.end());
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_pong(std::span<const std::byte> payload)
|
||||
{
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Pong;
|
||||
f.masked = false;
|
||||
f.payload.assign(payload.begin(), payload.end());
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
void close(const WebSocketClose& close_info) noexcept override
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
if (m_closed || m_fd < 0) {
|
||||
m_closed = true;
|
||||
return;
|
||||
}
|
||||
m_closed = true;
|
||||
if (!m_close_sent) {
|
||||
m_close_sent = true;
|
||||
auto cf = encode_websocket_close_frame(close_info, false);
|
||||
if (cf.has_value()) {
|
||||
(void)send_all(m_fd, *cf,
|
||||
std::chrono::milliseconds{500});
|
||||
}
|
||||
}
|
||||
(void)::shutdown(m_fd, SHUT_RDWR);
|
||||
}
|
||||
|
||||
void detach_fd() noexcept
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
m_closed = true;
|
||||
m_fd = -1;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_closed() const noexcept
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
return m_closed || m_fd < 0;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_frame(const WebSocketFrame& frame)
|
||||
{
|
||||
auto encoded = encode_websocket_frame(frame);
|
||||
if (!encoded.has_value()) {
|
||||
return std::unexpected{std::move(encoded.error())};
|
||||
}
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
if (m_closed || m_fd < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocket: connection closed")};
|
||||
}
|
||||
return send_all(m_fd, *encoded, m_limits.io_timeout);
|
||||
}
|
||||
|
||||
WebSocketConnectionId m_id{};
|
||||
mutable std::mutex m_io_mutex{};
|
||||
int m_fd{-1};
|
||||
bool m_closed{false};
|
||||
bool m_close_sent{false};
|
||||
WebSocketLimits m_limits{};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
struct HttpServer::Impl {
|
||||
@@ -891,6 +1023,8 @@ namespace Void::Net
|
||||
|
||||
mutable std::shared_mutex stream_mutex{};
|
||||
std::vector<StreamingRoute> streaming_routes{};
|
||||
std::vector<WebSocketRoute> ws_routes{};
|
||||
std::atomic<std::uint64_t> next_ws_id{1};
|
||||
|
||||
std::atomic<bool> running{false};
|
||||
std::atomic<bool> stopping{false};
|
||||
@@ -958,6 +1092,157 @@ namespace Void::Net
|
||||
best->handler, std::move(best_params)};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<WebSocketRoute>
|
||||
match_websocket(std::string_view path_view) const
|
||||
{
|
||||
const auto segments = split_path(path_view);
|
||||
std::shared_lock lock{stream_mutex};
|
||||
const WebSocketRoute* best = nullptr;
|
||||
for (const auto& r : ws_routes) {
|
||||
if (!match_segments(r.segments, segments).has_value()) {
|
||||
continue;
|
||||
}
|
||||
if (best == nullptr ||
|
||||
more_specific_route(r.segments, best->segments)) {
|
||||
best = &r;
|
||||
}
|
||||
}
|
||||
if (best == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return *best;
|
||||
}
|
||||
|
||||
void run_websocket_session(int fd, const WebSocketRoute& route,
|
||||
const WebSocketUpgradeHandshake& hs,
|
||||
std::string& rx_buf,
|
||||
std::size_t& rx_off)
|
||||
{
|
||||
std::string resp = std::format(
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: {}\r\n",
|
||||
hs.accept_key);
|
||||
if (hs.selected_subprotocol.has_value()) {
|
||||
resp += std::format("Sec-WebSocket-Protocol: {}\r\n",
|
||||
*hs.selected_subprotocol);
|
||||
}
|
||||
resp += "\r\n";
|
||||
if (!send_str(fd, resp, options.write_timeout).has_value()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const WebSocketConnectionId cid{
|
||||
next_ws_id.fetch_add(1, std::memory_order_relaxed)};
|
||||
auto conn = std::make_shared<TcpWebSocketConnection>(
|
||||
cid, fd, route.options.limits);
|
||||
auto opened = route.sessions->open(conn);
|
||||
if (!opened.has_value() || !(*opened)) {
|
||||
conn->close({1001, "session rejected"});
|
||||
conn->detach_fd();
|
||||
return;
|
||||
}
|
||||
|
||||
WebSocketDecoder decoder{true, route.options.limits};
|
||||
WebSocketClose final_close{1000, ""};
|
||||
bool protocol_failed = false;
|
||||
|
||||
auto process_messages =
|
||||
[&](const std::vector<WebSocketMessage>& messages) -> bool {
|
||||
for (const auto& msg : messages) {
|
||||
switch (msg.opcode) {
|
||||
case WebSocketOpcode::Text:
|
||||
(void)route.sessions->receive_text(
|
||||
cid, msg.text_view());
|
||||
break;
|
||||
case WebSocketOpcode::Binary:
|
||||
(void)route.sessions->receive_binary(
|
||||
cid, msg.payload);
|
||||
break;
|
||||
case WebSocketOpcode::Ping:
|
||||
if (!conn->send_pong(msg.payload).has_value()) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case WebSocketOpcode::Pong:
|
||||
break;
|
||||
case WebSocketOpcode::Close:
|
||||
final_close = msg.close_info.value_or(
|
||||
WebSocketClose{1000, ""});
|
||||
conn->close(final_close);
|
||||
return false;
|
||||
case WebSocketOpcode::Continuation:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return !conn->is_closed();
|
||||
};
|
||||
|
||||
bool active = true;
|
||||
if (rx_off < rx_buf.size()) {
|
||||
const auto tail = std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(rx_buf.data()) +
|
||||
rx_off,
|
||||
rx_buf.size() - rx_off};
|
||||
std::vector<WebSocketMessage> msgs;
|
||||
auto dr = decoder.feed(tail, msgs);
|
||||
rx_buf.clear();
|
||||
rx_off = 0;
|
||||
if (!dr.has_value()) {
|
||||
protocol_failed = true;
|
||||
(void)route.sessions->fail(cid, dr.error());
|
||||
final_close = {1002, "protocol error"};
|
||||
conn->close(final_close);
|
||||
active = false;
|
||||
} else {
|
||||
active = process_messages(msgs);
|
||||
}
|
||||
}
|
||||
|
||||
std::array<char, 8192> buf{};
|
||||
while (active && !stopping.load(std::memory_order_acquire) &&
|
||||
!conn->is_closed()) {
|
||||
auto nr = recv_slice(fd, buf, stopping,
|
||||
route.options.limits.io_timeout);
|
||||
if (!nr.has_value()) {
|
||||
if (stopping.load(std::memory_order_acquire)) {
|
||||
final_close = {1001, "server shutdown"};
|
||||
conn->close(final_close);
|
||||
} else if (nr.error().kind() !=
|
||||
Void::Result::ErrorKind::cancelled) {
|
||||
(void)route.sessions->fail(cid, nr.error());
|
||||
final_close = {1006, "transport error"};
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (*nr == 0) {
|
||||
if (!decoder.close_received()) {
|
||||
final_close = {1006, "peer closed"};
|
||||
}
|
||||
break;
|
||||
}
|
||||
std::vector<WebSocketMessage> msgs;
|
||||
auto dr = decoder.feed(
|
||||
std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(buf.data()),
|
||||
*nr},
|
||||
msgs);
|
||||
if (!dr.has_value()) {
|
||||
protocol_failed = true;
|
||||
(void)route.sessions->fail(cid, dr.error());
|
||||
final_close = {1002, "protocol error"};
|
||||
conn->close(final_close);
|
||||
break;
|
||||
}
|
||||
active = process_messages(msgs);
|
||||
}
|
||||
|
||||
(void)protocol_failed;
|
||||
conn->detach_fd();
|
||||
(void)route.sessions->disconnect(cid, final_close);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<Method>
|
||||
collect_allowed_methods(std::string_view path_view) const
|
||||
{
|
||||
@@ -1289,6 +1574,26 @@ namespace Void::Net
|
||||
keep_alive = false;
|
||||
}
|
||||
|
||||
// 3b. Check RFC 6455 WebSocket upgrade route.
|
||||
if (auto ws_match = match_websocket(raw_path);
|
||||
ws_match.has_value()) {
|
||||
ServerRequest ws_req;
|
||||
ws_req.method = *method_opt;
|
||||
ws_req.path = std::string{raw_path};
|
||||
ws_req.headers = std::move(headers);
|
||||
ws_req.query = std::string{raw_query};
|
||||
auto hs = validate_websocket_upgrade_request(
|
||||
ws_req, ws_match->options);
|
||||
if (!hs.has_value()) {
|
||||
send_error_close(fd_guard.get(), 400,
|
||||
"Bad Request");
|
||||
break;
|
||||
}
|
||||
run_websocket_session(fd_guard.get(), *ws_match, *hs,
|
||||
rx_buf, rx_off);
|
||||
break;
|
||||
}
|
||||
|
||||
// 4. Check streaming route vs buffered Router.
|
||||
auto streaming_match =
|
||||
match_streaming(*method_opt, raw_path);
|
||||
@@ -1681,6 +1986,31 @@ namespace Void::Net
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
HttpServer::add_websocket_route(std::string pattern,
|
||||
WebSocketSessions& sessions,
|
||||
WebSocketUpgradeOptions options)
|
||||
{
|
||||
auto compiled = compile_route_pattern(pattern);
|
||||
if (!compiled.has_value()) {
|
||||
return std::unexpected{std::move(compiled.error())};
|
||||
}
|
||||
std::unique_lock lock{m_impl->stream_mutex};
|
||||
const auto dup = std::ranges::find_if(
|
||||
m_impl->ws_routes, [&](const WebSocketRoute& r) {
|
||||
return same_route_shape(r.segments, *compiled);
|
||||
});
|
||||
if (dup != m_impl->ws_routes.end()) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::HttpServer: duplicate WebSocket route")};
|
||||
}
|
||||
m_impl->ws_routes.push_back(WebSocketRoute{
|
||||
std::move(pattern), std::move(*compiled), &sessions,
|
||||
std::move(options)});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> HttpServer::start()
|
||||
{
|
||||
if (m_impl->running.load(std::memory_order_acquire)) {
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
#include <Void/Net/Pool.hpp>
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
struct ConnectionPool::State {
|
||||
struct IdleEntry {
|
||||
std::unique_ptr<PooledConnection> conn;
|
||||
Void::Time::MonotonicClock::time_point idle_since;
|
||||
};
|
||||
|
||||
PoolLimits limits{};
|
||||
const Void::Time::MonotonicClock* clock{nullptr};
|
||||
|
||||
mutable std::mutex mutex{};
|
||||
bool shut_down{false};
|
||||
std::size_t total_connections{0};
|
||||
std::size_t active_leases{0};
|
||||
std::size_t idle_connections{0};
|
||||
std::uint64_t total_acquires{0};
|
||||
std::uint64_t idle_hits{0};
|
||||
std::uint64_t idle_evictions{0};
|
||||
std::uint64_t closed_dirty{0};
|
||||
std::map<PoolKey, std::size_t> per_origin_count{};
|
||||
std::map<PoolKey, std::deque<IdleEntry>> idle_by_key{};
|
||||
|
||||
void evict_expired_locked(
|
||||
Void::Time::MonotonicClock::time_point now,
|
||||
std::vector<std::unique_ptr<PooledConnection>>& to_close)
|
||||
{
|
||||
for (auto it = idle_by_key.begin(); it != idle_by_key.end();) {
|
||||
auto& dq = it->second;
|
||||
while (!dq.empty()) {
|
||||
const bool expired =
|
||||
limits.idle_timeout >
|
||||
std::chrono::milliseconds::zero() &&
|
||||
(now - dq.front().idle_since) >=
|
||||
limits.idle_timeout;
|
||||
const bool closed =
|
||||
!dq.front().conn || !dq.front().conn->is_open();
|
||||
if (!expired && !closed) {
|
||||
break;
|
||||
}
|
||||
to_close.push_back(std::move(dq.front().conn));
|
||||
dq.pop_front();
|
||||
--idle_connections;
|
||||
--total_connections;
|
||||
++idle_evictions;
|
||||
auto oit = per_origin_count.find(it->first);
|
||||
if (oit != per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dq.empty()) {
|
||||
it = idle_by_key.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void evict_oldest_idle_locked(
|
||||
std::vector<std::unique_ptr<PooledConnection>>& to_close)
|
||||
{
|
||||
auto oldest_it = idle_by_key.end();
|
||||
for (auto it = idle_by_key.begin(); it != idle_by_key.end();
|
||||
++it) {
|
||||
if (it->second.empty()) {
|
||||
continue;
|
||||
}
|
||||
if (oldest_it == idle_by_key.end() ||
|
||||
it->second.front().idle_since <
|
||||
oldest_it->second.front().idle_since) {
|
||||
oldest_it = it;
|
||||
}
|
||||
}
|
||||
if (oldest_it == idle_by_key.end()) {
|
||||
return;
|
||||
}
|
||||
to_close.push_back(std::move(oldest_it->second.front().conn));
|
||||
oldest_it->second.pop_front();
|
||||
--idle_connections;
|
||||
--total_connections;
|
||||
++idle_evictions;
|
||||
auto oit = per_origin_count.find(oldest_it->first);
|
||||
if (oit != per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
if (oldest_it->second.empty()) {
|
||||
idle_by_key.erase(oldest_it);
|
||||
}
|
||||
}
|
||||
|
||||
void return_lease(const PoolKey& key,
|
||||
std::unique_ptr<PooledConnection> conn,
|
||||
bool reusable) noexcept
|
||||
{
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{mutex};
|
||||
const auto now = clock->now();
|
||||
if (active_leases > 0) {
|
||||
--active_leases;
|
||||
}
|
||||
evict_expired_locked(now, to_close);
|
||||
|
||||
const bool can_keep = !shut_down && reusable &&
|
||||
conn != nullptr && conn->is_open() &&
|
||||
limits.max_idle_connections > 0;
|
||||
if (can_keep) {
|
||||
while (idle_connections >=
|
||||
limits.max_idle_connections) {
|
||||
evict_oldest_idle_locked(to_close);
|
||||
}
|
||||
idle_by_key[key].push_back(
|
||||
IdleEntry{std::move(conn), now});
|
||||
++idle_connections;
|
||||
} else {
|
||||
if (conn != nullptr) {
|
||||
to_close.push_back(std::move(conn));
|
||||
}
|
||||
if (!reusable) {
|
||||
++closed_dirty;
|
||||
}
|
||||
if (total_connections > 0) {
|
||||
--total_connections;
|
||||
}
|
||||
auto oit = per_origin_count.find(key);
|
||||
if (oit != per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── ConnectionLease ─────────────────────────────────────────────────────
|
||||
|
||||
ConnectionLease::~ConnectionLease() noexcept { release(); }
|
||||
|
||||
ConnectionLease::ConnectionLease(ConnectionLease&& other) noexcept
|
||||
: m_pool_state(std::move(other.m_pool_state)),
|
||||
m_key(std::move(other.m_key)), m_conn(std::move(other.m_conn)),
|
||||
m_reused(std::exchange(other.m_reused, false)),
|
||||
m_reusable(std::exchange(other.m_reusable, false)),
|
||||
m_active(std::exchange(other.m_active, false))
|
||||
{
|
||||
}
|
||||
|
||||
ConnectionLease& ConnectionLease::operator=(ConnectionLease&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
release();
|
||||
m_pool_state = std::move(other.m_pool_state);
|
||||
m_key = std::move(other.m_key);
|
||||
m_conn = std::move(other.m_conn);
|
||||
m_reused = std::exchange(other.m_reused, false);
|
||||
m_reusable = std::exchange(other.m_reusable, false);
|
||||
m_active = std::exchange(other.m_active, false);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool ConnectionLease::valid() const noexcept
|
||||
{
|
||||
return m_active && m_conn != nullptr;
|
||||
}
|
||||
|
||||
bool ConnectionLease::reused() const noexcept { return m_reused; }
|
||||
|
||||
const PoolKey& ConnectionLease::key() const noexcept { return m_key; }
|
||||
|
||||
PooledConnection* ConnectionLease::get() const noexcept
|
||||
{
|
||||
return m_conn.get();
|
||||
}
|
||||
|
||||
PooledConnection& ConnectionLease::operator*() const noexcept
|
||||
{
|
||||
return *m_conn;
|
||||
}
|
||||
|
||||
PooledConnection* ConnectionLease::operator->() const noexcept
|
||||
{
|
||||
return m_conn.get();
|
||||
}
|
||||
|
||||
void ConnectionLease::mark_reusable(bool reusable) noexcept
|
||||
{
|
||||
m_reusable = reusable;
|
||||
}
|
||||
|
||||
void ConnectionLease::release() noexcept
|
||||
{
|
||||
if (!m_active) {
|
||||
return;
|
||||
}
|
||||
m_active = false;
|
||||
auto state = std::static_pointer_cast<ConnectionPool::State>(
|
||||
std::move(m_pool_state));
|
||||
auto conn = std::move(m_conn);
|
||||
const bool reusable = std::exchange(m_reusable, false);
|
||||
if (state) {
|
||||
state->return_lease(m_key, std::move(conn), reusable);
|
||||
} else if (conn) {
|
||||
conn->close();
|
||||
}
|
||||
}
|
||||
|
||||
// ── ConnectionPool ──────────────────────────────────────────────────────
|
||||
|
||||
ConnectionPool::ConnectionPool(PoolLimits limits,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
: m_state(std::make_shared<State>())
|
||||
{
|
||||
m_state->limits = limits;
|
||||
m_state->clock = &clock;
|
||||
}
|
||||
|
||||
ConnectionPool::~ConnectionPool() noexcept { shutdown(); }
|
||||
ConnectionPool::ConnectionPool(ConnectionPool&&) noexcept = default;
|
||||
ConnectionPool&
|
||||
ConnectionPool::operator=(ConnectionPool&&) noexcept = default;
|
||||
|
||||
Void::Result::Result<ConnectionLease>
|
||||
ConnectionPool::acquire(const PoolKey& key,
|
||||
const ConnectionFactory& factory)
|
||||
{
|
||||
if (!m_state) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::ConnectionPool: moved-from pool")};
|
||||
}
|
||||
if (!factory) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::ConnectionPool: empty connection factory")};
|
||||
}
|
||||
if (key.host.empty() || key.port == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::ConnectionPool: invalid pool key")};
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
std::unique_ptr<PooledConnection> reused_conn;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
if (m_state->shut_down) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::cancelled,
|
||||
"Net::ConnectionPool: pool is shut down")};
|
||||
}
|
||||
const auto now = m_state->clock->now();
|
||||
m_state->evict_expired_locked(now, to_close);
|
||||
|
||||
// Try LIFO idle connection for this exact key.
|
||||
auto it = m_state->idle_by_key.find(key);
|
||||
if (it != m_state->idle_by_key.end()) {
|
||||
while (!it->second.empty()) {
|
||||
auto cand = std::move(it->second.back().conn);
|
||||
it->second.pop_back();
|
||||
--m_state->idle_connections;
|
||||
if (cand && cand->is_open()) {
|
||||
reused_conn = std::move(cand);
|
||||
++m_state->active_leases;
|
||||
++m_state->total_acquires;
|
||||
++m_state->idle_hits;
|
||||
break;
|
||||
}
|
||||
to_close.push_back(std::move(cand));
|
||||
--m_state->total_connections;
|
||||
++m_state->idle_evictions;
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (it->second.empty()) {
|
||||
m_state->idle_by_key.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
if (!reused_conn) {
|
||||
// Enforce per-origin and total connection capacity.
|
||||
const std::size_t cur_origin =
|
||||
m_state->per_origin_count[key];
|
||||
if (cur_origin >= m_state->limits.max_per_origin) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::overloaded,
|
||||
"Net::ConnectionPool: per-origin connection limit "
|
||||
"reached",
|
||||
Void::Result::ErrorCode{
|
||||
Void::Result::kNetErrorDomain,
|
||||
static_cast<std::int32_t>(
|
||||
NetErrorCode::quota_exceeded)}}};
|
||||
}
|
||||
if (m_state->total_connections >=
|
||||
m_state->limits.max_total_connections) {
|
||||
// Evict an idle connection from another origin if possible.
|
||||
if (m_state->idle_connections > 0) {
|
||||
m_state->evict_oldest_idle_locked(to_close);
|
||||
}
|
||||
}
|
||||
if (m_state->total_connections >=
|
||||
m_state->limits.max_total_connections) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::overloaded,
|
||||
"Net::ConnectionPool: total connection limit reached",
|
||||
Void::Result::ErrorCode{
|
||||
Void::Result::kNetErrorDomain,
|
||||
static_cast<std::int32_t>(
|
||||
NetErrorCode::quota_exceeded)}}};
|
||||
}
|
||||
// Reserve slot before calling factory outside lock.
|
||||
++m_state->total_connections;
|
||||
++m_state->active_leases;
|
||||
++m_state->per_origin_count[key];
|
||||
++m_state->total_acquires;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
|
||||
if (reused_conn) {
|
||||
ConnectionLease lease;
|
||||
lease.m_pool_state = m_state;
|
||||
lease.m_key = key;
|
||||
lease.m_conn = std::move(reused_conn);
|
||||
lease.m_reused = true;
|
||||
lease.m_reusable = false;
|
||||
lease.m_active = true;
|
||||
return lease;
|
||||
}
|
||||
|
||||
// Create new connection outside pool lock.
|
||||
auto created = factory(key);
|
||||
if (!created.has_value() || !(*created) || !(*created)->is_open()) {
|
||||
// Roll back reservation.
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
if (m_state->active_leases > 0) {
|
||||
--m_state->active_leases;
|
||||
}
|
||||
if (m_state->total_connections > 0) {
|
||||
--m_state->total_connections;
|
||||
}
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
if (!created.has_value()) {
|
||||
return std::unexpected{std::move(created.error())};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
"Net::ConnectionPool: factory returned closed/null "
|
||||
"connection")};
|
||||
}
|
||||
|
||||
ConnectionLease lease;
|
||||
lease.m_pool_state = m_state;
|
||||
lease.m_key = key;
|
||||
lease.m_conn = std::move(*created);
|
||||
lease.m_reused = false;
|
||||
lease.m_reusable = false;
|
||||
lease.m_active = true;
|
||||
return lease;
|
||||
}
|
||||
|
||||
std::size_t ConnectionPool::evict_expired()
|
||||
{
|
||||
if (!m_state) {
|
||||
return 0;
|
||||
}
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
m_state->evict_expired_locked(m_state->clock->now(), to_close);
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
return to_close.size();
|
||||
}
|
||||
|
||||
std::size_t ConnectionPool::clear_idle()
|
||||
{
|
||||
if (!m_state) {
|
||||
return 0;
|
||||
}
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
for (auto& [key, dq] : m_state->idle_by_key) {
|
||||
for (auto& entry : dq) {
|
||||
to_close.push_back(std::move(entry.conn));
|
||||
--m_state->idle_connections;
|
||||
--m_state->total_connections;
|
||||
++m_state->idle_evictions;
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m_state->idle_by_key.clear();
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
return to_close.size();
|
||||
}
|
||||
|
||||
void ConnectionPool::shutdown() noexcept
|
||||
{
|
||||
if (!m_state) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
m_state->shut_down = true;
|
||||
for (auto& [key, dq] : m_state->idle_by_key) {
|
||||
for (auto& entry : dq) {
|
||||
to_close.push_back(std::move(entry.conn));
|
||||
--m_state->idle_connections;
|
||||
--m_state->total_connections;
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m_state->idle_by_key.clear();
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PoolStats ConnectionPool::stats() const
|
||||
{
|
||||
if (!m_state) {
|
||||
return {};
|
||||
}
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
return PoolStats{
|
||||
.total_connections = m_state->total_connections,
|
||||
.active_leases = m_state->active_leases,
|
||||
.idle_connections = m_state->idle_connections,
|
||||
.total_acquires = m_state->total_acquires,
|
||||
.idle_hits = m_state->idle_hits,
|
||||
.idle_evictions = m_state->idle_evictions,
|
||||
.closed_dirty = m_state->closed_dirty,
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace Void::Net
|
||||
+271
-1
@@ -1,9 +1,20 @@
|
||||
#include <Void/Net/Server.hpp>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <set>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
@@ -440,6 +451,106 @@ namespace Void::Net
|
||||
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<std::string>
|
||||
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<std::size_t>(size_));
|
||||
std::array<char, 32 * 1024> buf{};
|
||||
std::uint64_t offset = 0;
|
||||
for (;;) {
|
||||
const ssize_t n = ::pread(fd_, buf.data(), buf.size(),
|
||||
static_cast<off_t>(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<std::uint64_t>(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<std::size_t>(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>
|
||||
StaticFileResolver::create(std::filesystem::path root,
|
||||
std::string index_file)
|
||||
@@ -458,8 +569,167 @@ namespace Void::Net
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: document root is not a directory");
|
||||
}
|
||||
std::shared_ptr<DirHandle> 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<DirHandle>(dir_fd);
|
||||
#endif
|
||||
return StaticFileResolver{std::move(canonical_root),
|
||||
std::move(index_file)};
|
||||
std::move(index_file),
|
||||
std::move(root_handle)};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<OpenedStaticFile>>
|
||||
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<OpenedStaticFile>{};
|
||||
}
|
||||
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<OpenedStaticFile>{};
|
||||
}
|
||||
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<OpenedStaticFile>{};
|
||||
}
|
||||
|
||||
const auto ct = content_type_for(rel_path);
|
||||
return std::optional<OpenedStaticFile>{OpenedStaticFile{
|
||||
file_fd, std::move(rel_path), ct,
|
||||
static_cast<std::uint64_t>(st.st_size)}};
|
||||
#else
|
||||
(void)request_path;
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver::open_safe: unsupported platform");
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<StaticFile>>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
void_add_module(Net
|
||||
INTERNAL_DEPS Functional Text
|
||||
INTERNAL_DEPS Functional Text Time
|
||||
EXTERNAL_DEPS
|
||||
Boost::headers
|
||||
Boost::beast
|
||||
|
||||
Reference in new issue
Block a user