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
@@ -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)) {
|
||||
|
||||
Reference in new issue
Block a user