Commit 744e5e57 authored by jan.koester's avatar jan.koester
Browse files

test

parent 4664d8a9
Loading
Loading
Loading
Loading
+79 −28
Changes for src/quic.cpp: 79 added lines, 28 removed lines.
Original line number Diff line number Diff line
@@ -349,7 +349,19 @@ ssize_t quic::sendPacket(const uint8_t* data, size_t len) {
// ============================================================================

void quic::batchPacket(const uint8_t* data, size_t len) {
    _send_batch.push_back({std::vector<uint8_t>(data, data + len)});
    // Flat arena instead of one heap vector per queued packet (see
    // BatchEntry's comment in socket.h). Sized to the currently confirmed
    // usable payload (getMaxUdpPayload()) times BATCH_MAX, grown only if a
    // packet or a PMTU-discovery increase needs more room — grow is O(1)
    // amortized just like std::vector's own, and rare in practice.
    size_t needed = _send_arena_used + len;
    if (_send_arena.size() < needed) {
        size_t grow_to = std::max(needed, BATCH_MAX * std::max<size_t>(_max_udp_payload, len));
        _send_arena.resize(grow_to);
    }
    std::memcpy(_send_arena.data() + _send_arena_used, data, len);
    _send_batch.push_back({_send_arena_used, len});
    _send_arena_used += len;
    if (_send_batch.size() >= BATCH_MAX) {
        flushBatch();
    }
@@ -357,13 +369,13 @@ void quic::batchPacket(const uint8_t* data, size_t len) {

ssize_t quic::flushBatch() {
    if (_send_batch.empty()) return 0;
    if (_Socket < 0) { _send_batch.clear(); return -1; }
    if (_Socket < 0) { _send_batch.clear(); _send_arena_used = 0; return -1; }

    // Build pointer/length pairs for udp::sendBatch
    std::vector<std::pair<const uint8_t*, size_t>> datagrams;
    datagrams.reserve(_send_batch.size());
    for (auto& entry : _send_batch)
        datagrams.emplace_back(entry.data.data(), entry.data.size());
        datagrams.emplace_back(_send_arena.data() + entry.offset, entry.len);

    // Child connections send to a specific peer address
    sockaddr_storage* dest = nullptr;
@@ -379,8 +391,22 @@ ssize_t quic::flushBatch() {
        const size_t sent_count = static_cast<size_t>(sent);
        if (sent_count >= _send_batch.size()) {
            _send_batch.clear();
            _send_arena_used = 0;
        } else {
            // Compact the still-unsent tail down to the front of the arena
            // so _send_arena_used stays bounded across repeated partial
            // sends instead of growing forever.
            size_t new_used = 0;
            for (size_t i = sent_count; i < _send_batch.size(); ++i) {
                auto& e = _send_batch[i];
                if (e.offset != new_used) {
                    std::memmove(_send_arena.data() + new_used, _send_arena.data() + e.offset, e.len);
                }
                e.offset = new_used;
                new_used += e.len;
            }
            _send_batch.erase(_send_batch.begin(), _send_batch.begin() + sent_count);
            _send_arena_used = new_used;
        }
        return sent;
    }
@@ -1197,10 +1223,11 @@ void quic::applyHeaderProtection(std::vector<uint8_t>& packet, EncryptionLevel l
// Packet Protection (AES-GCM - supports both AES-128 and AES-256)
// ============================================================================

std::vector<uint8_t> quic::protectPacket(const std::vector<uint8_t>& header,
void quic::protectPacketInto(const std::vector<uint8_t>& header,
                              const std::vector<uint8_t>& payload,
                              uint64_t packet_number,
                                          EncryptionLevel level, LevelKeyMaterial& mat) {
                              EncryptionLevel level, LevelKeyMaterial& mat,
                              std::vector<uint8_t>& out) {
    // Build nonce: IV XOR packet_number (left-padded to 12 bytes)
    uint8_t nonce[12];
    std::memcpy(nonce, mat.iv, 12);
@@ -1211,15 +1238,17 @@ std::vector<uint8_t> quic::protectPacket(const std::vector<uint8_t>& header,
    // Initial packets always use AES-128, others use the negotiated cipher
    const bool use_aes256 = (level != EncryptionLevel::Initial) && (_selected_cipher == 0x1302);

    // Allocate result: header + ciphertext + 16-byte tag — single allocation
    // header + ciphertext + 16-byte tag. `out`'s capacity is reused across
    // calls when the caller passes a persistent scratch buffer (see
    // sendShortHeaderControlPacket()) instead of a fresh local vector.
    const size_t total = header.size() + payload.size() + 16;
    std::vector<uint8_t> result(total);
    out.resize(total);

    // Copy header
    std::memcpy(result.data(), header.data(), header.size());
    std::memcpy(out.data(), header.data(), header.size());

    // Encrypt payload directly into result buffer (after header)
    uint8_t* ct_dst = result.data() + header.size();
    // Encrypt payload directly into the output buffer (after header)
    uint8_t* ct_dst = out.data() + header.size();
    uint8_t* tag_dst = ct_dst + payload.size();

    // Cached AES instance is already role/level-resolved via `mat` — no
@@ -1241,7 +1270,14 @@ std::vector<uint8_t> quic::protectPacket(const std::vector<uint8_t>& header,
                                payload.data(), payload.size(),
                                ct_dst, tag_dst);
    }
}

std::vector<uint8_t> quic::protectPacket(const std::vector<uint8_t>& header,
                                          const std::vector<uint8_t>& payload,
                                          uint64_t packet_number,
                                          EncryptionLevel level, LevelKeyMaterial& mat) {
    std::vector<uint8_t> result;
    protectPacketInto(header, payload, packet_number, level, mat, result);
    return result;
}

@@ -2891,6 +2927,32 @@ std::vector<uint8_t> quic::buildShortHeaderPacket(const std::vector<uint8_t>& pa
    return protectPacket(header, payload, pn, EncryptionLevel::Application, _app_keys.send);
}

// Zero-copy equivalent of buildShortHeaderPacket() + applyHeaderProtection()
// + sendPacket() for control-only frames (ACK, MAX_DATA, MAX_STREAM_DATA,
// DATA_BLOCKED, STREAM_DATA_BLOCKED) — see _ctrl_header_scratch/
// _ctrl_pkt_scratch's declaration in socket.h. Returns sendPacket()'s
// result so callers keep their existing retry-on_failure behavior.
ssize_t quic::sendShortHeaderControlPacket(const std::vector<uint8_t>& frame) {
    auto& header = _ctrl_header_scratch;
    header.clear();

    uint8_t first_byte = 0x40;
    size_t pn_len = 4;
    first_byte |= (pn_len - 1);
    header.push_back(first_byte);
    header.insert(header.end(), _remote_cid.begin(), _remote_cid.end());

    uint64_t pn = _app_pn_send++;
    header.push_back(static_cast<uint8_t>(pn >> 24));
    header.push_back(static_cast<uint8_t>(pn >> 16));
    header.push_back(static_cast<uint8_t>(pn >> 8));
    header.push_back(static_cast<uint8_t>(pn));

    protectPacketInto(header, frame, pn, EncryptionLevel::Application, _app_keys.send, _ctrl_pkt_scratch);
    applyHeaderProtection(_ctrl_pkt_scratch, EncryptionLevel::Application, _app_keys.send);
    return sendPacket(_ctrl_pkt_scratch.data(), _ctrl_pkt_scratch.size());
}

// ============================================================================
// Socket Interface: connect (Client-side connection initiation)
// ============================================================================
@@ -4857,13 +4919,11 @@ void quic::sendMaxStreamData(uint64_t stream_id, uint64_t max_data) {
    bytes = encodeVarInt(max_data, buf);
    frame.insert(frame.end(), buf, buf + bytes);

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
    applyHeaderProtection(packet, EncryptionLevel::Application, _app_keys.send);
    ssize_t sent = sendPacket(packet.data(), packet.size());
    ssize_t sent = sendShortHeaderControlPacket(frame);
    if (sent < 0) {
        // Flow control frames are critical — immediate non-blocking retry.
        // Do not sleep here: caller typically holds quic_mtx().
        sendPacket(packet.data(), packet.size());
        sendPacket(_ctrl_pkt_scratch.data(), _ctrl_pkt_scratch.size());
    }
}

@@ -4878,13 +4938,11 @@ void quic::sendMaxData(uint64_t max_data) {
    size_t bytes = encodeVarInt(max_data, buf);
    frame.insert(frame.end(), buf, buf + bytes);

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
    applyHeaderProtection(packet, EncryptionLevel::Application, _app_keys.send);
    ssize_t sent = sendPacket(packet.data(), packet.size());
    ssize_t sent = sendShortHeaderControlPacket(frame);
    if (sent < 0) {
        // Flow control frames are critical — immediate non-blocking retry.
        // Do not sleep here: caller typically holds quic_mtx().
        sendPacket(packet.data(), packet.size());
        sendPacket(_ctrl_pkt_scratch.data(), _ctrl_pkt_scratch.size());
    }
}

@@ -4899,9 +4957,7 @@ void quic::sendDataBlocked(uint64_t limit) {
    size_t bytes = encodeVarInt(limit, buf);
    frame.insert(frame.end(), buf, buf + bytes);

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
    applyHeaderProtection(packet, EncryptionLevel::Application, _app_keys.send);
    sendPacket(packet.data(), packet.size());
    sendShortHeaderControlPacket(frame);
}

// ============================================================================
@@ -4917,9 +4973,7 @@ void quic::sendStreamDataBlocked(uint64_t stream_id, uint64_t limit) {
    bytes = encodeVarInt(limit, buf);
    frame.insert(frame.end(), buf, buf + bytes);

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
    applyHeaderProtection(packet, EncryptionLevel::Application, _app_keys.send);
    sendPacket(packet.data(), packet.size());
    sendShortHeaderControlPacket(frame);
}

// ============================================================================
@@ -4928,10 +4982,7 @@ void quic::sendStreamDataBlocked(uint64_t stream_id, uint64_t limit) {

void quic::sendAppAck() {
    std::vector<uint8_t> frame = buildAckFrame(_app_pn_recv, 0, _app_pn_recv_ranges);

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
    applyHeaderProtection(packet, EncryptionLevel::Application, _app_keys.send);
    sendPacket(packet.data(), packet.size());
    sendShortHeaderControlPacket(frame);
}

// ============================================================================
+29 −2
Changes for src/socket.h: 29 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -886,6 +886,15 @@ namespace netplus {
		                                   const std::vector<uint8_t>& payload,
		                                   uint64_t packet_number,
		                                   EncryptionLevel level, LevelKeyMaterial& mat);
		// Same encryption as protectPacket(), but writes into `out` (capacity
		// reused across calls) instead of returning a freshly allocated
		// vector — the primitive sendShortHeaderControlPacket() uses to stay
		// allocation-free.
		void protectPacketInto(const std::vector<uint8_t>& header,
		                        const std::vector<uint8_t>& payload,
		                        uint64_t packet_number,
		                        EncryptionLevel level, LevelKeyMaterial& mat,
		                        std::vector<uint8_t>& out);
		bool unprotectPacket(const uint8_t* data, size_t len,
		                     std::vector<uint8_t>& header,
		                     std::vector<uint8_t>& payload,
@@ -1156,6 +1165,18 @@ namespace netplus {
		/// Send an ACK frame for 1-RTT packets
		void sendAppAck();

		// Builds a short-header 1-RTT packet around `frame`, applies AEAD
		// protection + header protection, and sends it — all using
		// persistent scratch buffers (_ctrl_header_scratch/_ctrl_pkt_scratch)
		// instead of buildShortHeaderPacket()'s return-by-value plus a
		// second protectPacket() allocation. Shared by every control-only
		// sender (ACK, MAX_DATA, MAX_STREAM_DATA, DATA_BLOCKED,
		// STREAM_DATA_BLOCKED) — mirrors the allocation-free pattern
		// sendStreamData(uint8_t*, ...) already uses for bulk data.
		ssize_t sendShortHeaderControlPacket(const std::vector<uint8_t>& frame);
		std::vector<uint8_t> _ctrl_header_scratch;
		std::vector<uint8_t> _ctrl_pkt_scratch;

		// Transport parameters
		uint64_t _max_idle_timeout = 30000;    // 30s
		uint64_t _max_udp_payload = 1472;      // Default: Ethernet-safe (1500 - IP/UDP headers).
@@ -1491,10 +1512,16 @@ namespace netplus {
		std::vector<uint8_t> _recv_header_scratch;
		std::vector<uint8_t> _recv_payload_scratch;

		// Batch send buffer for flushBatch()
		// Batch send buffer for flushBatch(). Packet bytes live in the flat
		// `_send_arena` (grown rarely, compacted on partial send) rather
		// than one heap-allocated vector per queued packet — BatchEntry is
		// just an {offset, len} view into it.
		struct BatchEntry {
			std::vector<uint8_t> data;
			size_t offset;
			size_t len;
		};
		std::vector<uint8_t> _send_arena;
		size_t _send_arena_used = 0;
		std::vector<BatchEntry> _send_batch;

		// Each connection's own lock — see _quic_mutex's comment for why