Loading src/quic.cpp +56 −19 Changes for src/quic.cpp: 56 added lines, 19 removed lines. Original line number Diff line number Diff line Loading @@ -4259,10 +4259,19 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { auto& stream = _streams[stream_id]; stream.stream_id = stream_id; // True exactly once per stream: the very first STREAM frame seen for // it. Tracked via recv_frame_count rather than "recv_buffer empty + // recv_offset==0" — with incremental dispatch's buffer trimming (see // its comment further below), recv_buffer legitimately goes back to // empty mid-stream between dispatched chunks, which would otherwise // make this fire again and double-count MAX_STREAMS accounting below. bool is_first_frame_for_stream = (stream.recv_frame_count == 0); stream.recv_frame_count++; // Track peer-initiated stream count for MAX_STREAMS enforcement // Peer-initiated streams: client-initiated if we're server, server-initiated if we're client bool peer_initiated = (_is_server) ? ((stream_id & 0x01) == 0) : ((stream_id & 0x01) == 1); if (peer_initiated && stream.recv_buffer.empty() && stream.recv_offset == 0) { if (peer_initiated && is_first_frame_for_stream) { // First data on a new peer-initiated stream bool is_bidi = (stream_id % 4 == 0) || (stream_id % 4 == 1); if (is_bidi) { Loading Loading @@ -4343,21 +4352,29 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { if (stream_len > 0) { uint64_t end_offset = stream_offset + stream_len; // Diagnostic: track frame arrival for server-side large streams if (_is_server && stream_len > 0) { stream.recv_frame_count++; } // Grow buffer if needed if (end_offset > stream.recv_buffer.size()) { stream.recv_buffer.resize(end_offset, 0); // recv_buffer only ever holds the not-yet-dispatched tail of the // stream (see incremental dispatch's trimming further below); // recv_base_offset is the absolute stream offset corresponding to // recv_buffer[0]. For the (default) non-incremental path, // recv_base_offset stays 0 and this is exactly the old absolute // indexing. Bytes at or before recv_base_offset were already // dispatched (or belong to a duplicate/retransmitted frame) and // must not be written — only the portion of this frame at or after // recv_base_offset, if any, still needs storing. uint64_t buf_end = (end_offset > stream.recv_base_offset) ? (end_offset - stream.recv_base_offset) : 0; if (buf_end > stream.recv_buffer.size()) { stream.recv_buffer.resize(buf_end, 0); } uint64_t write_start = std::max(stream_offset, stream.recv_base_offset); if (write_start < end_offset) { size_t copy_len = static_cast<size_t>(end_offset - write_start); size_t src_off = static_cast<size_t>(offset + (write_start - stream_offset)); std::memcpy(&stream.recv_buffer[write_start - stream.recv_base_offset], &data[src_off], copy_len); } // Copy data into the correct position (handles in-order, // out-of-order, and gap-fill cases) std::memcpy(&stream.recv_buffer[stream_offset], &data[offset], stream_len); // Track received range — merge with adjacent/overlapping ranges auto new_range = std::make_pair(stream_offset, end_offset); auto it = stream.recv_ranges.insert(new_range).first; Loading Loading @@ -4403,8 +4420,13 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { // Update connection-level receive counter (only new unique bytes) _data_recv += new_unique_bytes; // Flow control: defer MAX_STREAM_DATA when >50% of window consumed uint64_t consumed = stream.recv_buffer.size(); // Flow control: defer MAX_STREAM_DATA when >50% of window consumed. // recv_base_offset + recv_buffer.size() is the highest absolute offset // the buffer currently extends to — equivalent to the old plain // recv_buffer.size() when recv_base_offset is 0 (always true outside // incremental dispatch's trimming), and still correct once trimming // has shifted the buffer forward. uint64_t consumed = stream.recv_base_offset + stream.recv_buffer.size(); if (consumed > stream.max_data_local_committed / 2) { uint64_t new_limit = consumed + stream.max_data_local; stream.max_data_local_committed = new_limit; Loading Loading @@ -4443,9 +4465,13 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { // stream; everything before that is fin=false, mirroring how the // client side already reads via recv_contiguous (see recvData()). if (stream.recv_contiguous > stream.recv_dispatched_offset) { // recv_dispatched_offset always equals recv_base_offset here // (the buffer is trimmed to it immediately below, every time), // so the chunk always starts at the beginning of recv_buffer. uint64_t rel_contiguous = stream.recv_contiguous - stream.recv_base_offset; std::vector<uint8_t> chunk( stream.recv_buffer.begin() + stream.recv_dispatched_offset, stream.recv_buffer.begin() + stream.recv_contiguous); stream.recv_buffer.begin(), stream.recv_buffer.begin() + rel_contiguous); stream.recv_dispatched_offset = stream.recv_contiguous; bool chunk_fin = stream.recv_complete; if (chunk_fin) { Loading @@ -4453,7 +4479,18 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { stream.recv_buffer.clear(); stream.recv_buffer.shrink_to_fit(); stream.recv_ranges.clear(); } } else { // F04 fix: drop the now-dispatched prefix so recv_buffer // only ever holds undispatched bytes, instead of growing to // the stream's full cumulative size and only being freed at // FIN — the previous behavior for long-lived incremental // streams (e.g. large uploads), which could hold the // entire transfer in memory even though the application had // already consumed most of it via the callback. stream.recv_buffer.erase(stream.recv_buffer.begin(), stream.recv_buffer.begin() + rel_contiguous); } stream.recv_base_offset = stream.recv_dispatched_offset; _pending_dispatches.push_back({stream_id, std::move(chunk), chunk_fin}); } } else if (_is_server && _stream_callback) { Loading src/socket.h +10 −1 Changes for src/socket.h: 10 added lines, 1 removed line. Original line number Diff line number Diff line Loading @@ -595,7 +595,16 @@ namespace netplus { bool recv_complete = false; // all data up to FIN received bool send_fin = false; bool reset = false; uint64_t recv_frame_count = 0; // diagnostic: STREAM frames received // Absolute stream offset corresponding to recv_buffer[0]. Stays // 0 outside incremental dispatch (recv_buffer then holds the // stream from offset 0, as before); incremental dispatch // advances it to recv_dispatched_offset each time it trims the // already-dispatched prefix out of recv_buffer (see // processStreamFrame), so the buffer only ever holds // undispatched bytes instead of growing to the stream's full // cumulative size. uint64_t recv_base_offset = 0; uint64_t recv_frame_count = 0; // also used to detect a peer-initiated stream's first frame (processStreamFrame) // Track received byte ranges for gap detection std::set<std::pair<uint64_t,uint64_t>> recv_ranges; }; Loading test/quic_incremental_dispatch_test.cpp 0 → 100644 +206 −0 Changes for test/quic_incremental_dispatch_test.cpp: 206 added lines, 0 removed lines. Original line number Diff line number Diff line // quic_incremental_dispatch_test.cpp // // Regression test for setIncrementalStreamDispatch(true) + its recv_buffer // trimming (recv_base_offset): sends a large payload on one bidi stream to a // server that dispatches each newly-contiguous chunk as it arrives instead // of buffering the whole message, accumulates the chunks server-side, // verifies the reassembled data's SHA-256 matches the original, then echoes // it back and verifies the client's received bytes match too. Also asserts // more than one non-fin chunk was actually delivered, so the trimming path // (recv_base_offset advancing mid-stream) is genuinely exercised more than // once per stream, not just at FIN. #include <iostream> #include <string> #include <vector> #include <map> #include <mutex> #include <thread> #include <atomic> #include <chrono> #include <stdexcept> #include "connection.h" #include "eventapi.h" #include "socket.h" #include "exception.h" #include "random.h" #include "crypto/sha.h" #include "https_certs.h" #include "https_ca_cert.h" using namespace netplus; static int g_passed = 0, g_failed = 0; static void check(bool ok, const std::string& name) { if (ok) { std::cout << " PASS: " << name << std::endl; g_passed++; } else { std::cout << " FAIL: " << name << std::endl; g_failed++; } } static std::string toHex(const std::vector<uint8_t>& v) { static const char* hexd = "0123456789abcdef"; std::string s; s.reserve(v.size() * 2); for (uint8_t b : v) { s.push_back(hexd[b >> 4]); s.push_back(hexd[b & 0x0F]); } return s; } // ============================================================================ // QUIC server: incremental-dispatch echo. Accumulates chunks per stream_id // as they're pushed (rather than getting the whole message once at FIN), // and echoes the full reassembled message back once FIN arrives. // ============================================================================ static std::mutex g_accum_mutex; static std::map<uint64_t, std::vector<uint8_t>> g_accum; static std::atomic<int> g_nonfin_chunk_count{0}; static std::atomic<int> g_fin_chunk_count{0}; class IncrementalEchoServer : public event { public: IncrementalEchoServer(std::vector<netplus::socket*> socks, int timeout = 500) : event(socks, timeout) {} void RequestEvent(con&, const int, ULONG_PTR) override {} void ResponseEvent(con&, const int, ULONG_PTR) override {} void ConnectEvent(con&, const int, ULONG_PTR) override {} void DisconnectEvent(con&, const int, ULONG_PTR) override {} void CreateConnection(std::shared_ptr<con>& res) override { res = std::make_shared<con>(this); } }; static std::atomic<bool> g_quic_ready(false); static void waitReady(std::atomic<bool>& ready) { while (!ready.load()) std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } static void runQuicServer(std::map<std::string, ssl::CertificateBundle>& certs, int port) { try { quic serverSock(certs, "127.0.0.1", port, 64, -1); serverSock.setIncrementalStreamDispatch(true); serverSock.setStreamCallback([](netplus::socket* sock, uint64_t stream_id, const std::vector<uint8_t>& data, bool fin) { netplus::quic* q = dynamic_cast<netplus::quic*>(sock); if (!q) return; if (fin) g_fin_chunk_count++; else if (!data.empty()) g_nonfin_chunk_count++; std::vector<uint8_t> whole; { std::lock_guard<std::mutex> lk(g_accum_mutex); auto& buf = g_accum[stream_id]; buf.insert(buf.end(), data.begin(), data.end()); if (fin) whole = buf; } if (fin) { q->sendStreamData(stream_id, whole, true); } }); IncrementalEchoServer srv({&serverSock}); g_quic_ready.store(true); srv.runEventloop(); } catch (NetException& e) { std::cerr << "[QUIC server] NetException: " << e.what() << std::endl; g_quic_ready.store(true); } catch (std::exception& e) { std::cerr << "[QUIC server] Exception: " << e.what() << std::endl; g_quic_ready.store(true); } } static std::vector<uint8_t> quicRoundTrip(const std::vector<uint8_t>& payload, const std::string& host, int port) { quic client; client.connect(host, port); uint64_t sid = client.openStream(true); client.sendStreamData(sid, payload, true); std::vector<uint8_t> out(payload.size()); size_t total = 0; auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); while (total < out.size() && std::chrono::steady_clock::now() < deadline) { client.pumpNetwork(MSG_DONTWAIT); if (client.hasStreamData(sid)) { size_t got = client.recvStreamData(sid, out.data() + total, out.size() - total); if (got > 0) { total += got; continue; } } std::this_thread::sleep_for(std::chrono::microseconds(200)); } if (total != out.size()) throw std::runtime_error("quicRoundTrip: incomplete echo (" + std::to_string(total) + "/" + std::to_string(out.size()) + " bytes)"); return out; } int main() { std::cout << "=== QUIC Incremental Stream Dispatch Test ===" << std::endl; const size_t kPayloadSize = 4096 * 1024; // 4 MB: forces many dispatch/trim cycles const int kQuicPort = 19547; int rc = 0; try { std::vector<uint8_t> original(kPayloadSize); fillRandomBytes(original.data(), original.size()); std::vector<uint8_t> originalHash = sha256_hash(original); std::cout << "Generated " << kPayloadSize << " random bytes, sha256=" << toHex(originalHash) << std::endl; x509cert cert; if (!cert.loadFromBuffer(test_cert_der)) { std::cerr << "Failed to load certificate" << std::endl; return 1; } std::map<std::string, ssl::CertificateBundle> certs; ssl::CertificateBundle bundle; bundle.cert = cert; bundle.privateKeyDer = std::vector<uint8_t>(test_key_der.begin(), test_key_der.end()); bundle.rsa_key = rsa(bundle.privateKeyDer); bundle.chain.push_back(std::vector<uint8_t>(MKCERT_ROOT_CA_DER, MKCERT_ROOT_CA_DER + MKCERT_ROOT_CA_DER_LEN)); certs["localhost"] = bundle; certs["127.0.0.1"] = bundle; std::thread quicServerThread(runQuicServer, std::ref(certs), kQuicPort); waitReady(g_quic_ready); std::vector<uint8_t> echoed = quicRoundTrip(original, "127.0.0.1", kQuicPort); event::Running = false; quicServerThread.join(); check(echoed == original, "incremental-dispatch echo preserves bytes exactly"); check(sha256_hash(echoed) == originalHash, "incremental-dispatch echo preserves sha256"); check(g_nonfin_chunk_count.load() > 1, "server received more than one non-fin chunk (trim path exercised repeatedly, not just at FIN): got " + std::to_string(g_nonfin_chunk_count.load())); check(g_fin_chunk_count.load() == 1, "server received exactly one fin=true chunk"); std::cout << "non-fin chunks: " << g_nonfin_chunk_count.load() << ", fin chunks: " << g_fin_chunk_count.load() << std::endl; } catch (NetException& e) { std::cerr << "NetException: " << e.what() << std::endl; rc = 1; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; rc = 1; } std::cout << "\n==============================" << std::endl; std::cout << "Results: " << g_passed << " passed, " << g_failed << " failed" << std::endl; std::cout << "==============================" << std::endl; return (rc != 0 || g_failed > 0) ? 1 : 0; } Loading
src/quic.cpp +56 −19 Changes for src/quic.cpp: 56 added lines, 19 removed lines. Original line number Diff line number Diff line Loading @@ -4259,10 +4259,19 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { auto& stream = _streams[stream_id]; stream.stream_id = stream_id; // True exactly once per stream: the very first STREAM frame seen for // it. Tracked via recv_frame_count rather than "recv_buffer empty + // recv_offset==0" — with incremental dispatch's buffer trimming (see // its comment further below), recv_buffer legitimately goes back to // empty mid-stream between dispatched chunks, which would otherwise // make this fire again and double-count MAX_STREAMS accounting below. bool is_first_frame_for_stream = (stream.recv_frame_count == 0); stream.recv_frame_count++; // Track peer-initiated stream count for MAX_STREAMS enforcement // Peer-initiated streams: client-initiated if we're server, server-initiated if we're client bool peer_initiated = (_is_server) ? ((stream_id & 0x01) == 0) : ((stream_id & 0x01) == 1); if (peer_initiated && stream.recv_buffer.empty() && stream.recv_offset == 0) { if (peer_initiated && is_first_frame_for_stream) { // First data on a new peer-initiated stream bool is_bidi = (stream_id % 4 == 0) || (stream_id % 4 == 1); if (is_bidi) { Loading Loading @@ -4343,21 +4352,29 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { if (stream_len > 0) { uint64_t end_offset = stream_offset + stream_len; // Diagnostic: track frame arrival for server-side large streams if (_is_server && stream_len > 0) { stream.recv_frame_count++; } // Grow buffer if needed if (end_offset > stream.recv_buffer.size()) { stream.recv_buffer.resize(end_offset, 0); // recv_buffer only ever holds the not-yet-dispatched tail of the // stream (see incremental dispatch's trimming further below); // recv_base_offset is the absolute stream offset corresponding to // recv_buffer[0]. For the (default) non-incremental path, // recv_base_offset stays 0 and this is exactly the old absolute // indexing. Bytes at or before recv_base_offset were already // dispatched (or belong to a duplicate/retransmitted frame) and // must not be written — only the portion of this frame at or after // recv_base_offset, if any, still needs storing. uint64_t buf_end = (end_offset > stream.recv_base_offset) ? (end_offset - stream.recv_base_offset) : 0; if (buf_end > stream.recv_buffer.size()) { stream.recv_buffer.resize(buf_end, 0); } uint64_t write_start = std::max(stream_offset, stream.recv_base_offset); if (write_start < end_offset) { size_t copy_len = static_cast<size_t>(end_offset - write_start); size_t src_off = static_cast<size_t>(offset + (write_start - stream_offset)); std::memcpy(&stream.recv_buffer[write_start - stream.recv_base_offset], &data[src_off], copy_len); } // Copy data into the correct position (handles in-order, // out-of-order, and gap-fill cases) std::memcpy(&stream.recv_buffer[stream_offset], &data[offset], stream_len); // Track received range — merge with adjacent/overlapping ranges auto new_range = std::make_pair(stream_offset, end_offset); auto it = stream.recv_ranges.insert(new_range).first; Loading Loading @@ -4403,8 +4420,13 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { // Update connection-level receive counter (only new unique bytes) _data_recv += new_unique_bytes; // Flow control: defer MAX_STREAM_DATA when >50% of window consumed uint64_t consumed = stream.recv_buffer.size(); // Flow control: defer MAX_STREAM_DATA when >50% of window consumed. // recv_base_offset + recv_buffer.size() is the highest absolute offset // the buffer currently extends to — equivalent to the old plain // recv_buffer.size() when recv_base_offset is 0 (always true outside // incremental dispatch's trimming), and still correct once trimming // has shifted the buffer forward. uint64_t consumed = stream.recv_base_offset + stream.recv_buffer.size(); if (consumed > stream.max_data_local_committed / 2) { uint64_t new_limit = consumed + stream.max_data_local; stream.max_data_local_committed = new_limit; Loading Loading @@ -4443,9 +4465,13 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { // stream; everything before that is fin=false, mirroring how the // client side already reads via recv_contiguous (see recvData()). if (stream.recv_contiguous > stream.recv_dispatched_offset) { // recv_dispatched_offset always equals recv_base_offset here // (the buffer is trimmed to it immediately below, every time), // so the chunk always starts at the beginning of recv_buffer. uint64_t rel_contiguous = stream.recv_contiguous - stream.recv_base_offset; std::vector<uint8_t> chunk( stream.recv_buffer.begin() + stream.recv_dispatched_offset, stream.recv_buffer.begin() + stream.recv_contiguous); stream.recv_buffer.begin(), stream.recv_buffer.begin() + rel_contiguous); stream.recv_dispatched_offset = stream.recv_contiguous; bool chunk_fin = stream.recv_complete; if (chunk_fin) { Loading @@ -4453,7 +4479,18 @@ void quic::processStreamFrame(const uint8_t* data, size_t len, size_t& offset) { stream.recv_buffer.clear(); stream.recv_buffer.shrink_to_fit(); stream.recv_ranges.clear(); } } else { // F04 fix: drop the now-dispatched prefix so recv_buffer // only ever holds undispatched bytes, instead of growing to // the stream's full cumulative size and only being freed at // FIN — the previous behavior for long-lived incremental // streams (e.g. large uploads), which could hold the // entire transfer in memory even though the application had // already consumed most of it via the callback. stream.recv_buffer.erase(stream.recv_buffer.begin(), stream.recv_buffer.begin() + rel_contiguous); } stream.recv_base_offset = stream.recv_dispatched_offset; _pending_dispatches.push_back({stream_id, std::move(chunk), chunk_fin}); } } else if (_is_server && _stream_callback) { Loading
src/socket.h +10 −1 Changes for src/socket.h: 10 added lines, 1 removed line. Original line number Diff line number Diff line Loading @@ -595,7 +595,16 @@ namespace netplus { bool recv_complete = false; // all data up to FIN received bool send_fin = false; bool reset = false; uint64_t recv_frame_count = 0; // diagnostic: STREAM frames received // Absolute stream offset corresponding to recv_buffer[0]. Stays // 0 outside incremental dispatch (recv_buffer then holds the // stream from offset 0, as before); incremental dispatch // advances it to recv_dispatched_offset each time it trims the // already-dispatched prefix out of recv_buffer (see // processStreamFrame), so the buffer only ever holds // undispatched bytes instead of growing to the stream's full // cumulative size. uint64_t recv_base_offset = 0; uint64_t recv_frame_count = 0; // also used to detect a peer-initiated stream's first frame (processStreamFrame) // Track received byte ranges for gap detection std::set<std::pair<uint64_t,uint64_t>> recv_ranges; }; Loading
test/quic_incremental_dispatch_test.cpp 0 → 100644 +206 −0 Changes for test/quic_incremental_dispatch_test.cpp: 206 added lines, 0 removed lines. Original line number Diff line number Diff line // quic_incremental_dispatch_test.cpp // // Regression test for setIncrementalStreamDispatch(true) + its recv_buffer // trimming (recv_base_offset): sends a large payload on one bidi stream to a // server that dispatches each newly-contiguous chunk as it arrives instead // of buffering the whole message, accumulates the chunks server-side, // verifies the reassembled data's SHA-256 matches the original, then echoes // it back and verifies the client's received bytes match too. Also asserts // more than one non-fin chunk was actually delivered, so the trimming path // (recv_base_offset advancing mid-stream) is genuinely exercised more than // once per stream, not just at FIN. #include <iostream> #include <string> #include <vector> #include <map> #include <mutex> #include <thread> #include <atomic> #include <chrono> #include <stdexcept> #include "connection.h" #include "eventapi.h" #include "socket.h" #include "exception.h" #include "random.h" #include "crypto/sha.h" #include "https_certs.h" #include "https_ca_cert.h" using namespace netplus; static int g_passed = 0, g_failed = 0; static void check(bool ok, const std::string& name) { if (ok) { std::cout << " PASS: " << name << std::endl; g_passed++; } else { std::cout << " FAIL: " << name << std::endl; g_failed++; } } static std::string toHex(const std::vector<uint8_t>& v) { static const char* hexd = "0123456789abcdef"; std::string s; s.reserve(v.size() * 2); for (uint8_t b : v) { s.push_back(hexd[b >> 4]); s.push_back(hexd[b & 0x0F]); } return s; } // ============================================================================ // QUIC server: incremental-dispatch echo. Accumulates chunks per stream_id // as they're pushed (rather than getting the whole message once at FIN), // and echoes the full reassembled message back once FIN arrives. // ============================================================================ static std::mutex g_accum_mutex; static std::map<uint64_t, std::vector<uint8_t>> g_accum; static std::atomic<int> g_nonfin_chunk_count{0}; static std::atomic<int> g_fin_chunk_count{0}; class IncrementalEchoServer : public event { public: IncrementalEchoServer(std::vector<netplus::socket*> socks, int timeout = 500) : event(socks, timeout) {} void RequestEvent(con&, const int, ULONG_PTR) override {} void ResponseEvent(con&, const int, ULONG_PTR) override {} void ConnectEvent(con&, const int, ULONG_PTR) override {} void DisconnectEvent(con&, const int, ULONG_PTR) override {} void CreateConnection(std::shared_ptr<con>& res) override { res = std::make_shared<con>(this); } }; static std::atomic<bool> g_quic_ready(false); static void waitReady(std::atomic<bool>& ready) { while (!ready.load()) std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } static void runQuicServer(std::map<std::string, ssl::CertificateBundle>& certs, int port) { try { quic serverSock(certs, "127.0.0.1", port, 64, -1); serverSock.setIncrementalStreamDispatch(true); serverSock.setStreamCallback([](netplus::socket* sock, uint64_t stream_id, const std::vector<uint8_t>& data, bool fin) { netplus::quic* q = dynamic_cast<netplus::quic*>(sock); if (!q) return; if (fin) g_fin_chunk_count++; else if (!data.empty()) g_nonfin_chunk_count++; std::vector<uint8_t> whole; { std::lock_guard<std::mutex> lk(g_accum_mutex); auto& buf = g_accum[stream_id]; buf.insert(buf.end(), data.begin(), data.end()); if (fin) whole = buf; } if (fin) { q->sendStreamData(stream_id, whole, true); } }); IncrementalEchoServer srv({&serverSock}); g_quic_ready.store(true); srv.runEventloop(); } catch (NetException& e) { std::cerr << "[QUIC server] NetException: " << e.what() << std::endl; g_quic_ready.store(true); } catch (std::exception& e) { std::cerr << "[QUIC server] Exception: " << e.what() << std::endl; g_quic_ready.store(true); } } static std::vector<uint8_t> quicRoundTrip(const std::vector<uint8_t>& payload, const std::string& host, int port) { quic client; client.connect(host, port); uint64_t sid = client.openStream(true); client.sendStreamData(sid, payload, true); std::vector<uint8_t> out(payload.size()); size_t total = 0; auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); while (total < out.size() && std::chrono::steady_clock::now() < deadline) { client.pumpNetwork(MSG_DONTWAIT); if (client.hasStreamData(sid)) { size_t got = client.recvStreamData(sid, out.data() + total, out.size() - total); if (got > 0) { total += got; continue; } } std::this_thread::sleep_for(std::chrono::microseconds(200)); } if (total != out.size()) throw std::runtime_error("quicRoundTrip: incomplete echo (" + std::to_string(total) + "/" + std::to_string(out.size()) + " bytes)"); return out; } int main() { std::cout << "=== QUIC Incremental Stream Dispatch Test ===" << std::endl; const size_t kPayloadSize = 4096 * 1024; // 4 MB: forces many dispatch/trim cycles const int kQuicPort = 19547; int rc = 0; try { std::vector<uint8_t> original(kPayloadSize); fillRandomBytes(original.data(), original.size()); std::vector<uint8_t> originalHash = sha256_hash(original); std::cout << "Generated " << kPayloadSize << " random bytes, sha256=" << toHex(originalHash) << std::endl; x509cert cert; if (!cert.loadFromBuffer(test_cert_der)) { std::cerr << "Failed to load certificate" << std::endl; return 1; } std::map<std::string, ssl::CertificateBundle> certs; ssl::CertificateBundle bundle; bundle.cert = cert; bundle.privateKeyDer = std::vector<uint8_t>(test_key_der.begin(), test_key_der.end()); bundle.rsa_key = rsa(bundle.privateKeyDer); bundle.chain.push_back(std::vector<uint8_t>(MKCERT_ROOT_CA_DER, MKCERT_ROOT_CA_DER + MKCERT_ROOT_CA_DER_LEN)); certs["localhost"] = bundle; certs["127.0.0.1"] = bundle; std::thread quicServerThread(runQuicServer, std::ref(certs), kQuicPort); waitReady(g_quic_ready); std::vector<uint8_t> echoed = quicRoundTrip(original, "127.0.0.1", kQuicPort); event::Running = false; quicServerThread.join(); check(echoed == original, "incremental-dispatch echo preserves bytes exactly"); check(sha256_hash(echoed) == originalHash, "incremental-dispatch echo preserves sha256"); check(g_nonfin_chunk_count.load() > 1, "server received more than one non-fin chunk (trim path exercised repeatedly, not just at FIN): got " + std::to_string(g_nonfin_chunk_count.load())); check(g_fin_chunk_count.load() == 1, "server received exactly one fin=true chunk"); std::cout << "non-fin chunks: " << g_nonfin_chunk_count.load() << ", fin chunks: " << g_fin_chunk_count.load() << std::endl; } catch (NetException& e) { std::cerr << "NetException: " << e.what() << std::endl; rc = 1; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; rc = 1; } std::cout << "\n==============================" << std::endl; std::cout << "Results: " << g_passed << " passed, " << g_failed << " failed" << std::endl; std::cout << "==============================" << std::endl; return (rc != 0 || g_failed > 0) ? 1 : 0; }