Commit 85c05f88 authored by jan.koester's avatar jan.koester
Browse files

pmtu added

parent 1a8e7395
Loading
Loading
Loading
Loading
+106 −8
Changes for src/quic.cpp: 106 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -479,6 +479,82 @@ void quic::onPacketLostCC(size_t packet_size, uint64_t pn) {
    }
}

// ============================================================================
// Path MTU Discovery (DPLPMTUD, RFC 8899 / RFC 9000 §14.3-14.4)
// ============================================================================

// Send a PATH_CHALLENGE padded with PADDING frames to an exact wire size,
// and record it as the outstanding probe. header_overhead mirrors the
// formula sendData()/sendStreamData() use for stream-data chunking: flags
// (1) + DCID + packet number (4) + AEAD tag (16).
void quic::pmtudSendProbe(uint64_t size) {
    const size_t header_overhead = 1 + _remote_cid.size() + 4 + 16;
    const size_t path_challenge_len = 9;  // frame type (1) + data (8)
    if (size <= header_overhead + path_challenge_len) return;

    fillRandomBytes(_pmtud_probe_data.data(), _pmtud_probe_data.size());

    std::vector<uint8_t> frame;
    frame.reserve(size - header_overhead);
    frame.push_back(0x1a);  // PATH_CHALLENGE
    frame.insert(frame.end(), _pmtud_probe_data.begin(), _pmtud_probe_data.end());
    frame.resize(size - header_overhead, 0x00);  // PADDING (type 0x00) fills the rest

    std::vector<uint8_t> packet = buildShortHeaderPacket(frame);
    const uint8_t* hp_key = _is_server ? _app_hp_server : _app_hp_client;
    applyHeaderProtection(packet, hp_key);
    sendPacket(packet.data(), packet.size());  // best-effort, like the PING keepalive below

    _pmtud_probe_size = size;
    _pmtud_probe_sent = std::chrono::steady_clock::now();
}

// A PATH_RESPONSE matched our outstanding probe: the probed size is
// confirmed usable, so raise the confirmed send size and widen the
// search's lower bound.
void quic::pmtudOnProbeAcked() {
    _pmtud_lo = _pmtud_probe_size;
    _max_udp_payload = _pmtud_probe_size;
    _pmtud_probe_size = 0;
    _pmtud_attempts = 0;
}

// Called once per pumpNetwork() iteration (alongside the PING keepalive
// check) to drive the probe state machine: retry/time out an outstanding
// probe, or start the next one. Binary search between the largest
// confirmed-working size and the smallest size ruled out so far, bounded
// above by both our own configured ceiling and the peer's advertised
// max_udp_payload_size.
void quic::pmtudTick() {
    if (_pmtud_probe_size != 0) {
        double pto = _rtt_initialized
            ? (_srtt + std::max(4.0 * _rttvar, 0.001) + 0.025)
            : _rto;
        double elapsed = std::chrono::duration<double>(
            std::chrono::steady_clock::now() - _pmtud_probe_sent).count();
        if (elapsed < pto * 2.0) return;  // still within the probe timeout

        if (++_pmtud_attempts < PMTUD_MAX_ATTEMPTS) {
            pmtudSendProbe(_pmtud_probe_size);  // retry, same size
            return;
        }

        // Unconfirmed after repeated attempts — rule this size (and
        // everything larger) out, then fall through to try smaller.
        _pmtud_ruled_out = std::min(_pmtud_ruled_out, _pmtud_probe_size);
        _pmtud_probe_size = 0;
        _pmtud_attempts = 0;
    }

    if (_pmtud_lo == 0) _pmtud_lo = _max_udp_payload;  // seed from today's confirmed size

    uint64_t hi = std::min({_pmtud_ceiling, _pmtud_peer_ceiling, _pmtud_ruled_out - 1});
    if (hi <= _pmtud_lo || hi - _pmtud_lo < PMTUD_CONVERGE)
        return;  // converged, or nothing above the current baseline to explore

    pmtudSendProbe(_pmtud_lo + (hi - _pmtud_lo + 1) / 2);
}

// ============================================================================
// Variable-length Integer Encoding/Decoding (RFC 9000 Section 16)
// ============================================================================
@@ -1337,6 +1413,8 @@ void quic::handshake_after_accept() {
            sendPacket(packet.data(), packet.size());
            _last_activity = now;
        }

        pmtudTick();
    }

    // Collect pending dispatches before releasing lock
@@ -1750,6 +1828,7 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    child_ptr->_parent = this;               // Link to parent for routing
    child_ptr->_stream_callback = _stream_callback;  // Copy stream callback
    child_ptr->_incremental_stream_dispatch = _incremental_stream_dispatch;
    child_ptr->_pmtud_ceiling = _pmtud_ceiling;       // Copy PMTU discovery ceiling

    // Generate our own connection ID for the client to use
    child_ptr->generateConnectionId(child_ptr->_local_cid, 8);
@@ -2766,10 +2845,12 @@ std::vector<uint8_t> quic::buildTransportParameters() {
    params.insert(params.end(), timeout_len_buf, timeout_len_buf + timeout_len_size);
    params.insert(params.end(), timeout_buf, timeout_buf + timeout_len);

    // max_udp_payload_size (0x03) — advertise 1472 (Ethernet-safe, no IP fragmentation)
    // max_udp_payload_size (0x03) — advertise how large a datagram we're
    // willing to receive. Defaults to 1472 (Ethernet-safe); raised via
    // setPmtuCeiling(), which also lets pmtudTick() search higher.
    params.push_back(0x03);
    uint8_t mups_buf[8];
    size_t mups_len = encodeVarInt(1472, mups_buf);
    size_t mups_len = encodeVarInt(_pmtud_ceiling, mups_buf);
    uint8_t mups_len_buf[8];
    size_t mups_len_size = encodeVarInt(mups_len, mups_len_buf);
    params.insert(params.end(), mups_len_buf, mups_len_buf + mups_len_size);
@@ -3409,6 +3490,14 @@ void quic::processFrame(const uint8_t* data, size_t len, size_t& offset) {

        case 0x1b:  // PATH_RESPONSE
            {
                // A match against our own outstanding PMTUD probe (see
                // pmtudSendProbe/pmtudTick) proves a datagram of that
                // exact size traversed the path and was decrypted
                // intact — the confirmation the search is waiting for.
                if (offset + 8 <= len && _pmtud_probe_size != 0 &&
                    std::memcmp(&data[offset], _pmtud_probe_data.data(), 8) == 0) {
                    pmtudOnProbeAcked();
                }
                offset += 8;  // 8 bytes of data
            }
            break;
@@ -4520,14 +4609,23 @@ void quic::parseTransportParameters(const uint8_t* data, size_t len) {
                }
                break;
            }
            case 0x03: {  // max_udp_payload_size
            case 0x03: {  // max_udp_payload_size — the peer's receive
                          // limit: a hard ceiling on what we may ever
                          // send them, but never proof the *path* can
                          // actually carry that size (that's what
                          // pmtudTick()'s probing establishes before
                          // raising _max_udp_payload past the baseline).
                size_t vb;
                uint64_t peer_max_payload = decodeVarInt(&data[offset], vb);
                // Clamp to 1472 (Ethernet-safe, avoids IP fragmentation)
                if (peer_max_payload > 1472)
                    peer_max_payload = 1472;
                if (peer_max_payload > _max_udp_payload)
                    _max_udp_payload = peer_max_payload;
                if (peer_max_payload < 1200)
                    peer_max_payload = 1200;  // RFC 9000 §18.2 floor; ignore bogus/hostile values below it
                _pmtud_peer_ceiling = peer_max_payload;
                // Only ever shrink the confirmed send size here — never
                // grow it. Growing requires an actual probe (see
                // pmtudOnProbeAcked); this just protects a size we may
                // already be using from exceeding what the peer accepts.
                if (_pmtud_peer_ceiling < _max_udp_payload)
                    _max_udp_payload = _pmtud_peer_ceiling;
                break;
            }
            default:
+49 −1
Changes for src/socket.h: 49 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -638,6 +638,22 @@ namespace netplus {

		ConnectionState getConnectionState() const { return _conn_state.load(); }

		// Path MTU Discovery (DPLPMTUD, RFC 8899 / RFC 9000 §14.3-14.4).
		// Probing starts automatically once the handshake completes — no
		// separate enable call needed. This raises the ceiling the
		// post-handshake prober searches toward; the default (1472)
		// matches the fixed pre-discovery baseline exactly, so leaving it
		// untouched is a no-op. The peer's advertised max_udp_payload_size
		// transport parameter always applies as an additional hard ceiling
		// on top of this value. A listening socket's setting is copied to
		// every connection it accepts (see quic::accept()).
		void setPmtuCeiling(uint64_t ceiling) { _pmtud_ceiling = ceiling; }

		// Currently confirmed usable UDP payload size for this
		// connection's sends — 1472 until (and unless) PMTU discovery has
		// probed something larger.
		uint64_t getMaxUdpPayload() const { return _max_udp_payload; }

		// Stream management
		uint64_t openStream(bool bidirectional = true);
		void closeStream(uint64_t stream_id);
@@ -970,9 +986,18 @@ namespace netplus {

		// Transport parameters
		uint64_t _max_idle_timeout = 30000;    // 30s
		uint64_t _max_udp_payload = 1472;      // Default: Ethernet-safe (1500 - IP/UDP headers)
		uint64_t _max_udp_payload = 1472;      // Default: Ethernet-safe (1500 - IP/UDP headers).
		                                        // Also doubles as PMTUD's "current confirmed
		                                        // send size" — see pmtudTick().
		uint64_t _active_connection_id_limit = 2;

		// Path MTU Discovery ceilings (see setPmtuCeiling()). _pmtud_ceiling
		// is our own local cap (what we advertise as max_udp_payload_size
		// and search up to); _pmtud_peer_ceiling is the peer's advertised
		// value, applied as a hard cap in parseTransportParameters().
		uint64_t _pmtud_ceiling = 1472;
		uint64_t _pmtud_peer_ceiling = 1472;

		// Receive/send queues
		std::vector<uint8_t> _recv_buffer;
		std::deque<std::vector<uint8_t>> _send_queue;
@@ -1170,6 +1195,29 @@ namespace netplus {
		void onPacketAckedCC(size_t packet_size, uint64_t pn);
		void onPacketLostCC(size_t packet_size, uint64_t pn);

		// ---- Path MTU Discovery (DPLPMTUD, RFC 8899 / RFC 9000 §14.3-14.4) ----
		// A probe is a PATH_CHALLENGE frame padded with PADDING to an exact
		// target wire size, sent as an ordinary 1-RTT packet. Success is
		// judged solely by receiving a PATH_RESPONSE echoing the challenge
		// data back — proof a datagram of that exact size both left this
		// host and was decrypted intact by the peer, which ACK/loss
		// tracking alone can't distinguish from "would've been fine at a
		// smaller size too". Deliberately kept out of
		// _sent_packets/onPacketLostCC: RFC 9000 §14.4 requires that
		// losing a PMTU probe NOT be treated as a congestion signal, since
		// a path MTU black hole has nothing to do with congestion.
		uint64_t _pmtud_lo = 0;          // largest confirmed-working size this search (0 = not yet seeded)
		uint64_t _pmtud_ruled_out = UINT64_MAX; // smallest size confirmed NOT to work (exclusive upper bound)
		uint64_t _pmtud_probe_size = 0;  // size of the probe currently in flight (0 = none outstanding)
		std::array<uint8_t, 8> _pmtud_probe_data{};
		std::chrono::steady_clock::time_point _pmtud_probe_sent;
		int _pmtud_attempts = 0;         // retries already made at the current probe size
		static constexpr int PMTUD_MAX_ATTEMPTS = 3;
		static constexpr uint64_t PMTUD_CONVERGE = 8; // stop searching once the [lo, hi) gap closes to this many bytes
		void pmtudTick();                // called once per pumpNetwork() iteration
		void pmtudSendProbe(uint64_t size);
		void pmtudOnProbeAcked();         // matching PATH_RESPONSE arrived

		// ACK tracking: need to send ACK for initial/handshake levels
		bool _need_initial_ack = false;
		bool _need_handshake_ack = false;