Commit d750e2ee authored by jan.koester's avatar jan.koester
Browse files

tes

parent e21350d1
Loading
Loading
Loading
Loading
+188 −11
Changes for src/quic.cpp: 188 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -39,6 +39,7 @@
#include <thread>
#include <chrono>
#include <cstdio>
#include <cmath>

#define QUIC_DBG(fmt, ...) do {} while(0)

@@ -3279,22 +3280,179 @@ void quic::processAckFrame(const uint8_t* data, size_t len, size_t& offset) {
    uint64_t first_ack_range = decodeVarInt(&data[offset], bytes);
    offset += bytes;

    // Process ACK ranges (mark packets as acknowledged)
    // For now, just skip them
    // Collect all ACKed ranges: [lo, hi] pairs
    struct AckRange { uint64_t lo; uint64_t hi; };
    std::vector<AckRange> acked_ranges;

    // First range
    uint64_t hi = largest_ack;
    uint64_t lo = (largest_ack >= first_ack_range) ? largest_ack - first_ack_range : 0;
    acked_ranges.push_back({lo, hi});

    uint64_t prev_smallest = lo;

    // Additional ranges
    for (uint64_t i = 0; i < ack_range_count; ++i) {
        // Gap
        decodeVarInt(&data[offset], bytes);
        uint64_t gap = decodeVarInt(&data[offset], bytes);
        offset += bytes;
        
        // ACK Range Length
        decodeVarInt(&data[offset], bytes);
        uint64_t ack_range = decodeVarInt(&data[offset], bytes);
        offset += bytes;

        // RFC 9000: prev_smallest - gap - 2 is the top of the next range
        if (prev_smallest < gap + 2) break; // malformed
        hi = prev_smallest - gap - 2;
        lo = (hi >= ack_range) ? hi - ack_range : 0;
        acked_ranges.push_back({lo, hi});
        prev_smallest = lo;
    }

    auto now = std::chrono::steady_clock::now();

    // Remove acknowledged packets from _sent_packets and update RTT
    for (auto& ar : acked_ranges) {
        for (auto it = _sent_packets.lower_bound(ar.lo);
             it != _sent_packets.end() && it->first <= ar.hi; ) {
            // Update RTT from the largest newly-acked packet
            if (it->first == largest_ack && it->second.ack_eliciting) {
                double rtt_sample = std::chrono::duration<double>(now - it->second.sent_time).count();
                double adj_delay = static_cast<double>(ack_delay) / 1000000.0;
                if (rtt_sample > adj_delay) rtt_sample -= adj_delay;
                if (!_rtt_initialized) {
                    _srtt = rtt_sample;
                    _rttvar = rtt_sample / 2.0;
                    _rtt_initialized = true;
                } else {
                    _rttvar = 0.75 * _rttvar + 0.25 * std::abs(_srtt - rtt_sample);
                    _srtt = 0.875 * _srtt + 0.125 * rtt_sample;
                }
                _rto = _srtt + std::max(4.0 * _rttvar, 0.001);
                if (_rto < 0.1) _rto = 0.1;
                if (_rto > 10.0) _rto = 10.0;
            }
            it = _sent_packets.erase(it);
        }
    }

    if (_largest_acked_pn == UINT64_MAX || largest_ack > _largest_acked_pn) {
        _largest_acked_pn = largest_ack;
    }

    // Trigger loss detection after processing ACK
    checkLossAndRetransmit();
}

// ============================================================================
// Retransmission: Record a sent packet for tracking
// ============================================================================

void quic::recordSentPacket(uint64_t pn, uint64_t stream_id, uint64_t stream_offset,
                            const uint8_t* data, size_t len, bool fin) {
    SentPacket sp;
    sp.pn = pn;
    sp.sent_time = std::chrono::steady_clock::now();
    sp.stream_id = stream_id;
    sp.stream_offset = stream_offset;
    sp.data_length = len;
    sp.fin = fin;
    sp.ack_eliciting = true;
    sp.stream_data.assign(data, data + len);
    _sent_packets[pn] = std::move(sp);
}

// ============================================================================
// Retransmission: Loss detection and retransmit
// ============================================================================

void quic::checkLossAndRetransmit() {
    if (_sent_packets.empty() || _largest_acked_pn == UINT64_MAX) return;

    auto now = std::chrono::steady_clock::now();
    // Time-based loss threshold (RFC 9002 §6.1.2)
    double loss_delay = TIME_THRESHOLD * std::max(_srtt, _rttvar);
    if (loss_delay < 0.001) loss_delay = 0.001; // min 1ms
    auto loss_time = std::chrono::duration<double>(loss_delay);

    std::vector<SentPacket> lost;

    for (auto it = _sent_packets.begin(); it != _sent_packets.end(); ) {
        bool is_lost = false;

        // Packet-number-based detection: PN is PACKET_THRESHOLD below largest acked
        if (it->first + PACKET_THRESHOLD <= _largest_acked_pn) {
            is_lost = true;
        }

        // Time-based detection: packet was sent long enough ago
        if (!is_lost) {
            auto elapsed = std::chrono::duration<double>(now - it->second.sent_time);
            if (elapsed.count() >= loss_delay) {
                // Only declare lost if this pn < largest_acked (peer has received later packets)
                if (it->first < _largest_acked_pn) {
                    is_lost = true;
                }
            }
        }

    // TODO: Implement proper ACK processing for congestion control
    (void)largest_ack;
    (void)ack_delay;
    (void)first_ack_range;
        if (is_lost) {
            lost.push_back(std::move(it->second));
            it = _sent_packets.erase(it);
        } else {
            ++it;
        }
    }

    // Retransmit lost stream data with new packet numbers
    for (auto& sp : lost) {
        if (sp.data_length == 0 && !sp.fin) continue;

        auto& stream = _streams[sp.stream_id];

        // Build STREAM frame for the lost data
        uint8_t frame_type = 0x08 | 0x02; // LEN bit
        if (sp.stream_offset > 0) frame_type |= 0x04; // OFF bit
        if (sp.fin) frame_type |= 0x01;

        std::vector<uint8_t> frame;
        frame.reserve(1 + 8 + 8 + 8 + sp.data_length);
        frame.push_back(frame_type);

        uint8_t varint_buf[8];
        size_t bytes = encodeVarInt(sp.stream_id, varint_buf);
        frame.insert(frame.end(), varint_buf, varint_buf + bytes);

        if (sp.stream_offset > 0) {
            bytes = encodeVarInt(sp.stream_offset, varint_buf);
            frame.insert(frame.end(), varint_buf, varint_buf + bytes);
        }

        bytes = encodeVarInt(sp.data_length, varint_buf);
        frame.insert(frame.end(), varint_buf, varint_buf + bytes);

        frame.insert(frame.end(), sp.stream_data.begin(), sp.stream_data.end());

        // New packet number for retransmit
        uint64_t new_pn = _app_pn_send; // buildShortHeaderPacket will increment
        std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
        const uint8_t* hp_key = _is_server ? _app_hp_server : _app_hp_client;
        applyHeaderProtection(packet, hp_key);

        ssize_t sent = sendPacket(packet.data(), packet.size());
        if (sent < 0) {
            std::this_thread::sleep_for(std::chrono::microseconds(500));
            sent = sendPacket(packet.data(), packet.size());
        }

        if (sent > 0) {
            // Track retransmitted packet under new PN
            recordSentPacket(new_pn, sp.stream_id, sp.stream_offset,
                            sp.stream_data.data(), sp.stream_data.size(), sp.fin);
        }

        QUIC_DBG("RETRANSMIT: old_pn=%lu new_pn=%lu sid=%lu off=%lu len=%zu fin=%d",
                 (unsigned long)sp.pn, (unsigned long)new_pn,
                 (unsigned long)sp.stream_id, (unsigned long)sp.stream_offset,
                 sp.data_length, (int)sp.fin);
    }
}

// ============================================================================
@@ -3454,6 +3612,7 @@ void quic::sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data,
                         data.begin() + abs_offset,
                         data.begin() + abs_offset + chunk_len);

            uint64_t pn_before = _app_pn_send; // capture before buildShortHeaderPacket increments
            std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
            const uint8_t* hp_key = _is_server ? _app_hp_server : _app_hp_client;
            applyHeaderProtection(packet, hp_key);
@@ -3468,6 +3627,10 @@ void quic::sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data,
                if (sent < 0) goto done;
            }

            // Record for retransmission tracking
            recordSentPacket(pn_before, stream_id, stream_off,
                            data.data() + abs_offset, chunk_len, set_fin);

            stream.send_offset += chunk_len;
            _data_sent += chunk_len;
            chunk_offset += chunk_len;
@@ -4275,6 +4438,7 @@ size_t quic::sendData(buffer& data, int flags) {
            stream_id, chunk_data, stream.send_offset, false);

        // Build 1-RTT packet
        uint64_t pn_before = _app_pn_send;
        std::vector<uint8_t> packet = buildShortHeaderPacket(stream_frame);

        // Apply header protection
@@ -4292,6 +4456,10 @@ size_t quic::sendData(buffer& data, int flags) {
            if (ret < 0) break;
        }

        // Record for retransmission tracking
        recordSentPacket(pn_before, stream_id, stream.send_offset,
                        send_ptr + sent_total, chunk, false);

        stream.send_offset += chunk;
        _data_sent += chunk;
        sent_total += chunk;
@@ -4351,6 +4519,7 @@ size_t quic::sendStreamData(uint64_t stream_id, const uint8_t* data, size_t len,
        std::vector<uint8_t> stream_frame = buildStreamFrame(
            stream_id, chunk_data, stream.send_offset, set_fin);

        uint64_t pn_before = _app_pn_send;
        std::vector<uint8_t> packet = buildShortHeaderPacket(stream_frame);
        const uint8_t* hp_key = _is_server ? _app_hp_server : _app_hp_client;
        applyHeaderProtection(packet, hp_key);
@@ -4365,6 +4534,10 @@ size_t quic::sendStreamData(uint64_t stream_id, const uint8_t* data, size_t len,
            if (ret < 0) break;
        }

        // Record for retransmission tracking
        recordSentPacket(pn_before, stream_id, stream.send_offset,
                        data + sent_total, chunk, set_fin);

        stream.send_offset += chunk;
        _data_sent += chunk;
        sent_total += chunk;
@@ -4578,6 +4751,10 @@ void quic::pumpIncoming() {
            }
        }
    }

    // After processing incoming packets (which may contain ACKs),
    // check for lost packets and retransmit.
    checkLossAndRetransmit();
}

// ============================================================================
+30 −0
Changes for src/socket.h: 30 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -503,6 +503,18 @@ namespace netplus {
			Closed
		};

		// Sent packet metadata for retransmission / loss detection
		struct SentPacket {
			uint64_t pn;             // packet number
			std::chrono::steady_clock::time_point sent_time;
			uint64_t stream_id;
			uint64_t stream_offset;
			size_t   data_length;
			bool     fin;            // carried FIN flag
			bool     ack_eliciting;  // true for STREAM frames
			std::vector<uint8_t> stream_data; // copy of payload for retransmit
		};

		// Stream state
		struct Stream {
			uint64_t stream_id;
@@ -627,6 +639,11 @@ namespace netplus {
		void processStreamFrame(const uint8_t* data, size_t len, size_t& offset);
		void processAckFrame(const uint8_t* data, size_t len, size_t& offset);

		// Loss detection and retransmission
		void checkLossAndRetransmit();
		void recordSentPacket(uint64_t pn, uint64_t stream_id, uint64_t stream_offset,
		                      const uint8_t* data, size_t len, bool fin);

		// Packet building
		std::vector<uint8_t> buildInitialPacket(const std::vector<uint8_t>& payload);
		std::vector<uint8_t> buildHandshakePacket(const std::vector<uint8_t>& payload);
@@ -905,6 +922,19 @@ namespace netplus {
		static constexpr int HS_RETRANSMIT_MAX = 5;
		static constexpr int HS_RETRANSMIT_INTERVAL_MS = 200;  // Initial retransmit timer

		// Application packet retransmission (loss detection + recovery)
		std::map<uint64_t, SentPacket> _sent_packets;  // pn → metadata
		uint64_t _largest_acked_pn = UINT64_MAX;       // largest packet number ACKed
		// RTT estimation (RFC 9002 §5)
		double _srtt = 0.0;           // smoothed RTT (seconds)
		double _rttvar = 0.0;         // RTT variance (seconds)
		double _rto = 0.5;            // retransmission timeout (seconds), initial 500ms
		bool   _rtt_initialized = false;
		// Loss detection
		static constexpr uint64_t PACKET_THRESHOLD = 3;     // RFC 9002 kPacketThreshold
		static constexpr double   TIME_THRESHOLD   = 9.0/8; // RFC 9002 kTimeThreshold
		std::chrono::steady_clock::time_point _loss_detection_timer;

		// Flow control batching: avoid sending duplicate MAX_DATA/MAX_STREAM_DATA
		bool _pending_max_data = false;
		uint64_t _pending_max_data_value = 0;