Commit 883d5530 authored by jan.koester's avatar jan.koester
Browse files

test

parent cd08ca21
Loading
Loading
Loading
Loading
+128 −4
Changes for src/quic.cpp: 128 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -1540,6 +1540,41 @@ void quic::runDispatchQueue(std::shared_ptr<quic> self) {
    // goes out of scope here, dropping this function's reference.
}

// ============================================================================
// Retry Packet (RFC 9000 §17.2.5 / §8.1.2) — server side
// ============================================================================

void quic::sendRetryPacket(const std::vector<uint8_t>& client_dcid,
                            const std::vector<uint8_t>& client_scid,
                            sockaddr_storage peer_addr, socklen_t peer_len) {
    std::vector<uint8_t> token = generateToken(true, client_dcid, peer_addr, peer_len);
    if (token.empty()) return; // unsupported peer address family

    // Fresh CID for the client to use as DCID on its retried Initial —
    // stateless: we don't need to remember this anywhere (see _retry_scid's
    // comment in socket.h for how the server recovers it later, from the
    // retried Initial's own DCID field).
    std::vector<uint8_t> retry_scid;
    generateConnectionId(retry_scid, 8);

    std::vector<uint8_t> packet;
    packet.push_back(0xF0); // long header, fixed bit, type=Retry(0b11), unused nibble=0
    packet.push_back(static_cast<uint8_t>(_version >> 24));
    packet.push_back(static_cast<uint8_t>(_version >> 16));
    packet.push_back(static_cast<uint8_t>(_version >> 8));
    packet.push_back(static_cast<uint8_t>(_version));
    packet.push_back(static_cast<uint8_t>(client_scid.size())); // DCID = client's SCID
    packet.insert(packet.end(), client_scid.begin(), client_scid.end());
    packet.push_back(static_cast<uint8_t>(retry_scid.size()));  // SCID = our fresh CID
    packet.insert(packet.end(), retry_scid.begin(), retry_scid.end());
    packet.insert(packet.end(), token.begin(), token.end());    // Retry Token

    auto tag = computeRetryIntegrityTag(client_dcid, packet.data(), packet.size());
    packet.insert(packet.end(), tag.begin(), tag.end());

    sendBatch({{packet.data(), packet.size()}}, &peer_addr, peer_len);
}

// ============================================================================
// Socket Interface: accept (Server-side connection acceptance)
// ============================================================================
@@ -1859,6 +1894,31 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    std::vector<uint8_t> token(dgram.begin() + offset, dgram.begin() + offset + token_len);
    offset += token_len;

    // RFC 9000 §8.1: require address validation before creating any
    // connection state. No token at all, or one that fails validation
    // (tampered/expired/wrong address — treated the same as absent rather
    // than dropped outright, so a legitimate client with a stale token
    // recovers in one more round trip instead of hanging), gets a Retry
    // and nothing else: no child object, nothing to clean up.
    ParsedToken parsed_token;
    if (!token.empty()) {
        parsed_token = validateToken(token, peer_addr, peer_len);
    }
    if (!parsed_token.valid) {
        sendRetryPacket(dcid, scid, peer_addr, peer_len);
        continue;
    }

    // The client's TRUE original DCID: for a Retry-validated connection,
    // extracted from the token (this packet's own `dcid` is the server's
    // Retry SCID instead — RFC 9001 §5.2 derives Initial keys from the
    // client's *first* Initial packet's DCID, which must stay fixed across
    // the Retry round trip); for a NEW_TOKEN-validated connection (no
    // Retry occurred), `dcid` already *is* the client's first Initial's
    // DCID.
    const std::vector<uint8_t>& true_original_dcid =
        parsed_token.is_retry ? parsed_token.original_dcid : dcid;

    // Create new QUIC connection socket for this client. Lock its own
    // mutex immediately, before it's configured or registered — nothing
    // else can be contending for this specific (brand new) mutex yet, and
@@ -1874,7 +1934,13 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    child_ptr->_version = version;
    // RFC 9000: Server sends packets TO the client using the client's SCID as DCID
    child_ptr->_remote_cid = scid;           // Client's SCID becomes our DCID for responses
    child_ptr->_original_dcid = dcid;        // Original DCID for key derivation
    child_ptr->_original_dcid = true_original_dcid;  // True original DCID, for key derivation
    if (parsed_token.is_retry) {
        // For the retry_source_connection_id transport parameter — see
        // _retry_scid's comment in socket.h for why `dcid` (this packet's
        // own DCID field) is exactly right here.
        child_ptr->_retry_scid = dcid;
    }
    child_ptr->_cert_map = _cert_map;        // Copy certificate configuration
    child_ptr->_parent = this;               // Link to parent for routing
    child_ptr->_stream_callback = _stream_callback;  // Copy stream callback
@@ -1966,8 +2032,10 @@ void quic::accept(std::unique_ptr<socket>& csock, bool nonblock) {
        child_ptr->setNonBlock();
    }

    // Derive initial keys from the original DCID
    child_ptr->deriveInitialKeys(dcid, true);
    // Derive initial keys from the client's TRUE original DCID (RFC 9001
    // §5.2 — not this packet's own `dcid` field once a Retry occurred, see
    // true_original_dcid's comment above).
    child_ptr->deriveInitialKeys(true_original_dcid, true);

    // Store the received Initial packet for processing
    child_ptr->_recv_buffer = dgram;
@@ -2155,11 +2223,67 @@ void quic::processLongHeaderPacket(const uint8_t* data, size_t len) {
            processHandshakePacket(data, len);
            break;
        case 0x03:  // Retry
            // TODO: Implement Retry handling
            processRetryPacket(data, len);
            break;
    }
}

void quic::processRetryPacket(const uint8_t* data, size_t len) {
    // Only clients act on a Retry (a server never legitimately receives
    // one), and at most once per connection (RFC 9000 §17.2.5.2) — a
    // second Retry is discarded, not reprocessed.
    if (_is_server || _retry_received) return;
    // Only meaningful while still waiting on the very first Initial's
    // response; one arriving after the handshake has moved past that point
    // is stale/spurious.
    if (_handshake_complete || _conn_state.load() != ConnectionState::Handshaking) return;

    if (len < 7) return;
    size_t offset = 5; // after first byte + version
    if (offset >= len) return;
    uint8_t dcid_len = data[offset++];
    if (dcid_len > len - offset) return;
    // This is our own SCID echoed back as the Retry's DCID (RFC 9000
    // §17.2.5.1) — confirm it's actually addressed to us before trusting
    // anything else in the packet.
    if (dcid_len != _local_cid.size() ||
        !std::equal(_local_cid.begin(), _local_cid.end(), data + offset)) {
        return;
    }
    offset += dcid_len;
    if (offset >= len) return;
    uint8_t scid_len = data[offset++];
    if (scid_len > len - offset) return;
    std::vector<uint8_t> scid(data + offset, data + offset + scid_len);
    offset += scid_len;

    // Whatever remains, minus the trailing 16-byte Integrity Tag, is the
    // Retry Token — Retry has no length prefix on it, unlike Initial.
    if (len < offset + 16) return; // not even room for the tag
    size_t token_len = len - offset - 16;
    std::vector<uint8_t> token(data + offset, data + offset + token_len);

    // Verify the Integrity Tag before trusting anything in this packet.
    auto expected_tag = computeRetryIntegrityTag(_original_dcid, data, len - 16);
    if (!std::equal(expected_tag.begin(), expected_tag.end(), data + len - 16)) {
        return; // drop silently — off-path noise or corruption, not fatal
    }

    _retry_received = true;
    _pending_token = token;
    _retry_scid = scid; // for the Phase 3 transport-parameter cross-check
    _remote_cid = scid; // new DCID for the resent Initial

    // Deliberately NOT re-deriving Initial keys here — RFC 9001 §5.2 keys
    // them off the client's *first* Initial's DCID, which never changes
    // across a Retry; only the wire-level _remote_cid (and the token)
    // change for the resend.
    std::vector<uint8_t> packet = buildInitialPacket(_initial_crypto_frame);
    applyHeaderProtection(packet, EncryptionLevel::Initial, _initial_keys.send);
    buffer send_buf(reinterpret_cast<const char*>(packet.data()), packet.size());
    udp::sendData(send_buf, 0);
}

void quic::processShortHeaderPacket(const uint8_t* data, size_t len) {
    // Short header packets are 1-RTT (application data)
    QUIC_DBG("processShortHeaderPacket: len=%zu", len);
+12 −0
Changes for src/socket.h: 12 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -779,6 +779,10 @@ namespace netplus {
		void processInitialPacket(const uint8_t* data, size_t len);
		void processHandshakePacket(const uint8_t* data, size_t len);
		void processApplicationPacket(const uint8_t* data, size_t len);
		// Client-side: handle an incoming Retry packet (RFC 9000 §8.1.2) —
		// verify its RFC 9001 §5.8 Integrity Tag, capture the token + new
		// SCID, and resend the (already-built) Initial with the token.
		void processRetryPacket(const uint8_t* data, size_t len);

		// Frame processing
		// ack_eliciting is set to whether this frame counts as ack-eliciting
@@ -820,6 +824,14 @@ namespace netplus {
		std::vector<uint8_t> buildInitialPacket(const std::vector<uint8_t>& payload);
		std::vector<uint8_t> buildHandshakePacket(const std::vector<uint8_t>& payload);
		std::vector<uint8_t> buildShortHeaderPacket(const std::vector<uint8_t>& payload);
		// Server-side: build and send a Retry packet (RFC 9000 §17.2.5) in
		// response to an Initial that arrived without a valid
		// address-validation token. `client_dcid`/`client_scid` are that
		// Initial's own DCID/SCID fields. No child connection exists yet —
		// sent directly on the listening socket to `peer_addr`.
		void sendRetryPacket(const std::vector<uint8_t>& client_dcid,
		                     const std::vector<uint8_t>& client_scid,
		                     sockaddr_storage peer_addr, socklen_t peer_len);

		// Frame building
		std::vector<uint8_t> buildCryptoFrame(const std::vector<uint8_t>& data, uint64_t offset);