feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security, data, app, realtime, supervisor, clients, CLI, example plus enterprise tenancy, audit, operability, governance, supplychain. Postgres via docker compose for tests.
This commit is contained in:
@@ -0,0 +1,962 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113. H2 connection engine.
|
||||
#include "connection.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include "runtime/base64.h"
|
||||
#include "runtime/event_loop.h"
|
||||
#include "runtime/http/connection.h"
|
||||
#include "runtime/http/protocol_detect.h"
|
||||
#include "runtime/observability_hooks.h"
|
||||
#include "runtime/task.h"
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
namespace {
|
||||
constexpr uint8_t kData = 0x0;
|
||||
constexpr uint8_t kHeaders = 0x1;
|
||||
constexpr uint8_t kPriority = 0x2;
|
||||
constexpr uint8_t kRst = 0x3;
|
||||
constexpr uint8_t kSettings = 0x4;
|
||||
constexpr uint8_t kPushPromise = 0x5;
|
||||
constexpr uint8_t kPing = 0x6;
|
||||
constexpr uint8_t kGoaway = 0x7;
|
||||
constexpr uint8_t kWindowUpdate = 0x8;
|
||||
constexpr uint8_t kContinuation = 0x9;
|
||||
|
||||
constexpr uint8_t kFlagEndStream = 0x1;
|
||||
constexpr uint8_t kFlagAck = 0x1;
|
||||
constexpr uint8_t kFlagEndHeaders = 0x4;
|
||||
constexpr uint8_t kFlagPadded = 0x8;
|
||||
constexpr uint8_t kFlagPriority = 0x20;
|
||||
|
||||
constexpr uint32_t kNoError = 0x0;
|
||||
constexpr uint32_t kProtocolError = 0x1;
|
||||
constexpr uint32_t kInternalError = 0x2;
|
||||
constexpr uint32_t kFlowControlError = 0x3;
|
||||
constexpr uint32_t kStreamClosed = 0x5;
|
||||
constexpr uint32_t kFrameSizeError = 0x6;
|
||||
constexpr uint32_t kRefusedStream = 0x7;
|
||||
constexpr uint32_t kCancel = 0x8;
|
||||
constexpr uint32_t kCompressionError = 0x9;
|
||||
|
||||
bool IsH2HopHeader(std::string_view name) {
|
||||
return EqCaseInsensitive(name, "connection") ||
|
||||
EqCaseInsensitive(name, "keep-alive") ||
|
||||
EqCaseInsensitive(name, "proxy-connection") ||
|
||||
EqCaseInsensitive(name, "transfer-encoding") ||
|
||||
EqCaseInsensitive(name, "upgrade") ||
|
||||
EqCaseInsensitive(name, "http2-settings");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
H2Connection::H2Connection(Connection& conn, H2Config config)
|
||||
: conn_(conn), config_(config) {
|
||||
if (config_.max_concurrent_streams > caps::kH2MaxConcurrentStreamsCeiling) {
|
||||
config_.max_concurrent_streams = caps::kH2MaxConcurrentStreamsCeiling;
|
||||
}
|
||||
local_.max_concurrent_streams =
|
||||
(uint32_t)config_.max_concurrent_streams;
|
||||
decoder_.SetMaxTableSize(local_.header_table_size);
|
||||
}
|
||||
|
||||
void H2Connection::drain() {
|
||||
draining_ = true;
|
||||
SendGoaway(kNoError);
|
||||
conn_.InterruptRead(); // unpark the read loop for a prompt exit
|
||||
}
|
||||
|
||||
std::string H2Connection::FrameBytes(uint8_t type, uint8_t flags,
|
||||
uint32_t stream_id, const char* payload,
|
||||
std::size_t len) {
|
||||
std::string out;
|
||||
out.resize(9 + len);
|
||||
out[0] = (char)((len >> 16) & 0xff);
|
||||
out[1] = (char)((len >> 8) & 0xff);
|
||||
out[2] = (char)(len & 0xff);
|
||||
out[3] = (char)type;
|
||||
out[4] = (char)flags;
|
||||
out[5] = (char)((stream_id >> 24) & 0x7f);
|
||||
out[6] = (char)((stream_id >> 16) & 0xff);
|
||||
out[7] = (char)((stream_id >> 8) & 0xff);
|
||||
out[8] = (char)(stream_id & 0xff);
|
||||
if (len > 0) out.replace(9, len, payload, len);
|
||||
return out;
|
||||
}
|
||||
|
||||
void H2Connection::EnqueueControl(uint32_t stream_id,
|
||||
const std::string& frame_bytes) {
|
||||
OutItem item;
|
||||
item.stream_id = stream_id;
|
||||
item.bytes = frame_bytes;
|
||||
item.is_data = false;
|
||||
item.end_stream = false;
|
||||
out_queued_bytes_ += item.bytes.size();
|
||||
out_queue_.push_back(std::move(item));
|
||||
KickWriter();
|
||||
}
|
||||
|
||||
void H2Connection::EnqueueData(uint32_t stream_id, std::string payload,
|
||||
bool end_stream) {
|
||||
OutItem item;
|
||||
item.stream_id = stream_id;
|
||||
item.bytes = std::move(payload);
|
||||
item.is_data = true;
|
||||
item.end_stream = end_stream;
|
||||
out_queued_bytes_ += item.bytes.size();
|
||||
out_queue_.push_back(std::move(item));
|
||||
KickWriter();
|
||||
}
|
||||
|
||||
void H2Connection::KickWriter() {
|
||||
if (writer_active_ || conn_.closed()) return;
|
||||
writer_active_ = true;
|
||||
conn_.loop().post(WriterTask(weak_from_this()));
|
||||
}
|
||||
|
||||
void H2Connection::WakeWriter() {
|
||||
if (window_waiter_) {
|
||||
auto h = window_waiter_;
|
||||
window_waiter_ = nullptr;
|
||||
h.resume();
|
||||
}
|
||||
}
|
||||
|
||||
void H2Connection::SendSettingsAck() {
|
||||
EnqueueControl(0, FrameBytes(kSettings, kFlagAck, 0, nullptr, 0));
|
||||
}
|
||||
|
||||
void H2Connection::SendPingAck(const char* payload) {
|
||||
EnqueueControl(0, FrameBytes(kPing, kFlagAck, 0, payload, 8));
|
||||
}
|
||||
|
||||
void H2Connection::SendRst(uint32_t stream_id, uint32_t code) {
|
||||
char p[4] = {(char)(code >> 24), (char)((code >> 16) & 0xff),
|
||||
(char)((code >> 8) & 0xff), (char)(code & 0xff)};
|
||||
EnqueueControl(stream_id, FrameBytes(kRst, 0, stream_id, p, 4));
|
||||
}
|
||||
|
||||
void H2Connection::SendGoaway(uint32_t code) {
|
||||
if (goaway_sent_) return;
|
||||
goaway_sent_ = true;
|
||||
char p[8];
|
||||
p[0] = (char)((max_stream_id_ >> 24) & 0x7f);
|
||||
p[1] = (char)((max_stream_id_ >> 16) & 0xff);
|
||||
p[2] = (char)((max_stream_id_ >> 8) & 0xff);
|
||||
p[3] = (char)(max_stream_id_ & 0xff);
|
||||
p[4] = (char)(code >> 24);
|
||||
p[5] = (char)((code >> 16) & 0xff);
|
||||
p[6] = (char)((code >> 8) & 0xff);
|
||||
p[7] = (char)(code & 0xff);
|
||||
EnqueueControl(0, FrameBytes(kGoaway, 0, 0, p, 8));
|
||||
}
|
||||
|
||||
void H2Connection::SendWindowUpdate(uint32_t stream_id, uint32_t increment) {
|
||||
if (increment == 0) return;
|
||||
char p[4] = {(char)((increment >> 24) & 0x7f),
|
||||
(char)((increment >> 16) & 0xff),
|
||||
(char)((increment >> 8) & 0xff), (char)(increment & 0xff)};
|
||||
EnqueueControl(stream_id, FrameBytes(kWindowUpdate, 0, stream_id, p, 4));
|
||||
}
|
||||
|
||||
void H2Connection::Fatal(uint32_t code) {
|
||||
if (fatal_) return;
|
||||
fatal_ = true;
|
||||
close_after_flush_ = true;
|
||||
SendGoaway(code);
|
||||
WakeWriter();
|
||||
}
|
||||
|
||||
Task<bool> H2Connection::Ensure(std::size_t n) {
|
||||
std::string& in = conn_.inbox();
|
||||
while (in.size() < n) {
|
||||
if (conn_.closed() || fatal_) co_return false;
|
||||
Connection::ReadResult r = co_await conn_.PumpRead(config_.idle_timeout);
|
||||
if (r == Connection::ReadResult::Ok) continue;
|
||||
if (r == Connection::ReadResult::Interrupted) {
|
||||
// Drain poke or race: return so the read loop re-checks its exit
|
||||
// conditions. The loop must verify byte counts before parsing.
|
||||
co_return true;
|
||||
}
|
||||
if (r == Connection::ReadResult::Timeout) {
|
||||
if (!streams_.empty()) continue; // in-flight work: keep waiting
|
||||
SendGoaway(kNoError); // idle: graceful close
|
||||
co_return false;
|
||||
}
|
||||
co_return false;
|
||||
}
|
||||
co_return true;
|
||||
}
|
||||
|
||||
Task<void> H2Connection::Run(bool expect_magic, bool from_upgrade,
|
||||
const RequestHead& upgrade_head,
|
||||
const std::string& upgrade_body) {
|
||||
auto self = shared_from_this();
|
||||
if (expect_magic) {
|
||||
for (;;) {
|
||||
if (!co_await Ensure(kH2Preface.size())) co_return;
|
||||
if (conn_.closed() || fatal_) co_return;
|
||||
if (conn_.inbox().size() >= kH2Preface.size()) break;
|
||||
// Interrupted with a short buffer: re-park.
|
||||
}
|
||||
std::string& in = conn_.inbox();
|
||||
if (in.compare(0, kH2Preface.size(), kH2Preface) != 0) {
|
||||
Fatal(kProtocolError);
|
||||
} else {
|
||||
in.erase(0, kH2Preface.size());
|
||||
}
|
||||
if (fatal_) {
|
||||
read_done_ = true;
|
||||
WakeWriter();
|
||||
co_return;
|
||||
}
|
||||
}
|
||||
// Server preface.
|
||||
{
|
||||
std::string payload = EncodeSettingsPayload(local_);
|
||||
conn_.outbox().append(
|
||||
FrameBytes(kSettings, 0, 0, payload.data(), payload.size()));
|
||||
if (!co_await conn_.Flush(config_.idle_timeout)) co_return;
|
||||
}
|
||||
if (from_upgrade) {
|
||||
if (!ApplyUpgrade(upgrade_head, upgrade_body)) {
|
||||
read_done_ = true;
|
||||
WakeWriter();
|
||||
co_return;
|
||||
}
|
||||
co_await ReadLoop(false);
|
||||
} else {
|
||||
co_await ReadLoop(true);
|
||||
}
|
||||
read_done_ = true;
|
||||
WakeWriter();
|
||||
// Join the writer so GOAWAY is delivered before the socket closes.
|
||||
if (writer_active_ || !out_queue_.empty()) {
|
||||
struct JoinAwait {
|
||||
H2Connection* self;
|
||||
bool await_ready() const noexcept { return false; }
|
||||
void await_suspend(std::coroutine_handle<> h) {
|
||||
self->writer_done_waiter_ = h;
|
||||
H2Connection* h2 = self;
|
||||
h2->conn_.loop().schedule_after(std::chrono::milliseconds(5000),
|
||||
[h2] {
|
||||
if (h2->writer_done_waiter_) {
|
||||
auto w =
|
||||
h2->writer_done_waiter_;
|
||||
h2->writer_done_waiter_ =
|
||||
nullptr;
|
||||
w.resume();
|
||||
}
|
||||
});
|
||||
}
|
||||
void await_resume() noexcept {}
|
||||
};
|
||||
KickWriter();
|
||||
co_await JoinAwait{this};
|
||||
writer_done_waiter_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
Task<void> H2Connection::ReadLoop(bool first_must_be_settings) {
|
||||
auto self = shared_from_this();
|
||||
bool first = first_must_be_settings;
|
||||
std::string& in = conn_.inbox();
|
||||
for (;;) {
|
||||
if (conn_.closed() || fatal_) co_return;
|
||||
if ((peer_goaway_ || draining_) && streams_.empty()) co_return;
|
||||
if (!co_await Ensure(9)) co_return;
|
||||
if (conn_.closed() || fatal_) co_return;
|
||||
if ((peer_goaway_ || draining_) && streams_.empty()) co_return;
|
||||
if (in.size() < 9) continue; // interrupted: re-check, then re-park
|
||||
Frame fr;
|
||||
fr.length = ((uint32_t)(unsigned char)in[0] << 16) |
|
||||
((uint32_t)(unsigned char)in[1] << 8) |
|
||||
(uint32_t)(unsigned char)in[2];
|
||||
fr.type = (unsigned char)in[3];
|
||||
fr.flags = (unsigned char)in[4];
|
||||
fr.stream_id = ((uint32_t)((unsigned char)in[5] & 0x7f) << 24) |
|
||||
((uint32_t)(unsigned char)in[6] << 16) |
|
||||
((uint32_t)(unsigned char)in[7] << 8) |
|
||||
(uint32_t)(unsigned char)in[8];
|
||||
if (fr.length > local_.max_frame_size) {
|
||||
Fatal(kFrameSizeError);
|
||||
co_return;
|
||||
}
|
||||
if (!co_await Ensure(9 + fr.length)) co_return;
|
||||
if (conn_.closed() || fatal_) co_return;
|
||||
if ((peer_goaway_ || draining_) && streams_.empty()) co_return;
|
||||
if (in.size() < 9 + fr.length) continue; // interrupted: re-park
|
||||
std::string payload(in.data() + 9, fr.length);
|
||||
in.erase(0, 9 + fr.length);
|
||||
if (first) {
|
||||
first = false;
|
||||
if (fr.type != kSettings) {
|
||||
Fatal(kProtocolError);
|
||||
co_return;
|
||||
}
|
||||
}
|
||||
if (!ProcessFrame(fr, payload.data())) co_return;
|
||||
}
|
||||
}
|
||||
|
||||
bool H2Connection::ProcessFrame(const Frame& fr, const char* payload) {
|
||||
if (cont_expected_ && fr.type != kContinuation) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
switch (fr.type) {
|
||||
case kData:
|
||||
return OnData(fr, payload);
|
||||
case kHeaders:
|
||||
return OnHeaders(fr, payload);
|
||||
case kPriority:
|
||||
return OnPriority(fr, payload);
|
||||
case kRst:
|
||||
return OnRst(fr, payload);
|
||||
case kSettings:
|
||||
return OnSettings(fr, payload);
|
||||
case kPushPromise:
|
||||
Fatal(kProtocolError); // server push is gone; never accept it
|
||||
return false;
|
||||
case kPing:
|
||||
return OnPing(fr, payload);
|
||||
case kGoaway:
|
||||
return OnGoaway(fr, payload);
|
||||
case kWindowUpdate:
|
||||
return OnWindowUpdate(fr, payload);
|
||||
case kContinuation:
|
||||
return OnContinuation(fr, payload);
|
||||
default:
|
||||
return true; // unknown types are ignored
|
||||
}
|
||||
}
|
||||
|
||||
bool H2Connection::OnSettings(const Frame& fr, const char* payload) {
|
||||
if (fr.stream_id != 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (fr.flags & kFlagAck) {
|
||||
if (fr.length != 0) {
|
||||
Fatal(kFrameSizeError);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
uint32_t old_window = peer_.initial_window_size;
|
||||
Settings next = peer_;
|
||||
SettingsError e = DecodeSettingsPayload(payload, fr.length, next);
|
||||
if (e == SettingsError::ProtocolError) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (e == SettingsError::FlowControlError) {
|
||||
Fatal(kFlowControlError);
|
||||
return false;
|
||||
}
|
||||
if (e == SettingsError::CompressionError) {
|
||||
Fatal(kCompressionError);
|
||||
return false;
|
||||
}
|
||||
peer_ = next;
|
||||
encoder_.SetMaxTableSize(peer_.header_table_size);
|
||||
if (peer_.initial_window_size != old_window) {
|
||||
int64_t delta =
|
||||
(int64_t)peer_.initial_window_size - (int64_t)old_window;
|
||||
if (!flow_.AdjustAllStreams(delta, peer_.initial_window_size)) {
|
||||
Fatal(kFlowControlError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
SendSettingsAck();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnHeaders(const Frame& fr, const char* payload) {
|
||||
if (fr.stream_id == 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
std::size_t off = 0;
|
||||
std::size_t len = fr.length;
|
||||
if (fr.flags & kFlagPadded) {
|
||||
if (len < 1) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
std::size_t pad = (unsigned char)payload[0];
|
||||
if (pad + 1 > len) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
off = 1;
|
||||
len -= 1 + pad;
|
||||
}
|
||||
if (fr.flags & kFlagPriority) {
|
||||
if (len < 5) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
off += 5;
|
||||
len -= 5;
|
||||
}
|
||||
bool end_stream = (fr.flags & kFlagEndStream) != 0;
|
||||
if (!(fr.flags & kFlagEndHeaders)) {
|
||||
cont_expected_ = true;
|
||||
cont_stream_ = fr.stream_id;
|
||||
cont_buf_.assign(payload + off, len);
|
||||
cont_end_stream_ = end_stream;
|
||||
return true;
|
||||
}
|
||||
return FinishHeaders(fr.stream_id, std::string(payload + off, len),
|
||||
end_stream);
|
||||
}
|
||||
|
||||
bool H2Connection::FinishHeaders(uint32_t stream_id,
|
||||
const std::string& block, bool end_stream) {
|
||||
std::vector<HpackField> fields;
|
||||
HpackError e = decoder_.Decode(block.data(), block.size(), fields);
|
||||
if (e != HpackError::Ok) {
|
||||
Fatal(kCompressionError);
|
||||
return false;
|
||||
}
|
||||
auto it = streams_.find(stream_id);
|
||||
if (it == streams_.end()) {
|
||||
if ((stream_id % 2) == 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (stream_id <= max_stream_id_) {
|
||||
SendRst(stream_id, kStreamClosed);
|
||||
return true;
|
||||
}
|
||||
if (goaway_sent_ || peer_goaway_ || draining_) return true;
|
||||
if (streams_.size() >= config_.max_concurrent_streams) {
|
||||
max_stream_id_ = stream_id;
|
||||
SendRst(stream_id, kRefusedStream);
|
||||
return true;
|
||||
}
|
||||
max_stream_id_ = stream_id;
|
||||
streams_.emplace(stream_id, H2Stream(stream_id, config_.body_cap));
|
||||
flow_.AddStream(stream_id, peer_.initial_window_size);
|
||||
stream_in_window_[stream_id] = (int64_t)local_.initial_window_size;
|
||||
it = streams_.find(stream_id);
|
||||
}
|
||||
StreamOutcome oc = it->second.OnHeaders(fields, end_stream);
|
||||
if (oc.event == StreamEvent::LocalReset) {
|
||||
SendRst(stream_id, oc.rst_code);
|
||||
EraseStream(stream_id);
|
||||
return true;
|
||||
}
|
||||
if (oc.event == StreamEvent::MessageComplete) Dispatch(stream_id);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnContinuation(const Frame& fr, const char* payload) {
|
||||
if (!cont_expected_ || fr.stream_id != cont_stream_) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (cont_buf_.size() + fr.length > caps::kH2HeaderListMax) {
|
||||
Fatal(kCompressionError);
|
||||
return false;
|
||||
}
|
||||
cont_buf_.append(payload, fr.length);
|
||||
if (!(fr.flags & kFlagEndHeaders)) return true;
|
||||
cont_expected_ = false;
|
||||
std::string block = std::move(cont_buf_);
|
||||
cont_buf_.clear();
|
||||
return FinishHeaders(fr.stream_id, block, cont_end_stream_);
|
||||
}
|
||||
|
||||
bool H2Connection::OnData(const Frame& fr, const char* payload) {
|
||||
if (fr.stream_id == 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
std::size_t off = 0;
|
||||
std::size_t len = fr.length;
|
||||
if (fr.flags & kFlagPadded) {
|
||||
if (len < 1) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
std::size_t pad = (unsigned char)payload[0];
|
||||
if (pad + 1 > len) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
off = 1;
|
||||
len -= 1 + pad;
|
||||
}
|
||||
bool end_stream = (fr.flags & kFlagEndStream) != 0;
|
||||
auto it = streams_.find(fr.stream_id);
|
||||
if (it == streams_.end()) {
|
||||
if (fr.stream_id <= max_stream_id_) {
|
||||
SendRst(fr.stream_id, kStreamClosed);
|
||||
return true;
|
||||
}
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if ((int64_t)fr.length > conn_in_window_) {
|
||||
Fatal(kFlowControlError);
|
||||
return false;
|
||||
}
|
||||
auto win = stream_in_window_.find(fr.stream_id);
|
||||
if (win == stream_in_window_.end() ||
|
||||
(int64_t)fr.length > win->second) {
|
||||
Fatal(kFlowControlError);
|
||||
return false;
|
||||
}
|
||||
conn_in_window_ -= (int64_t)fr.length;
|
||||
win->second -= (int64_t)fr.length;
|
||||
flow_.ConsumedConnection(fr.length);
|
||||
flow_.ConsumedStream(fr.stream_id, fr.length);
|
||||
// Immediate refund keeps the peer flowing; bounded by frame caps.
|
||||
SendWindowUpdate(0, (uint32_t)flow_.TakeConnectionRefund());
|
||||
SendWindowUpdate(fr.stream_id,
|
||||
(uint32_t)flow_.TakeStreamRefund(fr.stream_id));
|
||||
conn_in_window_ += (int64_t)fr.length;
|
||||
win->second += (int64_t)fr.length;
|
||||
StreamOutcome oc =
|
||||
it->second.OnData(payload + off, len, end_stream);
|
||||
if (oc.event == StreamEvent::LocalReset) {
|
||||
SendRst(fr.stream_id, oc.rst_code);
|
||||
EraseStream(fr.stream_id);
|
||||
return true;
|
||||
}
|
||||
if (oc.event == StreamEvent::MessageComplete) {
|
||||
Dispatch(fr.stream_id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnRst(const Frame& fr, const char* payload) {
|
||||
if (fr.stream_id == 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (fr.length != 4) {
|
||||
Fatal(kFrameSizeError);
|
||||
return false;
|
||||
}
|
||||
auto it = streams_.find(fr.stream_id);
|
||||
if (it == streams_.end()) return true; // idle or closed: ignore
|
||||
uint32_t code = ((uint32_t)(unsigned char)payload[0] << 24) |
|
||||
((uint32_t)(unsigned char)payload[1] << 16) |
|
||||
((uint32_t)(unsigned char)payload[2] << 8) |
|
||||
(uint32_t)(unsigned char)payload[3];
|
||||
it->second.OnRst(code);
|
||||
EraseStream(fr.stream_id);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnPing(const Frame& fr, const char* payload) {
|
||||
if (fr.stream_id != 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (fr.length != 8) {
|
||||
Fatal(kFrameSizeError);
|
||||
return false;
|
||||
}
|
||||
if (fr.flags & kFlagAck) return true;
|
||||
SendPingAck(payload);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnGoaway(const Frame& fr, const char* payload) {
|
||||
if (fr.stream_id != 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (fr.length < 8) {
|
||||
Fatal(kFrameSizeError);
|
||||
return false;
|
||||
}
|
||||
(void)payload;
|
||||
peer_goaway_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnWindowUpdate(const Frame& fr, const char* payload) {
|
||||
if (fr.length != 4) {
|
||||
Fatal(kFrameSizeError);
|
||||
return false;
|
||||
}
|
||||
uint32_t inc = ((uint32_t)((unsigned char)payload[0] & 0x7f) << 24) |
|
||||
((uint32_t)(unsigned char)payload[1] << 16) |
|
||||
((uint32_t)(unsigned char)payload[2] << 8) |
|
||||
(uint32_t)(unsigned char)payload[3];
|
||||
if (inc == 0) {
|
||||
Fatal(kFlowControlError);
|
||||
return false;
|
||||
}
|
||||
if (fr.stream_id == 0) {
|
||||
flow_.OnConnectionWindowUpdate(inc);
|
||||
WakeWriter();
|
||||
return true;
|
||||
}
|
||||
auto it = streams_.find(fr.stream_id);
|
||||
if (it == streams_.end()) {
|
||||
if (fr.stream_id > max_stream_id_) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
return true; // closed: ignore
|
||||
}
|
||||
StreamOutcome oc = it->second.OnWindowUpdate(inc);
|
||||
if (oc.event == StreamEvent::LocalReset) {
|
||||
SendRst(fr.stream_id, oc.rst_code);
|
||||
EraseStream(fr.stream_id);
|
||||
return true;
|
||||
}
|
||||
flow_.OnStreamWindowUpdate(fr.stream_id, inc);
|
||||
WakeWriter();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool H2Connection::OnPriority(const Frame& fr, const char* payload) {
|
||||
(void)payload;
|
||||
if (fr.stream_id == 0) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (fr.length != 5) {
|
||||
Fatal(kFrameSizeError);
|
||||
return false;
|
||||
}
|
||||
return true; // accepted and ignored per plan open question 2
|
||||
}
|
||||
|
||||
void H2Connection::EraseStream(uint32_t stream_id) {
|
||||
streams_.erase(stream_id);
|
||||
flow_.RemoveStream(stream_id);
|
||||
stream_in_window_.erase(stream_id);
|
||||
if ((draining_ || peer_goaway_) && streams_.empty()) {
|
||||
conn_.InterruptRead(); // let the read loop notice the drain is done
|
||||
}
|
||||
}
|
||||
|
||||
void H2Connection::Dispatch(uint32_t stream_id) {
|
||||
auto it = streams_.find(stream_id);
|
||||
if (it == streams_.end()) return;
|
||||
FullRequest req;
|
||||
req.head = it->second.head();
|
||||
req.body = it->second.body();
|
||||
req.trailers = it->second.trailers();
|
||||
req.is_tls = conn_.is_tls();
|
||||
req.peer = conn_.peer();
|
||||
req.protocol = "HTTP/2";
|
||||
++requests_;
|
||||
MOLO_RUNTIME_COUNT("runtime.h2.requests");
|
||||
conn_.loop().post(StreamTask(weak_from_this(), stream_id, std::move(req)));
|
||||
}
|
||||
|
||||
Task<void> H2Connection::StreamTask(std::weak_ptr<H2Connection> weak,
|
||||
uint32_t stream_id, FullRequest req) {
|
||||
auto self = weak.lock();
|
||||
if (!self) co_return;
|
||||
TimerWheel::TimerId budget = self->conn_.loop().schedule_after(
|
||||
self->config_.handler_budget, [weak, stream_id] {
|
||||
if (auto s = weak.lock()) {
|
||||
auto it = s->streams_.find(stream_id);
|
||||
if (it != s->streams_.end()) {
|
||||
s->SendRst(stream_id, kCancel);
|
||||
s->EraseStream(stream_id);
|
||||
}
|
||||
}
|
||||
});
|
||||
FullResponse resp;
|
||||
bool ok = true;
|
||||
try {
|
||||
resp = co_await self->conn_.handler()(req);
|
||||
} catch (...) {
|
||||
ok = false;
|
||||
}
|
||||
self = weak.lock();
|
||||
if (!self) co_return;
|
||||
self->conn_.loop().cancel_timer(budget);
|
||||
if (!ok) {
|
||||
resp.head.status = 500;
|
||||
resp.head.headers.clear();
|
||||
resp.head.headers.set("content-type", "text/plain; charset=utf-8");
|
||||
resp.body = "500 Internal Server Error\n";
|
||||
}
|
||||
std::optional<FileBody> fb;
|
||||
if (resp.file.has_value()) {
|
||||
fb = resp.file;
|
||||
resp.file.reset();
|
||||
}
|
||||
if (fb.has_value() && fb->fd >= 0 && !resp.body.empty()) {
|
||||
// Contract violation: file and string body at once. Fail closed.
|
||||
::close(fb->fd);
|
||||
fb.reset();
|
||||
resp.head.status = 500;
|
||||
resp.head.headers.clear();
|
||||
resp.head.headers.set("content-type", "text/plain; charset=utf-8");
|
||||
resp.body = "500 Internal Server Error\n";
|
||||
}
|
||||
bool file_follows = fb.has_value() && fb->fd >= 0;
|
||||
bool stream_file = self->CompleteResponse(stream_id, std::move(resp),
|
||||
file_follows);
|
||||
if (stream_file && file_follows) {
|
||||
co_await FileBodyTask(weak, stream_id, *fb);
|
||||
} else if (file_follows) {
|
||||
::close(fb->fd); // HEAD, reset, or no-body status: drop the bytes
|
||||
}
|
||||
}
|
||||
|
||||
Task<void> H2Connection::FileBodyTask(std::weak_ptr<H2Connection> weak,
|
||||
uint32_t stream_id, FileBody fb) {
|
||||
struct Closer {
|
||||
int fd;
|
||||
~Closer() {
|
||||
if (fd >= 0) ::close(fd);
|
||||
}
|
||||
} closer{fb.fd};
|
||||
if (!ClampFileBody(fb)) {
|
||||
if (auto s = weak.lock()) s->SendRst(stream_id, kInternalError);
|
||||
co_return;
|
||||
}
|
||||
auto self = weak.lock();
|
||||
if (!self) co_return;
|
||||
if (fb.length == 0) {
|
||||
// Empty file still needs the terminal flag.
|
||||
if (self->streams_.find(stream_id) != self->streams_.end()) {
|
||||
self->EnqueueData(stream_id, std::string(), true);
|
||||
}
|
||||
co_return;
|
||||
}
|
||||
// Framing forbids sendfile here, so stream bounded 64 KB DATA items with
|
||||
// queue backpressure: park on yield until the writer drains below the
|
||||
// high watermark.
|
||||
uint64_t pos = fb.offset;
|
||||
uint64_t left = fb.length;
|
||||
std::string chunk;
|
||||
chunk.resize(caps::kFileChunkSize);
|
||||
while (left > 0) {
|
||||
self = weak.lock();
|
||||
if (!self || self->conn_.closed()) co_return;
|
||||
if (self->streams_.find(stream_id) == self->streams_.end()) co_return;
|
||||
std::size_t n =
|
||||
left > chunk.size() ? chunk.size() : (std::size_t)left;
|
||||
ssize_t r = ::pread(fb.fd, chunk.data(), n, (off_t)pos);
|
||||
if (r <= 0) {
|
||||
self->SendRst(stream_id, kInternalError);
|
||||
co_return;
|
||||
}
|
||||
pos += (uint64_t)r;
|
||||
left -= (uint64_t)r;
|
||||
self->EnqueueData(stream_id, chunk.substr(0, (std::size_t)r),
|
||||
left == 0);
|
||||
while (self && !self->conn_.closed() &&
|
||||
self->out_queued_bytes_ > caps::kWriteHighWatermark &&
|
||||
self->streams_.find(stream_id) != self->streams_.end()) {
|
||||
co_await self->conn_.loop().yield();
|
||||
self = weak.lock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool H2Connection::CompleteResponse(uint32_t stream_id, FullResponse resp,
|
||||
bool file_follows) {
|
||||
auto it = streams_.find(stream_id);
|
||||
if (it == streams_.end()) return false; // reset or timed out: drop
|
||||
if (it->second.state() == StreamState::Closed) {
|
||||
EraseStream(stream_id);
|
||||
return false;
|
||||
}
|
||||
std::vector<HpackField> fields;
|
||||
fields.push_back({":status", std::to_string(resp.head.status)});
|
||||
for (const auto& kv : resp.head.headers.entries()) {
|
||||
if (IsH2HopHeader(kv.first)) continue;
|
||||
if (!kv.first.empty() && kv.first[0] == ':') continue;
|
||||
fields.push_back({kv.first, kv.second});
|
||||
}
|
||||
std::string block = encoder_.Encode(fields);
|
||||
bool head_only = (it->second.head().method == "HEAD");
|
||||
bool no_body = head_only || resp.head.status == 204 ||
|
||||
resp.head.status == 304 ||
|
||||
(resp.head.status >= 100 && resp.head.status < 200) ||
|
||||
(!file_follows && resp.body.empty());
|
||||
std::size_t maxf = peer_.max_frame_size;
|
||||
if (maxf == 0) maxf = caps::kH2MaxFrameDefault;
|
||||
std::size_t off = 0;
|
||||
bool first = true;
|
||||
// HEADERS plus CONTINUATIONs as one control item.
|
||||
std::string head_frames;
|
||||
while (off < block.size()) {
|
||||
std::size_t n = block.size() - off;
|
||||
if (n > maxf) n = maxf;
|
||||
bool last = (off + n >= block.size());
|
||||
uint8_t flags = 0;
|
||||
if (last) flags |= kFlagEndHeaders;
|
||||
if (last && no_body) flags |= kFlagEndStream;
|
||||
head_frames.append(FrameBytes(first ? kHeaders : kContinuation, flags,
|
||||
stream_id, block.data() + off, n));
|
||||
off += n;
|
||||
first = false;
|
||||
}
|
||||
if (block.empty()) {
|
||||
uint8_t flags = kFlagEndHeaders;
|
||||
if (no_body) flags |= kFlagEndStream;
|
||||
head_frames.append(FrameBytes(kHeaders, flags, stream_id, nullptr, 0));
|
||||
}
|
||||
OutItem ctl;
|
||||
ctl.stream_id = stream_id;
|
||||
ctl.bytes = std::move(head_frames);
|
||||
ctl.is_data = false;
|
||||
ctl.end_stream = no_body;
|
||||
out_queued_bytes_ += ctl.bytes.size();
|
||||
out_queue_.push_back(std::move(ctl));
|
||||
if (no_body) {
|
||||
KickWriter();
|
||||
return false;
|
||||
}
|
||||
if (file_follows) {
|
||||
KickWriter(); // HEADERS flush while the file streams behind
|
||||
return true;
|
||||
}
|
||||
EnqueueData(stream_id, std::move(resp.body), true);
|
||||
return false;
|
||||
}
|
||||
|
||||
Task<void> H2Connection::WriterTask(std::weak_ptr<H2Connection> weak) {
|
||||
auto self = weak.lock();
|
||||
if (!self) co_return;
|
||||
struct WindowAwait {
|
||||
H2Connection* h2;
|
||||
bool await_ready() const noexcept { return false; }
|
||||
void await_suspend(std::coroutine_handle<> h) { h2->window_waiter_ = h; }
|
||||
void await_resume() noexcept {}
|
||||
};
|
||||
while (self && !self->out_queue_.empty() && !self->conn_.closed()) {
|
||||
OutItem& item = self->out_queue_.front();
|
||||
if (!item.is_data) {
|
||||
self->conn_.outbox().append(item.bytes);
|
||||
bool ok = co_await self->conn_.Flush(self->config_.idle_timeout);
|
||||
self = weak.lock();
|
||||
if (!self) co_return;
|
||||
if (!ok) break;
|
||||
bool end = item.end_stream;
|
||||
uint32_t sid = item.stream_id;
|
||||
self->UnqueueBytes(item.bytes.size() - item.offset);
|
||||
self->out_queue_.pop_front();
|
||||
auto it = self->streams_.find(sid);
|
||||
if (it != self->streams_.end()) {
|
||||
it->second.MarkResponseHeadersSent(end);
|
||||
if (end) self->EraseStream(sid);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// DATA with flow control.
|
||||
auto it = self->streams_.find(item.stream_id);
|
||||
if (it == self->streams_.end()) {
|
||||
self->UnqueueBytes(item.bytes.size() - item.offset);
|
||||
self->out_queue_.pop_front(); // reset meanwhile: drop
|
||||
continue;
|
||||
}
|
||||
std::size_t remaining = item.bytes.size() - item.offset;
|
||||
int64_t cw = self->flow_.ConnectionAvailable();
|
||||
int64_t sw = self->flow_.StreamAvailable(item.stream_id);
|
||||
if (cw <= 0 || sw <= 0) {
|
||||
if (self->read_done_) {
|
||||
self->UnqueueBytes(item.bytes.size() - item.offset);
|
||||
self->out_queue_.pop_front(); // no more updates coming
|
||||
continue;
|
||||
}
|
||||
co_await WindowAwait{self.get()};
|
||||
self = weak.lock();
|
||||
if (!self) co_return;
|
||||
continue;
|
||||
}
|
||||
std::size_t n = remaining;
|
||||
if ((int64_t)n > cw) n = (std::size_t)cw;
|
||||
if ((int64_t)n > sw) n = (std::size_t)sw;
|
||||
std::size_t maxf = self->peer_.max_frame_size;
|
||||
if (maxf == 0) maxf = caps::kH2MaxFrameDefault;
|
||||
if (n > maxf) n = maxf;
|
||||
self->flow_.TakeConnection(n);
|
||||
self->flow_.TakeStream(item.stream_id, n);
|
||||
bool last = (item.offset + n >= item.bytes.size());
|
||||
bool end = last && item.end_stream;
|
||||
uint8_t flags = end ? kFlagEndStream : 0;
|
||||
self->conn_.outbox().append(FrameBytes(kData, flags, item.stream_id,
|
||||
item.bytes.data() + item.offset,
|
||||
n));
|
||||
bool ok = co_await self->conn_.Flush(self->config_.idle_timeout);
|
||||
self = weak.lock();
|
||||
if (!self) co_return;
|
||||
if (!ok) break;
|
||||
item.offset += n;
|
||||
self->UnqueueBytes(n);
|
||||
auto jt = self->streams_.find(item.stream_id);
|
||||
if (jt != self->streams_.end()) {
|
||||
jt->second.MarkResponseDataSent(end);
|
||||
if (end) self->EraseStream(item.stream_id);
|
||||
}
|
||||
if (last) self->out_queue_.pop_front();
|
||||
}
|
||||
if (!self) co_return;
|
||||
self->writer_active_ = false;
|
||||
self->window_waiter_ = nullptr;
|
||||
if (self->writer_done_waiter_) {
|
||||
auto h = self->writer_done_waiter_;
|
||||
self->writer_done_waiter_ = nullptr;
|
||||
h.resume();
|
||||
}
|
||||
}
|
||||
|
||||
bool H2Connection::ApplyUpgrade(const RequestHead& head,
|
||||
const std::string& body) {
|
||||
std::string encoded = head.headers.get("http2-settings");
|
||||
std::optional<std::string> raw = Base64Url::Decode(encoded);
|
||||
if (!raw.has_value()) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
Settings next = peer_;
|
||||
SettingsError e = DecodeSettingsPayload(raw->data(), raw->size(), next);
|
||||
if (e != SettingsError::Ok) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
peer_ = next;
|
||||
encoder_.SetMaxTableSize(peer_.header_table_size);
|
||||
// Stream 1 carries the upgraded request, half-closed (remote).
|
||||
std::vector<HpackField> fields;
|
||||
fields.push_back({":method", head.method});
|
||||
fields.push_back({":scheme", conn_.is_tls() ? "https" : "http"});
|
||||
std::string authority = head.headers.get("host");
|
||||
if (authority.empty()) authority = head.headers.get(":authority");
|
||||
fields.push_back({":authority", authority});
|
||||
fields.push_back({":path", head.target});
|
||||
for (const auto& kv : head.headers.entries()) {
|
||||
if (IsH2HopHeader(kv.first)) continue;
|
||||
if (EqCaseInsensitive(kv.first, "host")) continue;
|
||||
fields.push_back({kv.first, kv.second});
|
||||
}
|
||||
streams_.emplace(1, H2Stream(1, config_.body_cap));
|
||||
max_stream_id_ = 1;
|
||||
flow_.AddStream(1, peer_.initial_window_size);
|
||||
stream_in_window_[1] = (int64_t)local_.initial_window_size;
|
||||
auto it = streams_.find(1);
|
||||
StreamOutcome oc = it->second.OnHeaders(fields, body.empty());
|
||||
if (oc.event == StreamEvent::LocalReset) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
if (!body.empty()) {
|
||||
oc = it->second.OnData(body.data(), body.size(), true);
|
||||
if (oc.event != StreamEvent::MessageComplete) {
|
||||
Fatal(kProtocolError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (oc.event == StreamEvent::MessageComplete) Dispatch(1);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,152 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113. H2 framing, settings handshake,
|
||||
// HPACK, stream multiplexing, dual flow control, GOAWAY/RST/PING. No server
|
||||
// push. PRIORITY accepted and ignored. Runs on the owning Connection's
|
||||
// transport, waiter and buffers; the Connection keeps lifecycle ownership.
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <coroutine>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "runtime/caps.h"
|
||||
#include "runtime/http/message.h"
|
||||
#include "runtime/task.h"
|
||||
#include "flow_control.h"
|
||||
#include "hpack.h"
|
||||
#include "settings.h"
|
||||
#include "stream.h"
|
||||
|
||||
namespace molo::runtime {
|
||||
class EventLoop;
|
||||
namespace tls {
|
||||
class ITlsHandle;
|
||||
}
|
||||
namespace http {
|
||||
class Connection;
|
||||
struct FullRequest;
|
||||
struct FullResponse;
|
||||
} // namespace http
|
||||
} // namespace molo::runtime
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
struct H2Config {
|
||||
std::size_t body_cap = caps::kBodyMaxDefault;
|
||||
std::size_t max_concurrent_streams = caps::kH2MaxConcurrentStreamsDefault;
|
||||
std::chrono::milliseconds idle_timeout = caps::kIdleKeepAliveTimeout;
|
||||
std::chrono::milliseconds handler_budget = caps::kHandlerBudget;
|
||||
};
|
||||
|
||||
class H2Connection : public std::enable_shared_from_this<H2Connection> {
|
||||
public:
|
||||
H2Connection(Connection& conn, H2Config config = H2Config{});
|
||||
~H2Connection() = default;
|
||||
|
||||
Task<void> Run(bool expect_magic, bool from_upgrade,
|
||||
const RequestHead& upgrade_head,
|
||||
const std::string& upgrade_body);
|
||||
void drain();
|
||||
std::size_t requests_served() const { return requests_; }
|
||||
|
||||
private:
|
||||
struct Frame {
|
||||
uint32_t length = 0;
|
||||
uint8_t type = 0;
|
||||
uint8_t flags = 0;
|
||||
uint32_t stream_id = 0;
|
||||
};
|
||||
|
||||
struct OutItem {
|
||||
uint32_t stream_id = 0;
|
||||
std::string bytes; // payload for DATA, full frame(s) otherwise
|
||||
bool is_data = false;
|
||||
bool end_stream = false;
|
||||
std::size_t offset = 0;
|
||||
};
|
||||
|
||||
static Task<void> StreamTask(std::weak_ptr<H2Connection> weak,
|
||||
uint32_t stream_id, FullRequest req);
|
||||
static Task<void> WriterTask(std::weak_ptr<H2Connection> weak);
|
||||
static Task<void> FileBodyTask(std::weak_ptr<H2Connection> weak,
|
||||
uint32_t stream_id, FileBody fb);
|
||||
|
||||
Task<bool> Ensure(std::size_t n);
|
||||
Task<void> ReadLoop(bool first_must_be_settings);
|
||||
bool ProcessFrame(const Frame& fr, const char* payload);
|
||||
// Sends HEADERS. file_follows means a file body streams next: the stream
|
||||
// stays open unless HEAD or a no-body status applies. Returns true when
|
||||
// the caller must stream the file body (via FileBodyTask).
|
||||
bool CompleteResponse(uint32_t stream_id, FullResponse resp,
|
||||
bool file_follows);
|
||||
|
||||
void EnqueueControl(uint32_t stream_id, const std::string& frame_bytes);
|
||||
void EnqueueData(uint32_t stream_id, std::string payload, bool end_stream);
|
||||
void KickWriter();
|
||||
void WakeWriter();
|
||||
void SendSettingsAck();
|
||||
void SendPingAck(const char* payload);
|
||||
void SendRst(uint32_t stream_id, uint32_t code);
|
||||
void SendGoaway(uint32_t code);
|
||||
void SendWindowUpdate(uint32_t stream_id, uint32_t increment);
|
||||
void Fatal(uint32_t code);
|
||||
static std::string FrameBytes(uint8_t type, uint8_t flags,
|
||||
uint32_t stream_id, const char* payload,
|
||||
std::size_t len);
|
||||
|
||||
bool OnSettings(const Frame& fr, const char* payload);
|
||||
bool OnHeaders(const Frame& fr, const char* payload);
|
||||
bool OnData(const Frame& fr, const char* payload);
|
||||
bool OnRst(const Frame& fr, const char* payload);
|
||||
bool OnPing(const Frame& fr, const char* payload);
|
||||
bool OnGoaway(const Frame& fr, const char* payload);
|
||||
bool OnWindowUpdate(const Frame& fr, const char* payload);
|
||||
bool OnPriority(const Frame& fr, const char* payload);
|
||||
bool OnContinuation(const Frame& fr, const char* payload);
|
||||
bool FinishHeaders(uint32_t stream_id, const std::string& block,
|
||||
bool end_stream);
|
||||
void EraseStream(uint32_t stream_id);
|
||||
void Dispatch(uint32_t stream_id);
|
||||
bool ApplyUpgrade(const RequestHead& head, const std::string& body);
|
||||
|
||||
Connection& conn_;
|
||||
H2Config config_;
|
||||
Settings local_;
|
||||
Settings peer_;
|
||||
HpackEncoder encoder_;
|
||||
HpackDecoder decoder_;
|
||||
FlowController flow_;
|
||||
std::unordered_map<uint32_t, H2Stream> streams_;
|
||||
int64_t conn_in_window_ = 65535;
|
||||
std::unordered_map<uint32_t, int64_t> stream_in_window_;
|
||||
std::deque<OutItem> out_queue_;
|
||||
// Payload bytes currently queued; bounds file-body streaming.
|
||||
std::size_t out_queued_bytes_ = 0;
|
||||
void UnqueueBytes(std::size_t n) {
|
||||
out_queued_bytes_ -=
|
||||
n > out_queued_bytes_ ? out_queued_bytes_ : n;
|
||||
}
|
||||
bool writer_active_ = false;
|
||||
bool read_done_ = false;
|
||||
bool close_after_flush_ = false;
|
||||
bool draining_ = false;
|
||||
bool goaway_sent_ = false;
|
||||
bool peer_goaway_ = false;
|
||||
bool fatal_ = false;
|
||||
uint32_t max_stream_id_ = 0;
|
||||
std::size_t requests_ = 0;
|
||||
// CONTINUATION reassembly state.
|
||||
bool cont_expected_ = false;
|
||||
uint32_t cont_stream_ = 0;
|
||||
std::string cont_buf_;
|
||||
bool cont_end_stream_ = false;
|
||||
std::coroutine_handle<> window_waiter_ = nullptr;
|
||||
std::coroutine_handle<> writer_done_waiter_ = nullptr;
|
||||
};
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,82 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113 section 6.9. Flow control.
|
||||
#include "flow_control.h"
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
namespace {
|
||||
constexpr int64_t kWindowMax = 0x7fffffffLL;
|
||||
}
|
||||
|
||||
FlowController::FlowController(uint32_t initial_window)
|
||||
: conn_out_((int64_t)initial_window) {}
|
||||
|
||||
bool FlowController::TakeConnection(std::size_t n) {
|
||||
if ((int64_t)n > conn_out_) return false;
|
||||
conn_out_ -= (int64_t)n;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FlowController::TakeStream(uint32_t stream_id, std::size_t n) {
|
||||
auto it = stream_out_.find(stream_id);
|
||||
if (it == stream_out_.end()) return false;
|
||||
if ((int64_t)n > it->second) return false;
|
||||
it->second -= (int64_t)n;
|
||||
return true;
|
||||
}
|
||||
|
||||
void FlowController::OnConnectionWindowUpdate(uint32_t increment) {
|
||||
conn_out_ += (int64_t)increment;
|
||||
if (conn_out_ > kWindowMax) conn_out_ = kWindowMax;
|
||||
}
|
||||
|
||||
void FlowController::OnStreamWindowUpdate(uint32_t stream_id,
|
||||
uint32_t increment) {
|
||||
auto it = stream_out_.find(stream_id);
|
||||
if (it == stream_out_.end()) return;
|
||||
it->second += (int64_t)increment;
|
||||
if (it->second > kWindowMax) it->second = kWindowMax;
|
||||
}
|
||||
|
||||
bool FlowController::AdjustAllStreams(int64_t delta, uint32_t new_initial) {
|
||||
(void)new_initial;
|
||||
for (const auto& kv : stream_out_) {
|
||||
if (kv.second + delta > kWindowMax) return false;
|
||||
}
|
||||
for (auto& kv : stream_out_) kv.second += delta;
|
||||
return true;
|
||||
}
|
||||
|
||||
void FlowController::AddStream(uint32_t stream_id, uint32_t initial_window) {
|
||||
stream_out_[stream_id] = (int64_t)initial_window;
|
||||
}
|
||||
|
||||
void FlowController::RemoveStream(uint32_t stream_id) {
|
||||
stream_out_.erase(stream_id);
|
||||
stream_in_used_.erase(stream_id);
|
||||
}
|
||||
|
||||
int64_t FlowController::StreamAvailable(uint32_t stream_id) const {
|
||||
auto it = stream_out_.find(stream_id);
|
||||
if (it == stream_out_.end()) return 0;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
void FlowController::ConsumedStream(uint32_t stream_id, std::size_t n) {
|
||||
stream_in_used_[stream_id] += n;
|
||||
}
|
||||
|
||||
std::size_t FlowController::TakeConnectionRefund() {
|
||||
std::size_t n = conn_in_used_;
|
||||
conn_in_used_ = 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
std::size_t FlowController::TakeStreamRefund(uint32_t stream_id) {
|
||||
auto it = stream_in_used_.find(stream_id);
|
||||
if (it == stream_in_used_.end()) return 0;
|
||||
std::size_t n = it->second;
|
||||
it->second = 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,43 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113 section 6.9. Connection-level plus
|
||||
// stream-level flow control accounting. Windows are signed: a SETTINGS
|
||||
// reduction may push a stream window negative, which only blocks sends.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
class FlowController {
|
||||
public:
|
||||
explicit FlowController(uint32_t initial_window = 65535);
|
||||
|
||||
// Outbound (peer windows): take returns false when the window is too
|
||||
// small; the caller waits for WINDOW_UPDATE.
|
||||
bool TakeConnection(std::size_t n);
|
||||
bool TakeStream(uint32_t stream_id, std::size_t n);
|
||||
void OnConnectionWindowUpdate(uint32_t increment);
|
||||
void OnStreamWindowUpdate(uint32_t stream_id, uint32_t increment);
|
||||
// Applies an INITIAL_WINDOW_SIZE change to every live stream. False when
|
||||
// a window would exceed 2^31-1 (FLOW_CONTROL_ERROR).
|
||||
bool AdjustAllStreams(int64_t delta, uint32_t new_initial);
|
||||
void AddStream(uint32_t stream_id, uint32_t initial_window);
|
||||
void RemoveStream(uint32_t stream_id);
|
||||
int64_t ConnectionAvailable() const { return conn_out_; }
|
||||
int64_t StreamAvailable(uint32_t stream_id) const;
|
||||
|
||||
// Inbound: track consumed bytes; the connection emits WINDOW_UPDATE.
|
||||
void ConsumedConnection(std::size_t n) { conn_in_used_ += n; }
|
||||
void ConsumedStream(uint32_t stream_id, std::size_t n);
|
||||
std::size_t TakeConnectionRefund();
|
||||
std::size_t TakeStreamRefund(uint32_t stream_id);
|
||||
|
||||
private:
|
||||
int64_t conn_out_;
|
||||
std::unordered_map<uint32_t, int64_t> stream_out_;
|
||||
std::size_t conn_in_used_ = 0;
|
||||
std::unordered_map<uint32_t, std::size_t> stream_in_used_;
|
||||
};
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,344 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 7541. HPACK codec.
|
||||
#include "hpack.h"
|
||||
|
||||
#include "runtime/caps.h"
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
namespace {
|
||||
|
||||
struct StaticEntry {
|
||||
const char* name;
|
||||
const char* value;
|
||||
};
|
||||
|
||||
const uint32_t kHuffmanCodes[][2] = {
|
||||
#include "huffman_table.inc"
|
||||
};
|
||||
|
||||
const StaticEntry kStaticTable[] = {
|
||||
#include "static_table.inc"
|
||||
};
|
||||
|
||||
constexpr std::size_t kStaticCount =
|
||||
sizeof(kStaticTable) / sizeof(kStaticTable[0]); // 62 with slot 0 unused
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string HuffmanCodec::Encode(std::string_view in) {
|
||||
std::string out;
|
||||
uint64_t acc = 0;
|
||||
int bits = 0;
|
||||
auto push = [&](uint32_t code, int len) {
|
||||
acc = (acc << len) | code;
|
||||
bits += len;
|
||||
while (bits >= 8) {
|
||||
bits -= 8;
|
||||
out.push_back((char)((acc >> bits) & 0xff));
|
||||
}
|
||||
};
|
||||
for (unsigned char c : in) {
|
||||
push(kHuffmanCodes[c][0], (int)kHuffmanCodes[c][1]);
|
||||
}
|
||||
if (bits > 0) {
|
||||
// Pad with ones (EOS prefix) per RFC 7541 section 5.2.
|
||||
acc = (acc << (8 - bits)) | ((1u << (8 - bits)) - 1u);
|
||||
out.push_back((char)(acc & 0xff));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct TrieNode {
|
||||
int child[2] = {-1, -1};
|
||||
int symbol = -1; // 0..256, or -1 for interior
|
||||
};
|
||||
|
||||
const std::vector<TrieNode>& DecodeTrie() {
|
||||
static const std::vector<TrieNode> trie = [] {
|
||||
std::vector<TrieNode> t(1);
|
||||
for (int s = 0; s < 257; ++s) {
|
||||
uint32_t code = kHuffmanCodes[s][0];
|
||||
int nbits = (int)kHuffmanCodes[s][1];
|
||||
int node = 0;
|
||||
for (int i = nbits - 1; i >= 0; --i) {
|
||||
int bit = (code >> i) & 1;
|
||||
if (t[(std::size_t)node].child[bit] < 0) {
|
||||
t[(std::size_t)node].child[bit] = (int)t.size();
|
||||
t.emplace_back();
|
||||
}
|
||||
node = t[(std::size_t)node].child[bit];
|
||||
}
|
||||
t[(std::size_t)node].symbol = s;
|
||||
}
|
||||
return t;
|
||||
}();
|
||||
return trie;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string> HuffmanCodec::Decode(const char* data,
|
||||
std::size_t len) {
|
||||
const std::vector<TrieNode>& trie = DecodeTrie();
|
||||
std::string out;
|
||||
int node = 0;
|
||||
int depth = 0; // bits since the last emitted symbol
|
||||
bool ones_only = true; // partial path is all ones (EOS prefix)
|
||||
for (std::size_t i = 0; i < len; ++i) {
|
||||
unsigned char c = (unsigned char)data[i];
|
||||
for (int b = 7; b >= 0; --b) {
|
||||
int bit = (c >> b) & 1;
|
||||
int next = trie[(std::size_t)node].child[bit];
|
||||
if (next < 0) return std::nullopt;
|
||||
node = next;
|
||||
++depth;
|
||||
ones_only = ones_only && (bit == 1);
|
||||
int sym = trie[(std::size_t)node].symbol;
|
||||
if (sym >= 0) {
|
||||
if (sym == 256) return std::nullopt; // EOS in content
|
||||
out.push_back((char)sym);
|
||||
node = 0;
|
||||
depth = 0;
|
||||
ones_only = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// End state: exact symbol boundary, or an all-ones EOS-prefix padding of
|
||||
// at most 7 bits. This matches the reference COMPLETE flag semantics.
|
||||
if (node == 0) return out;
|
||||
if (ones_only && depth <= 7) return out;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
HpackEncoder::HpackEncoder(std::size_t max_table_size)
|
||||
: max_table_size_(max_table_size) {}
|
||||
|
||||
void HpackEncoder::SetMaxTableSize(std::size_t n) { max_table_size_ = n; }
|
||||
|
||||
namespace {
|
||||
|
||||
void EncodeInt(std::string& out, uint32_t value, uint8_t prefix_bits,
|
||||
uint8_t prefix) {
|
||||
uint8_t max = (uint8_t)((1u << prefix_bits) - 1u);
|
||||
if (value < max) {
|
||||
out.push_back((char)(prefix | (uint8_t)value));
|
||||
return;
|
||||
}
|
||||
out.push_back((char)(prefix | max));
|
||||
value -= max;
|
||||
while (value >= 128) {
|
||||
out.push_back((char)((value & 0x7f) | 0x80));
|
||||
value >>= 7;
|
||||
}
|
||||
out.push_back((char)value);
|
||||
}
|
||||
|
||||
void EncodeString(std::string& out, const std::string& s) {
|
||||
// Literal without Huffman: smaller code, always valid. Huffman saving is
|
||||
// an encoder optimization, not an interop requirement.
|
||||
EncodeInt(out, (uint32_t)s.size(), 7, 0x00);
|
||||
out.append(s);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string HpackEncoder::Encode(const std::vector<HpackField>& fields) {
|
||||
(void)max_table_size_;
|
||||
std::string out;
|
||||
for (const auto& f : fields) {
|
||||
int full = -1;
|
||||
int name_only = -1;
|
||||
for (std::size_t i = 1; i < kStaticCount; ++i) {
|
||||
if (kStaticTable[i].name == f.name) {
|
||||
if (name_only < 0) name_only = (int)i;
|
||||
if (kStaticTable[i].value == f.value) {
|
||||
full = (int)i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (full >= 0) {
|
||||
EncodeInt(out, (uint32_t)full, 7, 0x80); // indexed field
|
||||
continue;
|
||||
}
|
||||
if (name_only >= 0) {
|
||||
// Literal without indexing, indexed name.
|
||||
EncodeInt(out, (uint32_t)name_only, 4, 0x00);
|
||||
EncodeString(out, f.value);
|
||||
continue;
|
||||
}
|
||||
// Literal without indexing, new name.
|
||||
out.push_back((char)0x00);
|
||||
EncodeString(out, f.name);
|
||||
EncodeString(out, f.value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
HpackDecoder::HpackDecoder(std::size_t max_table_size,
|
||||
std::size_t max_header_list)
|
||||
: max_table_size_(max_table_size), max_header_list_(max_header_list) {}
|
||||
|
||||
void HpackDecoder::SetMaxTableSize(std::size_t n) {
|
||||
max_table_size_ = n;
|
||||
EvictTo(n);
|
||||
}
|
||||
|
||||
HpackError HpackDecoder::DecodeInt(const char*& p, const char* end,
|
||||
uint8_t prefix_bits, uint32_t& out) {
|
||||
if (p >= end) return HpackError::Truncated;
|
||||
uint8_t max = (uint8_t)((1u << prefix_bits) - 1u);
|
||||
uint32_t v = (uint32_t)((unsigned char)*p & max);
|
||||
++p;
|
||||
if (v < max) {
|
||||
out = v;
|
||||
return HpackError::Ok;
|
||||
}
|
||||
uint32_t m = 0;
|
||||
for (;;) {
|
||||
if (p >= end) return HpackError::Truncated;
|
||||
uint8_t b = (unsigned char)*p++;
|
||||
if (m >= 28 && (b & 0x7f) >= (1u << (32 - m))) {
|
||||
return HpackError::BadInteger;
|
||||
}
|
||||
v += (uint32_t)(b & 0x7f) << m;
|
||||
if ((b & 0x80) == 0) break;
|
||||
m += 7;
|
||||
if (m >= 35) return HpackError::BadInteger;
|
||||
}
|
||||
out = v;
|
||||
return HpackError::Ok;
|
||||
}
|
||||
|
||||
HpackError HpackDecoder::DecodeString(const char*& p, const char* end,
|
||||
std::string& out) {
|
||||
if (p >= end) return HpackError::Truncated;
|
||||
bool huffman = ((unsigned char)*p & 0x80) != 0;
|
||||
uint32_t len = 0;
|
||||
HpackError e = DecodeInt(p, end, 7, len);
|
||||
if (e != HpackError::Ok) return e;
|
||||
if ((std::size_t)(end - p) < len) return HpackError::Truncated;
|
||||
if (huffman) {
|
||||
std::optional<std::string> s = HuffmanCodec::Decode(p, len);
|
||||
if (!s.has_value()) return HpackError::BadHuffman;
|
||||
out = std::move(*s);
|
||||
} else {
|
||||
out.assign(p, len);
|
||||
}
|
||||
p += len;
|
||||
return HpackError::Ok;
|
||||
}
|
||||
|
||||
HpackError HpackDecoder::Lookup(uint32_t index, HpackField& out) const {
|
||||
if (index == 0) return HpackError::BadIndex;
|
||||
if (index < kStaticCount) {
|
||||
out.name = kStaticTable[index].name;
|
||||
out.value = kStaticTable[index].value;
|
||||
return HpackError::Ok;
|
||||
}
|
||||
uint32_t dyn = index - (uint32_t)kStaticCount;
|
||||
if (dyn >= dynamic_.size()) return HpackError::BadIndex;
|
||||
out = dynamic_[dyn];
|
||||
return HpackError::Ok;
|
||||
}
|
||||
|
||||
void HpackDecoder::EvictTo(std::size_t limit) {
|
||||
while (table_bytes_ > limit && !dynamic_.empty()) {
|
||||
const HpackField& back = dynamic_.back();
|
||||
table_bytes_ -= back.name.size() + back.value.size() + kEntryOverhead;
|
||||
dynamic_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
void HpackDecoder::Insert(HpackField f) {
|
||||
std::size_t sz = f.name.size() + f.value.size() + kEntryOverhead;
|
||||
if (sz > max_table_size_) {
|
||||
dynamic_.clear();
|
||||
table_bytes_ = 0;
|
||||
return;
|
||||
}
|
||||
EvictTo(max_table_size_ - sz);
|
||||
table_bytes_ += sz;
|
||||
dynamic_.push_front(std::move(f));
|
||||
}
|
||||
|
||||
HpackError HpackDecoder::Decode(const char* data, std::size_t len,
|
||||
std::vector<HpackField>& out) {
|
||||
const char* p = data;
|
||||
const char* end = data + len;
|
||||
std::size_t list_bytes = 0;
|
||||
while (p < end) {
|
||||
uint8_t b = (unsigned char)*p;
|
||||
if (b & 0x80) {
|
||||
// Indexed field.
|
||||
uint32_t index = 0;
|
||||
HpackError e = DecodeInt(p, end, 7, index);
|
||||
if (e != HpackError::Ok) return e;
|
||||
HpackField f;
|
||||
e = Lookup(index, f);
|
||||
if (e != HpackError::Ok) return e;
|
||||
list_bytes += f.name.size() + f.value.size() + kEntryOverhead;
|
||||
if (list_bytes > max_header_list_) {
|
||||
return HpackError::HeaderListTooLarge;
|
||||
}
|
||||
out.push_back(std::move(f));
|
||||
} else if ((b & 0xc0) == 0x40) {
|
||||
// Literal with incremental indexing.
|
||||
uint32_t index = 0;
|
||||
HpackError e = DecodeInt(p, end, 6, index);
|
||||
if (e != HpackError::Ok) return e;
|
||||
HpackField f;
|
||||
if (index == 0) {
|
||||
e = DecodeString(p, end, f.name);
|
||||
if (e != HpackError::Ok) return e;
|
||||
} else {
|
||||
HpackField t;
|
||||
e = Lookup(index, t);
|
||||
if (e != HpackError::Ok) return e;
|
||||
f.name = std::move(t.name);
|
||||
}
|
||||
e = DecodeString(p, end, f.value);
|
||||
if (e != HpackError::Ok) return e;
|
||||
list_bytes += f.name.size() + f.value.size() + kEntryOverhead;
|
||||
if (list_bytes > max_header_list_) {
|
||||
return HpackError::HeaderListTooLarge;
|
||||
}
|
||||
out.push_back(f);
|
||||
Insert(std::move(f));
|
||||
} else if ((b & 0xe0) == 0x20) {
|
||||
// Table size update.
|
||||
uint32_t size = 0;
|
||||
HpackError e = DecodeInt(p, end, 5, size);
|
||||
if (e != HpackError::Ok) return e;
|
||||
if (size > max_table_size_) return HpackError::TableSizeChanged;
|
||||
EvictTo(size);
|
||||
} else {
|
||||
// Literal without indexing (0x00) or never indexed (0x10).
|
||||
uint32_t index = 0;
|
||||
HpackError e = DecodeInt(p, end, 4, index);
|
||||
if (e != HpackError::Ok) return e;
|
||||
HpackField f;
|
||||
if (index == 0) {
|
||||
e = DecodeString(p, end, f.name);
|
||||
if (e != HpackError::Ok) return e;
|
||||
} else {
|
||||
HpackField t;
|
||||
e = Lookup(index, t);
|
||||
if (e != HpackError::Ok) return e;
|
||||
f.name = std::move(t.name);
|
||||
}
|
||||
e = DecodeString(p, end, f.value);
|
||||
if (e != HpackError::Ok) return e;
|
||||
list_bytes += f.name.size() + f.value.size() + kEntryOverhead;
|
||||
if (list_bytes > max_header_list_) {
|
||||
return HpackError::HeaderListTooLarge;
|
||||
}
|
||||
out.push_back(std::move(f));
|
||||
}
|
||||
if (out.size() > caps::kHeaderFieldMax) return HpackError::TooManyFields;
|
||||
}
|
||||
return HpackError::Ok;
|
||||
}
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,76 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 7541. HPACK field compression: static
|
||||
// plus dynamic table, Huffman string codec. The encoder emits indexed fields
|
||||
// for static hits and literals without indexing otherwise (no dynamic table
|
||||
// inserts); the decoder implements the full representation set including
|
||||
// incremental indexing and table size updates for interop.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
struct HpackField {
|
||||
std::string name;
|
||||
std::string value;
|
||||
};
|
||||
|
||||
enum class HpackError {
|
||||
Ok,
|
||||
Truncated,
|
||||
BadIndex,
|
||||
BadInteger,
|
||||
BadHuffman,
|
||||
TableSizeChanged,
|
||||
HeaderListTooLarge,
|
||||
TooManyFields,
|
||||
};
|
||||
|
||||
// Huffman string codec over the RFC 7541 Appendix B table.
|
||||
class HuffmanCodec {
|
||||
public:
|
||||
static std::string Encode(std::string_view in);
|
||||
// Nullopt on invalid encoding (bad padding, EOS symbol, overlong).
|
||||
static std::optional<std::string> Decode(const char* data, std::size_t len);
|
||||
};
|
||||
|
||||
class HpackEncoder {
|
||||
public:
|
||||
explicit HpackEncoder(std::size_t max_table_size = 4096);
|
||||
std::string Encode(const std::vector<HpackField>& fields);
|
||||
void SetMaxTableSize(std::size_t n);
|
||||
|
||||
private:
|
||||
std::size_t max_table_size_;
|
||||
};
|
||||
|
||||
class HpackDecoder {
|
||||
public:
|
||||
explicit HpackDecoder(std::size_t max_table_size = 4096,
|
||||
std::size_t max_header_list = 65536);
|
||||
HpackError Decode(const char* data, std::size_t len,
|
||||
std::vector<HpackField>& out);
|
||||
void SetMaxTableSize(std::size_t n);
|
||||
std::size_t table_size() const { return table_bytes_; }
|
||||
|
||||
private:
|
||||
static constexpr std::size_t kEntryOverhead = 32;
|
||||
HpackError DecodeInt(const char*& p, const char* end, uint8_t prefix_bits,
|
||||
uint32_t& out);
|
||||
HpackError DecodeString(const char*& p, const char* end, std::string& out);
|
||||
HpackError Lookup(uint32_t index, HpackField& out) const;
|
||||
void Insert(HpackField f);
|
||||
void EvictTo(std::size_t limit);
|
||||
|
||||
std::size_t max_table_size_;
|
||||
std::size_t max_header_list_;
|
||||
std::size_t table_bytes_ = 0;
|
||||
std::deque<HpackField> dynamic_;
|
||||
};
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,259 @@
|
||||
// Generated from RFC 7541 Appendix B, cross-checked against python-hpack.
|
||||
// Entry: {code (LSB aligned), bit length}. Index 256 is EOS (encode-only guard).
|
||||
{0x1ff8u, 13u}, // 0
|
||||
{0x7fffd8u, 23u}, // 1
|
||||
{0xfffffe2u, 28u}, // 2
|
||||
{0xfffffe3u, 28u}, // 3
|
||||
{0xfffffe4u, 28u}, // 4
|
||||
{0xfffffe5u, 28u}, // 5
|
||||
{0xfffffe6u, 28u}, // 6
|
||||
{0xfffffe7u, 28u}, // 7
|
||||
{0xfffffe8u, 28u}, // 8
|
||||
{0xffffeau, 24u}, // 9
|
||||
{0x3ffffffcu, 30u}, // 10
|
||||
{0xfffffe9u, 28u}, // 11
|
||||
{0xfffffeau, 28u}, // 12
|
||||
{0x3ffffffdu, 30u}, // 13
|
||||
{0xfffffebu, 28u}, // 14
|
||||
{0xfffffecu, 28u}, // 15
|
||||
{0xfffffedu, 28u}, // 16
|
||||
{0xfffffeeu, 28u}, // 17
|
||||
{0xfffffefu, 28u}, // 18
|
||||
{0xffffff0u, 28u}, // 19
|
||||
{0xffffff1u, 28u}, // 20
|
||||
{0xffffff2u, 28u}, // 21
|
||||
{0x3ffffffeu, 30u}, // 22
|
||||
{0xffffff3u, 28u}, // 23
|
||||
{0xffffff4u, 28u}, // 24
|
||||
{0xffffff5u, 28u}, // 25
|
||||
{0xffffff6u, 28u}, // 26
|
||||
{0xffffff7u, 28u}, // 27
|
||||
{0xffffff8u, 28u}, // 28
|
||||
{0xffffff9u, 28u}, // 29
|
||||
{0xffffffau, 28u}, // 30
|
||||
{0xffffffbu, 28u}, // 31
|
||||
{0x14u, 6u}, // 32
|
||||
{0x3f8u, 10u}, // 33
|
||||
{0x3f9u, 10u}, // 34
|
||||
{0xffau, 12u}, // 35
|
||||
{0x1ff9u, 13u}, // 36
|
||||
{0x15u, 6u}, // 37
|
||||
{0xf8u, 8u}, // 38
|
||||
{0x7fau, 11u}, // 39
|
||||
{0x3fau, 10u}, // 40
|
||||
{0x3fbu, 10u}, // 41
|
||||
{0xf9u, 8u}, // 42
|
||||
{0x7fbu, 11u}, // 43
|
||||
{0xfau, 8u}, // 44
|
||||
{0x16u, 6u}, // 45
|
||||
{0x17u, 6u}, // 46
|
||||
{0x18u, 6u}, // 47
|
||||
{0x0u, 5u}, // 48
|
||||
{0x1u, 5u}, // 49
|
||||
{0x2u, 5u}, // 50
|
||||
{0x19u, 6u}, // 51
|
||||
{0x1au, 6u}, // 52
|
||||
{0x1bu, 6u}, // 53
|
||||
{0x1cu, 6u}, // 54
|
||||
{0x1du, 6u}, // 55
|
||||
{0x1eu, 6u}, // 56
|
||||
{0x1fu, 6u}, // 57
|
||||
{0x5cu, 7u}, // 58
|
||||
{0xfbu, 8u}, // 59
|
||||
{0x7ffcu, 15u}, // 60
|
||||
{0x20u, 6u}, // 61
|
||||
{0xffbu, 12u}, // 62
|
||||
{0x3fcu, 10u}, // 63
|
||||
{0x1ffau, 13u}, // 64
|
||||
{0x21u, 6u}, // 65
|
||||
{0x5du, 7u}, // 66
|
||||
{0x5eu, 7u}, // 67
|
||||
{0x5fu, 7u}, // 68
|
||||
{0x60u, 7u}, // 69
|
||||
{0x61u, 7u}, // 70
|
||||
{0x62u, 7u}, // 71
|
||||
{0x63u, 7u}, // 72
|
||||
{0x64u, 7u}, // 73
|
||||
{0x65u, 7u}, // 74
|
||||
{0x66u, 7u}, // 75
|
||||
{0x67u, 7u}, // 76
|
||||
{0x68u, 7u}, // 77
|
||||
{0x69u, 7u}, // 78
|
||||
{0x6au, 7u}, // 79
|
||||
{0x6bu, 7u}, // 80
|
||||
{0x6cu, 7u}, // 81
|
||||
{0x6du, 7u}, // 82
|
||||
{0x6eu, 7u}, // 83
|
||||
{0x6fu, 7u}, // 84
|
||||
{0x70u, 7u}, // 85
|
||||
{0x71u, 7u}, // 86
|
||||
{0x72u, 7u}, // 87
|
||||
{0xfcu, 8u}, // 88
|
||||
{0x73u, 7u}, // 89
|
||||
{0xfdu, 8u}, // 90
|
||||
{0x1ffbu, 13u}, // 91
|
||||
{0x7fff0u, 19u}, // 92
|
||||
{0x1ffcu, 13u}, // 93
|
||||
{0x3ffcu, 14u}, // 94
|
||||
{0x22u, 6u}, // 95
|
||||
{0x7ffdu, 15u}, // 96
|
||||
{0x3u, 5u}, // 97
|
||||
{0x23u, 6u}, // 98
|
||||
{0x4u, 5u}, // 99
|
||||
{0x24u, 6u}, // 100
|
||||
{0x5u, 5u}, // 101
|
||||
{0x25u, 6u}, // 102
|
||||
{0x26u, 6u}, // 103
|
||||
{0x27u, 6u}, // 104
|
||||
{0x6u, 5u}, // 105
|
||||
{0x74u, 7u}, // 106
|
||||
{0x75u, 7u}, // 107
|
||||
{0x28u, 6u}, // 108
|
||||
{0x29u, 6u}, // 109
|
||||
{0x2au, 6u}, // 110
|
||||
{0x7u, 5u}, // 111
|
||||
{0x2bu, 6u}, // 112
|
||||
{0x76u, 7u}, // 113
|
||||
{0x2cu, 6u}, // 114
|
||||
{0x8u, 5u}, // 115
|
||||
{0x9u, 5u}, // 116
|
||||
{0x2du, 6u}, // 117
|
||||
{0x77u, 7u}, // 118
|
||||
{0x78u, 7u}, // 119
|
||||
{0x79u, 7u}, // 120
|
||||
{0x7au, 7u}, // 121
|
||||
{0x7bu, 7u}, // 122
|
||||
{0x7ffeu, 15u}, // 123
|
||||
{0x7fcu, 11u}, // 124
|
||||
{0x3ffdu, 14u}, // 125
|
||||
{0x1ffdu, 13u}, // 126
|
||||
{0xffffffcu, 28u}, // 127
|
||||
{0xfffe6u, 20u}, // 128
|
||||
{0x3fffd2u, 22u}, // 129
|
||||
{0xfffe7u, 20u}, // 130
|
||||
{0xfffe8u, 20u}, // 131
|
||||
{0x3fffd3u, 22u}, // 132
|
||||
{0x3fffd4u, 22u}, // 133
|
||||
{0x3fffd5u, 22u}, // 134
|
||||
{0x7fffd9u, 23u}, // 135
|
||||
{0x3fffd6u, 22u}, // 136
|
||||
{0x7fffdau, 23u}, // 137
|
||||
{0x7fffdbu, 23u}, // 138
|
||||
{0x7fffdcu, 23u}, // 139
|
||||
{0x7fffddu, 23u}, // 140
|
||||
{0x7fffdeu, 23u}, // 141
|
||||
{0xffffebu, 24u}, // 142
|
||||
{0x7fffdfu, 23u}, // 143
|
||||
{0xffffecu, 24u}, // 144
|
||||
{0xffffedu, 24u}, // 145
|
||||
{0x3fffd7u, 22u}, // 146
|
||||
{0x7fffe0u, 23u}, // 147
|
||||
{0xffffeeu, 24u}, // 148
|
||||
{0x7fffe1u, 23u}, // 149
|
||||
{0x7fffe2u, 23u}, // 150
|
||||
{0x7fffe3u, 23u}, // 151
|
||||
{0x7fffe4u, 23u}, // 152
|
||||
{0x1fffdcu, 21u}, // 153
|
||||
{0x3fffd8u, 22u}, // 154
|
||||
{0x7fffe5u, 23u}, // 155
|
||||
{0x3fffd9u, 22u}, // 156
|
||||
{0x7fffe6u, 23u}, // 157
|
||||
{0x7fffe7u, 23u}, // 158
|
||||
{0xffffefu, 24u}, // 159
|
||||
{0x3fffdau, 22u}, // 160
|
||||
{0x1fffddu, 21u}, // 161
|
||||
{0xfffe9u, 20u}, // 162
|
||||
{0x3fffdbu, 22u}, // 163
|
||||
{0x3fffdcu, 22u}, // 164
|
||||
{0x7fffe8u, 23u}, // 165
|
||||
{0x7fffe9u, 23u}, // 166
|
||||
{0x1fffdeu, 21u}, // 167
|
||||
{0x7fffeau, 23u}, // 168
|
||||
{0x3fffddu, 22u}, // 169
|
||||
{0x3fffdeu, 22u}, // 170
|
||||
{0xfffff0u, 24u}, // 171
|
||||
{0x1fffdfu, 21u}, // 172
|
||||
{0x3fffdfu, 22u}, // 173
|
||||
{0x7fffebu, 23u}, // 174
|
||||
{0x7fffecu, 23u}, // 175
|
||||
{0x1fffe0u, 21u}, // 176
|
||||
{0x1fffe1u, 21u}, // 177
|
||||
{0x3fffe0u, 22u}, // 178
|
||||
{0x1fffe2u, 21u}, // 179
|
||||
{0x7fffedu, 23u}, // 180
|
||||
{0x3fffe1u, 22u}, // 181
|
||||
{0x7fffeeu, 23u}, // 182
|
||||
{0x7fffefu, 23u}, // 183
|
||||
{0xfffeau, 20u}, // 184
|
||||
{0x3fffe2u, 22u}, // 185
|
||||
{0x3fffe3u, 22u}, // 186
|
||||
{0x3fffe4u, 22u}, // 187
|
||||
{0x7ffff0u, 23u}, // 188
|
||||
{0x3fffe5u, 22u}, // 189
|
||||
{0x3fffe6u, 22u}, // 190
|
||||
{0x7ffff1u, 23u}, // 191
|
||||
{0x3ffffe0u, 26u}, // 192
|
||||
{0x3ffffe1u, 26u}, // 193
|
||||
{0xfffebu, 20u}, // 194
|
||||
{0x7fff1u, 19u}, // 195
|
||||
{0x3fffe7u, 22u}, // 196
|
||||
{0x7ffff2u, 23u}, // 197
|
||||
{0x3fffe8u, 22u}, // 198
|
||||
{0x1ffffecu, 25u}, // 199
|
||||
{0x3ffffe2u, 26u}, // 200
|
||||
{0x3ffffe3u, 26u}, // 201
|
||||
{0x3ffffe4u, 26u}, // 202
|
||||
{0x7ffffdeu, 27u}, // 203
|
||||
{0x7ffffdfu, 27u}, // 204
|
||||
{0x3ffffe5u, 26u}, // 205
|
||||
{0xfffff1u, 24u}, // 206
|
||||
{0x1ffffedu, 25u}, // 207
|
||||
{0x7fff2u, 19u}, // 208
|
||||
{0x1fffe3u, 21u}, // 209
|
||||
{0x3ffffe6u, 26u}, // 210
|
||||
{0x7ffffe0u, 27u}, // 211
|
||||
{0x7ffffe1u, 27u}, // 212
|
||||
{0x3ffffe7u, 26u}, // 213
|
||||
{0x7ffffe2u, 27u}, // 214
|
||||
{0xfffff2u, 24u}, // 215
|
||||
{0x1fffe4u, 21u}, // 216
|
||||
{0x1fffe5u, 21u}, // 217
|
||||
{0x3ffffe8u, 26u}, // 218
|
||||
{0x3ffffe9u, 26u}, // 219
|
||||
{0xffffffdu, 28u}, // 220
|
||||
{0x7ffffe3u, 27u}, // 221
|
||||
{0x7ffffe4u, 27u}, // 222
|
||||
{0x7ffffe5u, 27u}, // 223
|
||||
{0xfffecu, 20u}, // 224
|
||||
{0xfffff3u, 24u}, // 225
|
||||
{0xfffedu, 20u}, // 226
|
||||
{0x1fffe6u, 21u}, // 227
|
||||
{0x3fffe9u, 22u}, // 228
|
||||
{0x1fffe7u, 21u}, // 229
|
||||
{0x1fffe8u, 21u}, // 230
|
||||
{0x7ffff3u, 23u}, // 231
|
||||
{0x3fffeau, 22u}, // 232
|
||||
{0x3fffebu, 22u}, // 233
|
||||
{0x1ffffeeu, 25u}, // 234
|
||||
{0x1ffffefu, 25u}, // 235
|
||||
{0xfffff4u, 24u}, // 236
|
||||
{0xfffff5u, 24u}, // 237
|
||||
{0x3ffffeau, 26u}, // 238
|
||||
{0x7ffff4u, 23u}, // 239
|
||||
{0x3ffffebu, 26u}, // 240
|
||||
{0x7ffffe6u, 27u}, // 241
|
||||
{0x3ffffecu, 26u}, // 242
|
||||
{0x3ffffedu, 26u}, // 243
|
||||
{0x7ffffe7u, 27u}, // 244
|
||||
{0x7ffffe8u, 27u}, // 245
|
||||
{0x7ffffe9u, 27u}, // 246
|
||||
{0x7ffffeau, 27u}, // 247
|
||||
{0x7ffffebu, 27u}, // 248
|
||||
{0xffffffeu, 28u}, // 249
|
||||
{0x7ffffecu, 27u}, // 250
|
||||
{0x7ffffedu, 27u}, // 251
|
||||
{0x7ffffeeu, 27u}, // 252
|
||||
{0x7ffffefu, 27u}, // 253
|
||||
{0x7fffff0u, 27u}, // 254
|
||||
{0x3ffffeeu, 26u}, // 255
|
||||
{0x3fffffffu, 30u}, // 256
|
||||
@@ -0,0 +1,102 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113 sections 6.5, 10. SETTINGS frame
|
||||
// payload codec with validation. No server push: ENABLE_PUSH must be 0.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "runtime/caps.h"
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
struct Settings {
|
||||
uint32_t header_table_size = 4096;
|
||||
bool enable_push = false; // MUST stay false; push is gone in RFC 9113.
|
||||
uint32_t max_concurrent_streams = caps::kH2MaxConcurrentStreamsDefault;
|
||||
uint32_t initial_window_size = 65535;
|
||||
uint32_t max_frame_size = 16384;
|
||||
uint32_t max_header_list_size = 65536;
|
||||
};
|
||||
|
||||
enum class SettingsError {
|
||||
Ok,
|
||||
ProtocolError, // bad length, ENABLE_PUSH=1, bad MAX_FRAME_SIZE
|
||||
FlowControlError, // bad INITIAL_WINDOW_SIZE
|
||||
CompressionError, // bad HEADER_TABLE_SIZE change discipline
|
||||
};
|
||||
|
||||
// Decodes a SETTINGS payload into out (applies peer values, clamped to our
|
||||
// ceilings). Returns the connection error to raise, if any.
|
||||
inline SettingsError DecodeSettingsPayload(const char* data, std::size_t len,
|
||||
Settings& out) {
|
||||
if (len % 6 != 0) return SettingsError::ProtocolError;
|
||||
for (std::size_t i = 0; i < len; i += 6) {
|
||||
uint16_t id = ((uint16_t)(unsigned char)data[i] << 8) |
|
||||
(uint16_t)(unsigned char)data[i + 1];
|
||||
uint32_t v = ((uint32_t)(unsigned char)data[i + 2] << 24) |
|
||||
((uint32_t)(unsigned char)data[i + 3] << 16) |
|
||||
((uint32_t)(unsigned char)data[i + 4] << 8) |
|
||||
(uint32_t)(unsigned char)data[i + 5];
|
||||
switch (id) {
|
||||
case 0x1:
|
||||
if (v > caps::kH2HeaderTableCeiling) return SettingsError::CompressionError;
|
||||
out.header_table_size = v;
|
||||
break;
|
||||
case 0x2:
|
||||
// Deprecated push knob. Real clients (hyper-h2 included) still send
|
||||
// ENABLE_PUSH=1; accept and ignore it. We never push, so the value
|
||||
// is meaningless to us either way.
|
||||
out.enable_push = false;
|
||||
break;
|
||||
case 0x3:
|
||||
out.max_concurrent_streams = v;
|
||||
if (out.max_concurrent_streams > caps::kH2MaxConcurrentStreamsCeiling) {
|
||||
out.max_concurrent_streams = caps::kH2MaxConcurrentStreamsCeiling;
|
||||
}
|
||||
break;
|
||||
case 0x4:
|
||||
if (v > 0x7fffffffu) return SettingsError::FlowControlError;
|
||||
out.initial_window_size = v;
|
||||
break;
|
||||
case 0x5:
|
||||
if (v < 16384 || v > caps::kH2MaxFrameCeiling) {
|
||||
return SettingsError::ProtocolError;
|
||||
}
|
||||
out.max_frame_size = v;
|
||||
break;
|
||||
case 0x6:
|
||||
out.max_header_list_size = v;
|
||||
if (out.max_header_list_size > caps::kH2HeaderListMax) {
|
||||
out.max_header_list_size = caps::kH2HeaderListMax;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// Unknown identifiers are ignored.
|
||||
break;
|
||||
}
|
||||
}
|
||||
return SettingsError::Ok;
|
||||
}
|
||||
|
||||
// Encodes our SETTINGS for the server preface.
|
||||
inline std::string EncodeSettingsPayload(const Settings& s) {
|
||||
std::string out;
|
||||
auto param = [&out](uint16_t id, uint32_t v) {
|
||||
out.push_back((char)(id >> 8));
|
||||
out.push_back((char)(id & 0xff));
|
||||
out.push_back((char)(v >> 24));
|
||||
out.push_back((char)((v >> 16) & 0xff));
|
||||
out.push_back((char)((v >> 8) & 0xff));
|
||||
out.push_back((char)(v & 0xff));
|
||||
};
|
||||
param(0x1, s.header_table_size);
|
||||
param(0x3, s.max_concurrent_streams);
|
||||
param(0x4, s.initial_window_size);
|
||||
param(0x5, s.max_frame_size);
|
||||
param(0x6, s.max_header_list_size);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,64 @@
|
||||
// HPACK static table, RFC 7541 Appendix A, cross-checked against python-hpack.
|
||||
// Index 0 unused; entries 1..61.
|
||||
{"", ""},
|
||||
{":authority", ""},
|
||||
{":method", "GET"},
|
||||
{":method", "POST"},
|
||||
{":path", "/"},
|
||||
{":path", "/index.html"},
|
||||
{":scheme", "http"},
|
||||
{":scheme", "https"},
|
||||
{":status", "200"},
|
||||
{":status", "204"},
|
||||
{":status", "206"},
|
||||
{":status", "304"},
|
||||
{":status", "400"},
|
||||
{":status", "404"},
|
||||
{":status", "500"},
|
||||
{"accept-charset", ""},
|
||||
{"accept-encoding", "gzip, deflate"},
|
||||
{"accept-language", ""},
|
||||
{"accept-ranges", ""},
|
||||
{"accept", ""},
|
||||
{"access-control-allow-origin", ""},
|
||||
{"age", ""},
|
||||
{"allow", ""},
|
||||
{"authorization", ""},
|
||||
{"cache-control", ""},
|
||||
{"content-disposition", ""},
|
||||
{"content-encoding", ""},
|
||||
{"content-language", ""},
|
||||
{"content-length", ""},
|
||||
{"content-location", ""},
|
||||
{"content-range", ""},
|
||||
{"content-type", ""},
|
||||
{"cookie", ""},
|
||||
{"date", ""},
|
||||
{"etag", ""},
|
||||
{"expect", ""},
|
||||
{"expires", ""},
|
||||
{"from", ""},
|
||||
{"host", ""},
|
||||
{"if-match", ""},
|
||||
{"if-modified-since", ""},
|
||||
{"if-none-match", ""},
|
||||
{"if-range", ""},
|
||||
{"if-unmodified-since", ""},
|
||||
{"last-modified", ""},
|
||||
{"link", ""},
|
||||
{"location", ""},
|
||||
{"max-forwards", ""},
|
||||
{"proxy-authenticate", ""},
|
||||
{"proxy-authorization", ""},
|
||||
{"range", ""},
|
||||
{"referer", ""},
|
||||
{"refresh", ""},
|
||||
{"retry-after", ""},
|
||||
{"server", ""},
|
||||
{"set-cookie", ""},
|
||||
{"strict-transport-security", ""},
|
||||
{"transfer-encoding", ""},
|
||||
{"user-agent", ""},
|
||||
{"vary", ""},
|
||||
{"via", ""},
|
||||
{"www-authenticate", ""},
|
||||
@@ -0,0 +1,145 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113 section 5. Stream states.
|
||||
#include "stream.h"
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
namespace {
|
||||
constexpr uint32_t kNoError = 0x0;
|
||||
constexpr uint32_t kProtocolError = 0x1;
|
||||
constexpr uint32_t kCancel = 0x8;
|
||||
constexpr uint32_t kRefusedStream = 0x7;
|
||||
} // namespace
|
||||
|
||||
H2Stream::H2Stream(uint32_t id, std::size_t body_cap)
|
||||
: id_(id), body_cap_(body_cap) {}
|
||||
|
||||
StreamOutcome H2Stream::OnHeaders(const std::vector<HpackField>& fields,
|
||||
bool end_stream) {
|
||||
if (state_ == StreamState::Idle) {
|
||||
// First HEADERS: build the request head from pseudo-headers.
|
||||
std::string method, scheme, authority, path;
|
||||
for (const auto& f : fields) {
|
||||
if (f.name.empty() || f.name[0] != ':') {
|
||||
head_.headers.add(f.name, f.value);
|
||||
continue;
|
||||
}
|
||||
if (f.name == ":method") {
|
||||
if (!method.empty()) return {StreamEvent::LocalReset, kProtocolError};
|
||||
method = f.value;
|
||||
} else if (f.name == ":scheme") {
|
||||
if (!scheme.empty()) return {StreamEvent::LocalReset, kProtocolError};
|
||||
scheme = f.value;
|
||||
} else if (f.name == ":authority") {
|
||||
if (!authority.empty()) {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
authority = f.value;
|
||||
} else if (f.name == ":path") {
|
||||
if (!path.empty()) return {StreamEvent::LocalReset, kProtocolError};
|
||||
path = f.value;
|
||||
} else {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
}
|
||||
if (method.empty() || scheme.empty() || path.empty()) {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
if (method == "CONNECT") {
|
||||
// v1: plain tunnels are out of scope.
|
||||
return {StreamEvent::LocalReset, kRefusedStream};
|
||||
}
|
||||
head_.method = method;
|
||||
head_.target = path;
|
||||
head_.version = "HTTP/2";
|
||||
if (!authority.empty()) head_.headers.add("host", authority);
|
||||
head_complete_ = true;
|
||||
if (end_stream) {
|
||||
state_ = StreamState::HalfClosedRemote;
|
||||
return CompleteMessage();
|
||||
}
|
||||
state_ = StreamState::Open;
|
||||
return {StreamEvent::HeadersComplete, kNoError};
|
||||
}
|
||||
if (state_ == StreamState::Open) {
|
||||
// Trailers (second HEADERS must carry only regular fields).
|
||||
for (const auto& f : fields) {
|
||||
if (!f.name.empty() && f.name[0] == ':') {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
trailers_.add(f.name, f.value);
|
||||
}
|
||||
trailers_phase_ = true;
|
||||
if (end_stream) {
|
||||
state_ = StreamState::HalfClosedRemote;
|
||||
return CompleteMessage();
|
||||
}
|
||||
return {StreamEvent::HeadersComplete, kNoError};
|
||||
}
|
||||
if (state_ == StreamState::HalfClosedRemote) {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
|
||||
StreamOutcome H2Stream::OnData(const char* data, std::size_t len,
|
||||
bool end_stream) {
|
||||
if (state_ != StreamState::Open) {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
if (body_.size() + len > body_cap_) {
|
||||
return {StreamEvent::LocalReset, kCancel};
|
||||
}
|
||||
body_.append(data, len);
|
||||
if (end_stream) {
|
||||
state_ = StreamState::HalfClosedRemote;
|
||||
return CompleteMessage();
|
||||
}
|
||||
return {StreamEvent::None, kNoError};
|
||||
}
|
||||
|
||||
StreamOutcome H2Stream::OnRst(uint32_t code) {
|
||||
peer_code_ = code;
|
||||
state_ = StreamState::Closed;
|
||||
return {StreamEvent::ResetByPeer, kNoError};
|
||||
}
|
||||
|
||||
StreamOutcome H2Stream::OnWindowUpdate(uint32_t increment) {
|
||||
if (increment == 0) return {StreamEvent::LocalReset, kProtocolError};
|
||||
if (state_ == StreamState::Idle) {
|
||||
return {StreamEvent::LocalReset, kProtocolError};
|
||||
}
|
||||
return {StreamEvent::None, kNoError};
|
||||
}
|
||||
|
||||
void H2Stream::MarkResponseHeadersSent(bool end_stream) {
|
||||
if (state_ == StreamState::HalfClosedRemote) {
|
||||
state_ = end_stream ? StreamState::Closed : StreamState::HalfClosedLocal;
|
||||
} else if (state_ == StreamState::Open) {
|
||||
state_ =
|
||||
end_stream ? StreamState::HalfClosedLocal : StreamState::Open;
|
||||
} else if (state_ == StreamState::HalfClosedLocal && end_stream) {
|
||||
state_ = StreamState::Closed;
|
||||
}
|
||||
}
|
||||
|
||||
void H2Stream::MarkResponseDataSent(bool end_stream) {
|
||||
if (end_stream) {
|
||||
if (state_ == StreamState::HalfClosedRemote ||
|
||||
state_ == StreamState::HalfClosedLocal) {
|
||||
state_ = StreamState::Closed;
|
||||
} else if (state_ == StreamState::Open) {
|
||||
state_ = StreamState::HalfClosedLocal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StreamOutcome H2Stream::LocalClose(uint32_t code) {
|
||||
state_ = StreamState::Closed;
|
||||
return {StreamEvent::LocalReset, code};
|
||||
}
|
||||
|
||||
StreamOutcome H2Stream::CompleteMessage() {
|
||||
return {StreamEvent::MessageComplete, kNoError};
|
||||
}
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
@@ -0,0 +1,81 @@
|
||||
// Spec: plans/01-runtime.md 6.4, RFC 9113 section 5. Server-side stream state
|
||||
// machine: idle, reserved, open, half-closed, closed. RST_STREAM on handler
|
||||
// cancel or caps.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "runtime/http/message.h"
|
||||
|
||||
#include "hpack.h"
|
||||
|
||||
namespace molo::runtime::http::v2 {
|
||||
|
||||
enum class StreamState {
|
||||
Idle,
|
||||
ReservedLocal,
|
||||
ReservedRemote,
|
||||
Open,
|
||||
HalfClosedLocal,
|
||||
HalfClosedRemote,
|
||||
Closed,
|
||||
};
|
||||
|
||||
enum class StreamEvent {
|
||||
None,
|
||||
// HEADERS completed the request head; body may follow via DATA.
|
||||
HeadersComplete,
|
||||
// END_STREAM seen: the full request is ready for dispatch.
|
||||
MessageComplete,
|
||||
ResetByPeer,
|
||||
// Local error with the RST code the connection must send.
|
||||
LocalReset,
|
||||
};
|
||||
|
||||
struct StreamOutcome {
|
||||
StreamEvent event = StreamEvent::None;
|
||||
uint32_t rst_code = 0;
|
||||
};
|
||||
|
||||
class H2Stream {
|
||||
public:
|
||||
explicit H2Stream(uint32_t id, std::size_t body_cap);
|
||||
|
||||
uint32_t id() const { return id_; }
|
||||
StreamState state() const { return state_; }
|
||||
const RequestHead& head() const { return head_; }
|
||||
const std::string& body() const { return body_; }
|
||||
const Headers& trailers() const { return trailers_; }
|
||||
bool head_complete() const { return head_complete_; }
|
||||
|
||||
// HEADERS frame payload (one decoded header list, CONTINUATION already
|
||||
// reassembled by the connection). end_stream reflects END_STREAM.
|
||||
StreamOutcome OnHeaders(const std::vector<HpackField>& fields,
|
||||
bool end_stream);
|
||||
StreamOutcome OnData(const char* data, std::size_t len, bool end_stream);
|
||||
StreamOutcome OnRst(uint32_t code);
|
||||
StreamOutcome OnWindowUpdate(uint32_t increment);
|
||||
|
||||
// Response path: HEADERS then DATA then close.
|
||||
void MarkResponseHeadersSent(bool end_stream);
|
||||
void MarkResponseDataSent(bool end_stream);
|
||||
StreamOutcome LocalClose(uint32_t code); // send RST_STREAM
|
||||
|
||||
private:
|
||||
StreamOutcome CompleteMessage();
|
||||
|
||||
uint32_t id_;
|
||||
std::size_t body_cap_;
|
||||
StreamState state_ = StreamState::Idle;
|
||||
RequestHead head_;
|
||||
std::string body_;
|
||||
Headers trailers_;
|
||||
bool head_complete_ = false;
|
||||
bool trailers_phase_ = false;
|
||||
uint32_t peer_code_ = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::runtime::http::v2
|
||||
Reference in New Issue
Block a user