Commit 35c873d4 authored by jan.koester's avatar jan.koester
Browse files

fixes fixes

parent 8e0e81c4
Loading
Loading
Loading
Loading
+14 −15
Changes for src/event/epoll.cpp: 14 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -455,33 +455,32 @@ namespace netplus {
                                size_t consumed = 0;
                                try {
                                    consumed = c->slots[0].csock->sendData(out, 0);
                                    if (c->slots[0].csock->hasPendingWrite())
                                        c->slots[0].csock->flush_out();
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        sendBlockedWouldBlock = true;
                                        break;
                                    }
                                    throw;
                                }

                                    // Advance pos immediately after sendData —
                                    // the plaintext is already encrypted and
                                    // queued in the TLS send_queue.  If the
                                    // flush_out below throws EAGAIN we must not
                                    // re-encrypt this chunk on the next cycle.
                                    if (consumed > 0) {
                                    // Advance position instead of erasing from the front
                                    // (erase from vector front is O(n) due to element shift).
                                        c->SendData.pos += consumed;
                                        if (c->SendData.pos >= c->SendData.size()) {
                                        // All data consumed — clear and reset
                                            c->SendData.clear();
                                            c->SendData.pos = 0;
                                        } else if (c->SendData.pos > BLOCKSIZE * 4) {
                                        // Compact only when waste exceeds threshold
                                            c->SendData.erase(c->SendData.begin(), c->SendData.begin() + c->SendData.pos);
                                            c->SendData.pos = 0;
                                        }
                                    } else {
                                    // No progress made, socket likely full
                                        break;
                                    }
                                    if (c->slots[0].csock->hasPendingWrite())
                                        c->slots[0].csock->flush_out();
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        sendBlockedWouldBlock = true;
                                        break;
                                    }
                                    throw;
                                }
                            }

                            // Send blocked, guard will re-arm with EPOLLOUT
+14 −12
Changes for src/event/kqueue.cpp: 14 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -575,31 +575,33 @@ namespace netplus {
                                size_t consumed = 0;
                                try {
                                    consumed = c->csock->sendData(out, 0);
                                    if (c->csock->hasPendingWrite())
                                        c->csock->flush_out();
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        sendBlockedWouldBlock = true;
                                        break;
                                    }
                                    throw;
                                }

                                    // Advance pos immediately after sendData —
                                    // the plaintext is already encrypted and
                                    // queued in the TLS send_queue.  If the
                                    // flush_out below throws EAGAIN we must not
                                    // re-encrypt this chunk on the next cycle.
                                    if (consumed > 0) {
                                        c->SendData.pos += consumed;
                                        if (c->SendData.pos >= c->SendData.size()) {
                                            c->SendData.clear();
                                            c->SendData.pos = 0;
                                        } else if (c->SendData.pos > BLOCKSIZE * 4) {
                                        // Compact only when waste exceeds threshold
                                            c->SendData.erase(c->SendData.begin(), c->SendData.begin() + c->SendData.pos);
                                            c->SendData.pos = 0;
                                        }
                                    } else {
                                    // No progress, socket full — need WRITE to resume
                                        sendBlockedWouldBlock = true;
                                        break;
                                    }
                                    if (c->csock->hasPendingWrite())
                                        c->csock->flush_out();
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        sendBlockedWouldBlock = true;
                                        break;
                                    }
                                    throw;
                                }
                            }

                            // Send blocked — guard auto-detects and arms WRITE
+134 −36
Changes for src/quic.cpp: 134 added lines, 36 removed lines.
Original line number Diff line number Diff line
@@ -40,7 +40,7 @@
#include <chrono>
#include <cstdio>

#define QUIC_DBG(fmt, ...) fprintf(stderr, "[QUIC] " fmt "\n", ##__VA_ARGS__)
#define QUIC_DBG(fmt, ...) do {} while(0)

namespace netplus {

@@ -2650,6 +2650,7 @@ void quic::processFrame(const uint8_t* data, size_t len, size_t& offset) {
                size_t bytes;
                _max_data_remote = decodeVarInt(&data[offset], bytes);
                offset += bytes;
                QUIC_DBG("processFrame: MAX_DATA new_limit=%lu", (unsigned long)_max_data_remote);
            }
            break;

@@ -2662,10 +2663,14 @@ void quic::processFrame(const uint8_t* data, size_t len, size_t& offset) {
                offset += bytes;
                auto it = _streams.find(sid);
                if (it != _streams.end()) {
                    if (max_sd > it->second.max_data_remote)
                    if (max_sd > it->second.max_data_remote) {
                        QUIC_DBG("processFrame: MAX_STREAM_DATA sid=%lu new_limit=%lu (was %lu)",
                                 (unsigned long)sid, (unsigned long)max_sd,
                                 (unsigned long)it->second.max_data_remote);
                        it->second.max_data_remote = max_sd;
                    }
                }
            }
            break;

        case 0x12:  // MAX_STREAMS (bidi)
@@ -3261,6 +3266,14 @@ void quic::sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data,
    std::lock_guard<std::recursive_mutex> lock(quic_mtx());
    QUIC_DBG("sendStreamData: sid=%lu data_len=%zu fin=%d", (unsigned long)stream_id, data.size(), (int)fin);

    if (_conn_state.load() != ConnectionState::Connected && !_handshake_complete) {
        return;
    }

    if (data.empty() && !fin) {
        return;
    }

    // Maximum QUIC datagram size minus short header overhead:
    //   1 (flags) + dcid_len + 4 (PN) + 16 (GCM tag) + frame header (~11 max)
    const size_t header_overhead = 1 + _remote_cid.size() + 4 + 16;
@@ -3275,94 +3288,136 @@ void quic::sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data,
    auto& stream = _streams[stream_id];
    stream.stream_id = stream_id;

    // Compute how much data we're allowed to send (flow control)
    size_t total_len = data.size();
    size_t buf_offset = 0;        // how much of 'data' we've sent so far
    int fc_stalls = 0;
    // 60s max stall — large transfers need time for client FC updates
    static constexpr int MAX_FC_STALLS = 60000;
    bool blocked_sent = false;
    size_t pkt_counter = 0;       // packets sent since last pump/pace

    // Pacing: pump incoming + brief sleep every N packets to let the
    // client process data and send MAX_STREAM_DATA / MAX_DATA updates.
    // Without this, burst-sending hundreds of packets causes packet loss
    // and the client never increases the FC window.
    static constexpr size_t PACE_INTERVAL = 10;

    while (buf_offset < data.size()) {
        size_t remaining = data.size() - buf_offset;

        // Connection-level flow control
    if (_data_sent + total_len > _max_data_remote) {
        total_len = (_max_data_remote > _data_sent) ?
        if (_data_sent + remaining > _max_data_remote) {
            remaining = (_max_data_remote > _data_sent) ?
                        static_cast<size_t>(_max_data_remote - _data_sent) : 0;
        if (total_len < data.size()) {
            sendDataBlocked(_max_data_remote);
        }
        }

        // Stream-level flow control
    if (stream.send_offset + total_len > stream.max_data_remote) {
        if (stream.send_offset + remaining > stream.max_data_remote) {
            size_t stream_allowed = (stream.max_data_remote > stream.send_offset) ?
                                    static_cast<size_t>(stream.max_data_remote - stream.send_offset) : 0;
        if (stream_allowed < total_len) {
            if (stream_allowed < remaining)
                remaining = stream_allowed;
        }

        if (remaining == 0) {
            // Flow control blocked — notify peer once per stall episode
            if (!blocked_sent) {
                QUIC_DBG("sendStreamData: FC BLOCKED sid=%lu buf_off=%zu/%zu "
                         "conn_sent=%lu conn_max=%lu stream_off=%lu stream_max=%lu",
                         (unsigned long)stream_id, buf_offset, data.size(),
                         (unsigned long)_data_sent, (unsigned long)_max_data_remote,
                         (unsigned long)stream.send_offset, (unsigned long)stream.max_data_remote);
                sendDataBlocked(_max_data_remote);
                sendStreamDataBlocked(stream_id, stream.max_data_remote);
            total_len = stream_allowed;
                blocked_sent = true;
            }

            if (++fc_stalls > MAX_FC_STALLS) {
                QUIC_DBG("sendStreamData: FC stall timeout sid=%lu sent=%zu/%zu "
                         "conn_sent=%lu conn_max=%lu stream_off=%lu stream_max=%lu",
                         (unsigned long)stream_id, buf_offset, data.size(),
                         (unsigned long)_data_sent, (unsigned long)_max_data_remote,
                         (unsigned long)stream.send_offset, (unsigned long)stream.max_data_remote);
                break;
            }

    if (total_len == 0 && !fin) {
        return;
            // Process incoming datagrams to receive MAX_DATA / MAX_STREAM_DATA
            pumpIncoming();
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            continue;
        }

    size_t offset = 0;
    while (offset < total_len) {
        size_t chunk_len = std::min(total_len - offset, max_stream_data);
        bool is_last = (offset + chunk_len >= total_len);
        bool set_fin = fin && is_last && (total_len == data.size());
        fc_stalls = 0;
        blocked_sent = false;

        // Send chunks for the FC-allowed portion
        size_t chunk_offset = 0;
        while (chunk_offset < remaining) {
            // Pacing: every PACE_INTERVAL packets, drain incoming and
            // yield briefly so the client can process data and update FC.
            if (++pkt_counter % PACE_INTERVAL == 0) {
                pumpIncoming();
                std::this_thread::sleep_for(std::chrono::microseconds(200));

                // Re-check FC limits — pumpIncoming may have raised them,
                // allowing us to send more than the original 'remaining'.
                // We break out of the inner loop to re-evaluate at the
                // outer loop which recalculates FC limits.
            }

            size_t chunk_len = std::min(remaining - chunk_offset, max_stream_data);
            size_t abs_offset = buf_offset + chunk_offset;
            bool is_last_data = (abs_offset + chunk_len >= data.size());
            bool set_fin = fin && is_last_data;

        // Use the actual stream send_offset for the QUIC STREAM frame
            uint64_t stream_off = stream.send_offset;

        // Frame type: 0x08 base + 0x02 (LEN always set)
            uint8_t frame_type = 0x08 | 0x02;
        if (stream_off > 0) frame_type |= 0x04;  // OFF bit when stream offset > 0
        if (set_fin) frame_type |= 0x01;      // FIN bit
            if (stream_off > 0) frame_type |= 0x04;
            if (set_fin) frame_type |= 0x01;

            std::vector<uint8_t> frame;
            frame.reserve(frame_hdr_max + chunk_len);
            frame.push_back(frame_type);

        // Stream ID (varint)
            uint8_t varint_buf[8];
            size_t bytes = encodeVarInt(stream_id, varint_buf);
            frame.insert(frame.end(), varint_buf, varint_buf + bytes);

        // Offset (varint) — only if OFF bit is set
            if (stream_off > 0) {
                bytes = encodeVarInt(stream_off, varint_buf);
                frame.insert(frame.end(), varint_buf, varint_buf + bytes);
            }

        // Length (varint)
            bytes = encodeVarInt(chunk_len, varint_buf);
            frame.insert(frame.end(), varint_buf, varint_buf + bytes);

        // Data chunk
        frame.insert(frame.end(), data.begin() + offset, data.begin() + offset + chunk_len);
            frame.insert(frame.end(),
                         data.begin() + abs_offset,
                         data.begin() + abs_offset + chunk_len);

        // Build and send as a 1-RTT short header packet
            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) {
            // Retry with increasing backoff (UDP send buffer may be full)
                for (int retry = 0; retry < 10 && sent < 0; ++retry) {
                    std::this_thread::sleep_for(
                        std::chrono::microseconds(100 * (1 << retry)));
                    sent = sendPacket(packet.data(), packet.size());
                }
            if (sent < 0) {
                return;
            }
                if (sent < 0) goto done;
            }

        // Update flow control counters
            stream.send_offset += chunk_len;
            _data_sent += chunk_len;
            chunk_offset += chunk_len;
        }

        offset += chunk_len;
        buf_offset += remaining;
    }

done:
    if (fin) {
        stream.send_fin = true;
    }
@@ -4419,6 +4474,49 @@ std::vector<uint8_t> quic::buildAckFrame(uint64_t largest_ack, uint64_t ack_dela
    return frame;
}

// ============================================================================
// pumpIncoming: Drain incoming UDP datagrams and process them
//
// Called from long-running stream callbacks (e.g. H3 streaming) to keep
// QUIC flow control alive.  Reads datagrams from the parent's (or own)
// UDP socket and processes ACKs, MAX_DATA, MAX_STREAM_DATA, etc.
// ============================================================================

void quic::pumpIncoming() {
    quic* parent = _parent ? _parent : this;
    std::lock_guard<std::recursive_mutex> lock(quic_mtx());

    static constexpr int MAX_PUMP = 64;
    for (int i = 0; i < MAX_PUMP; ++i) {
        std::vector<uint8_t> dgram(65535);
        sockaddr_storage peer_addr{};
        socklen_t peer_len = sizeof(peer_addr);

        ssize_t recv_len = ::recvfrom(parent->_Socket,
                                       reinterpret_cast<char*>(dgram.data()),
                                       static_cast<int>(dgram.size()),
                                       MSG_DONTWAIT,
                                       reinterpret_cast<sockaddr*>(&peer_addr),
                                       &peer_len);
        if (recv_len <= 0) break;
        dgram.resize(static_cast<size_t>(recv_len));

        // Short header packets — route via DCID
        if (!(dgram[0] & 0x80)) {
            static constexpr size_t CID_LEN = 8;
            if (dgram.size() < 1 + CID_LEN) continue;
            std::vector<uint8_t> dcid(dgram.begin() + 1,
                                       dgram.begin() + 1 + CID_LEN);
            auto it = parent->_child_connections.find(dcid);
            if (it != parent->_child_connections.end() && it->second) {
                it->second->processIncomingPacket(dgram.data(), dgram.size());
            }
        }
        // Long header packets during streaming are unlikely; ignore them
        // to keep this helper simple.
    }
}

// ============================================================================
// Socket Interface: flush_out (Send queued data)
// ============================================================================
+5 −0
Changes for src/socket.h: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -607,6 +607,11 @@ namespace netplus {
		// Send data on a stream (vector overload for application use)
		void sendStreamData(uint64_t stream_id, const std::vector<uint8_t>& data, bool fin);

		// Drain incoming UDP datagrams and process them (ACKs,
		// flow-control updates) so long-running stream callbacks
		// don't starve the QUIC connection.
		void pumpIncoming();

	private:
		// Packet processing
		void processIncomingPacket(const uint8_t* data, size_t len);