Skip to main content

turnloop_http/
http2.rs

1//! RFC 9113 connection/stream framing. Caller retains partial frames and acknowledges
2//! writes. DATA is borrowed, flow-control credit is returned explicitly by the host.
3use crate::{Error, Result, hpack, http1::Header};
4use std::{collections::VecDeque, time::Instant};
5pub const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Role {
8    Client,
9    Server,
10}
11#[derive(Debug, Clone, Copy)]
12pub struct Limits {
13    pub frame_size: usize,
14    pub header_block: usize,
15    pub header_list: usize,
16    pub continuations: usize,
17    pub streams: usize,
18}
19impl Default for Limits {
20    fn default() -> Self {
21        Self {
22            frame_size: 16384,
23            header_block: 65536,
24            header_list: 32768,
25            continuations: 16,
26            streams: 100,
27        }
28    }
29}
30/// SETTINGS parameters this endpoint sends: at most one value per identifier,
31/// kept and serialised in ascending identifier order (the order Node writes
32/// them in). An empty `Settings` is a valid, empty SETTINGS frame.
33///
34/// Identifiers this crate does not know are sent as given, so a host can
35/// advertise extension settings; the named constants are the ones RFC 9113
36/// section 6.5.2 and RFC 8441 define.
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct Settings {
39    entries: Vec<(u16, u32)>,
40}
41impl Settings {
42    pub const HEADER_TABLE_SIZE: u16 = 1;
43    pub const ENABLE_PUSH: u16 = 2;
44    pub const MAX_CONCURRENT_STREAMS: u16 = 3;
45    pub const INITIAL_WINDOW_SIZE: u16 = 4;
46    pub const MAX_FRAME_SIZE: u16 = 5;
47    pub const MAX_HEADER_LIST_SIZE: u16 = 6;
48    pub const ENABLE_CONNECT_PROTOCOL: u16 = 8;
49    pub fn new() -> Self {
50        Self::default()
51    }
52    /// The three limits [`Connection::new`] advertises.
53    pub fn from_limits(limits: &Limits) -> Self {
54        let mut settings = Self::new();
55        settings
56            .set(Self::MAX_CONCURRENT_STREAMS, limits.streams as u32)
57            .set(Self::MAX_FRAME_SIZE, limits.frame_size as u32)
58            .set(Self::MAX_HEADER_LIST_SIZE, limits.header_list as u32);
59        settings
60    }
61    /// Set `id` to `value`, replacing any earlier value for it.
62    pub fn set(&mut self, id: u16, value: u32) -> &mut Self {
63        match self.entries.binary_search_by_key(&id, |e| e.0) {
64            Ok(i) => self.entries[i].1 = value,
65            Err(i) => self.entries.insert(i, (id, value)),
66        }
67        self
68    }
69    pub fn remove(&mut self, id: u16) -> Option<u32> {
70        let i = self.entries.binary_search_by_key(&id, |e| e.0).ok()?;
71        Some(self.entries.remove(i).1)
72    }
73    pub fn get(&self, id: u16) -> Option<u32> {
74        let i = self.entries.binary_search_by_key(&id, |e| e.0).ok()?;
75        Some(self.entries[i].1)
76    }
77    /// `(identifier, value)` pairs in ascending identifier order.
78    pub fn iter(&self) -> impl Iterator<Item = (u16, u32)> + '_ {
79        self.entries.iter().copied()
80    }
81    pub fn len(&self) -> usize {
82        self.entries.len()
83    }
84    pub fn is_empty(&self) -> bool {
85        self.entries.is_empty()
86    }
87    fn merge(&mut self, from: impl Iterator<Item = (u16, u32)>) {
88        for (id, value) in from {
89            self.set(id, value);
90        }
91    }
92    fn encode(&self) -> Vec<u8> {
93        let mut payload = Vec::with_capacity(self.entries.len() * 6);
94        for (id, value) in self.iter() {
95            payload.extend_from_slice(&id.to_be_bytes());
96            payload.extend_from_slice(&value.to_be_bytes());
97        }
98        payload
99    }
100    /// Refuse what this endpoint cannot honour once the peer acts on it.
101    fn validate(&self, role: Role) -> Result<()> {
102        for (id, value) in self.iter() {
103            let valid = match id {
104                Self::HEADER_TABLE_SIZE => true,
105                // Only a client may invite pushes (RFC 9113 section 6.5.2); a
106                // server never sends a non-zero ENABLE_PUSH.
107                Self::ENABLE_PUSH => match role {
108                    Role::Client => value <= 1,
109                    Role::Server => value == 0,
110                },
111                Self::INITIAL_WINDOW_SIZE => value <= 0x7fffffff,
112                Self::MAX_FRAME_SIZE => (16384..=0xffffff).contains(&value),
113                Self::ENABLE_CONNECT_PROTOCOL => value <= 1,
114                _ => true,
115            };
116            if !valid {
117                return Err(protocol("invalid SETTINGS value"));
118            }
119        }
120        Ok(())
121    }
122}
123/// The parameters of one SETTINGS frame the peer sent, borrowed from the input
124/// exactly as they were on the wire: in frame order, duplicates and unknown
125/// identifiers included. RFC 9113 section 6.5.3 processes them in that order,
126/// so for a repeated identifier the last value is the one in force.
127#[derive(Debug, Clone, Copy)]
128pub struct SettingsFrame<'a> {
129    payload: &'a [u8],
130}
131impl<'a> SettingsFrame<'a> {
132    pub fn iter(&self) -> impl Iterator<Item = (u16, u32)> + 'a {
133        self.payload
134            .as_chunks::<6>()
135            .0
136            .iter()
137            .map(|s| (u16::from_be_bytes([s[0], s[1]]), u32be(&s[2..])))
138    }
139    /// The value in force for `id` after this frame, if the frame carried it.
140    pub fn get(&self, id: u16) -> Option<u32> {
141        self.iter().filter(|e| e.0 == id).last().map(|e| e.1)
142    }
143    pub fn is_empty(&self) -> bool {
144        self.payload.is_empty()
145    }
146    pub fn to_settings(&self) -> Settings {
147        let mut settings = Settings::new();
148        settings.merge(self.iter());
149        settings
150    }
151}
152#[derive(Debug, Clone, Copy)]
153pub struct Frame<'a> {
154    pub kind: u8,
155    pub flags: u8,
156    pub stream: u32,
157    pub payload: &'a [u8],
158}
159fn error(code: &'static str, message: &'static str) -> Error {
160    Error::new(code, message)
161}
162fn protocol(message: &'static str) -> Error {
163    error("PROTOCOL_ERROR", message)
164}
165fn frame_error() -> Error {
166    error("FRAME_SIZE_ERROR", "invalid frame size")
167}
168fn u32be(b: &[u8]) -> u32 {
169    u32::from_be_bytes(b[..4].try_into().unwrap())
170}
171pub fn decode_frame(input: &[u8], max: usize) -> Result<Option<Frame<'_>>> {
172    if input.len() < 9 {
173        return Ok(None);
174    }
175    let len = ((input[0] as usize) << 16) | ((input[1] as usize) << 8) | input[2] as usize;
176    if len > max {
177        return Err(frame_error());
178    }
179    if input.len() < 9 + len {
180        return Ok(None);
181    }
182    Ok(Some(Frame {
183        kind: input[3],
184        flags: input[4],
185        stream: u32be(&input[5..9]) & 0x7fffffff,
186        payload: &input[9..9 + len],
187    }))
188}
189pub fn encode_frame(
190    kind: u8,
191    flags: u8,
192    stream: u32,
193    payload: &[u8],
194    out: &mut Vec<u8>,
195) -> Result<()> {
196    if payload.len() > 0xffffff || stream > 0x7fffffff {
197        return Err(frame_error());
198    }
199    let len = payload.len() as u32;
200    out.extend_from_slice(&len.to_be_bytes()[1..]);
201    out.push(kind);
202    out.push(flags);
203    out.extend_from_slice(&stream.to_be_bytes());
204    out.extend_from_slice(payload);
205    Ok(())
206}
207/// Which of the three header blocks an [`Event::Headers`] carries. The
208/// connection already enforces the distinction, so a host does not have to
209/// track `received_head` itself to tell them apart.
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211pub enum HeadersKind {
212    /// The request head, or a final (>= 200) response head.
213    Head,
214    /// A 1xx response head. It never ends the stream, and a final head follows.
215    Informational,
216    /// A trailer block. It always ends the stream.
217    Trailers,
218}
219#[derive(Debug)]
220pub enum Event<'a> {
221    /// The peer's SETTINGS, already applied and acknowledged.
222    Settings(SettingsFrame<'a>),
223    /// The peer acknowledged the oldest SETTINGS frame this endpoint still had
224    /// outstanding; its parameters are returned here and are now in force.
225    /// Acknowledgements arrive in the order the frames were sent (RFC 9113
226    /// section 6.5.3), and the first is always for the frame the constructor
227    /// queued, so a host that timestamps construction and each
228    /// [`Connection::settings`] call can pair them in FIFO order to measure a
229    /// round trip. No clock is read here.
230    SettingsAck(Settings),
231    Headers {
232        stream: u32,
233        headers: Vec<Header>,
234        end_stream: bool,
235        kind: HeadersKind,
236    },
237    Data {
238        stream: u32,
239        bytes: &'a [u8],
240        end_stream: bool,
241    },
242    /// The server promised a response to the request `headers` (RFC 9113
243    /// section 8.4), on `stream`, a stream this endpoint opened. `promised` is
244    /// the server-initiated stream that will carry the response: its HEADERS
245    /// and DATA arrive as ordinary events, and [`Connection::reset`] declines
246    /// it. Only a client receives this, and only while it has not disabled push
247    /// with ENABLE_PUSH = 0.
248    PushPromise {
249        stream: u32,
250        promised: u32,
251        headers: Vec<Header>,
252    },
253    /// The stream is over. It may name a stream the host never saw opened: a
254    /// stream past the concurrent-stream limit is refused with
255    /// RST_STREAM(REFUSED_STREAM) before any [`Event::Headers`] for it is
256    /// produced (RFC 9113 section 5.1.2 requires a stream error there, and
257    /// Node answers the same way — measured).
258    Reset {
259        stream: u32,
260        code: u32,
261    },
262    /// The peer opened a stream after a graceful GOAWAY, above the last stream
263    /// id that GOAWAY named, and **nothing has been sent for it**. RFC 9113
264    /// section 6.8 makes such a stream simply "not processed" — the peer is
265    /// expected to retry it on a new connection — and Node emits no frame at
266    /// all here (measured against Node 26.5.1 with a raw peer: no RST_STREAM,
267    /// no GOAWAY, the session stays alive and the request never reaches the
268    /// application).
269    ///
270    /// The header block was decoded and discarded, because HPACK is connection
271    /// state. The connection deliberately does not answer for the host: a frame
272    /// it emitted could not be un-emitted, so a host that must match Node would
273    /// have no way back. A host that wants to answer may call
274    /// [`Connection::reset`].
275    Unprocessed {
276        stream: u32,
277    },
278    Goaway {
279        last_stream: u32,
280        code: u32,
281        /// The opaque debug data (RFC 9113 section 6.8). `None` when the frame
282        /// carried none - Node reports `undefined` there, not an empty buffer.
283        /// The wire cannot express "present but empty", so this is never
284        /// `Some` of an empty slice.
285        debug: Option<&'a [u8]>,
286    },
287    Ping {
288        ack: bool,
289        data: [u8; 8],
290    },
291    WindowUpdate {
292        stream: u32,
293    },
294}
295/// One decode step: how much of `input` was consumed, and the event it
296/// produced, if any. See the [step contract](crate#the-step-contract).
297///
298/// **`consumed` and `event` are independent.** All three shapes are normal:
299///
300/// | `consumed` | `event` | meaning |
301/// |---|---|---|
302/// | `0` | `None` | **stop.** A partial preface or a partial frame; read more input before calling again. |
303/// | `> 0` | `None` | **keep going.** Progress with nothing for the host: the client preface, PRIORITY, an unknown frame type, or a frame the peer had in flight for a stream that is already gone. |
304/// | `> 0` | `Some` | an event. In HTTP/2 an event always consumes; `consumed == 0` is only ever the stop case. |
305///
306/// So the loop condition is `consumed > 0 || event.is_some()`:
307///
308/// ```
309/// # use turnloop_http::http2::{Connection, Limits, Role, PREFACE};
310/// # let mut connection = Connection::new(Role::Server, Limits::default())?;
311/// # let mut input = PREFACE.to_vec();
312/// loop {
313///     let step = connection.receive(&input)?;
314///     let consumed = step.consumed;
315///     let progressed = consumed > 0 || step.event.is_some();
316///     if let Some(event) = step.event {
317///         // DATA borrows `input`, so handle the event before draining.
318///         let _ = event;
319///     }
320///     input.drain(..consumed);
321///     if !progressed {
322///         break; // read more bytes from the transport, then continue
323///     }
324/// }
325/// # Ok::<(), turnloop_http::Error>(())
326/// ```
327///
328/// Looping while `event.is_some()` instead **stalls at the client preface** —
329/// the first step of every server connection, before a single frame is read.
330/// Looping while input remains spins forever on a partial frame.
331#[derive(Debug)]
332pub struct Step<'a> {
333    pub consumed: usize,
334    pub event: Option<Event<'a>>,
335}
336/// What to do with a header block that does not belong to a live stream. Every
337/// arm decodes the block first: HPACK is connection state, and a block that is
338/// skipped desynchronises every block after it.
339#[derive(Debug, Clone, Copy)]
340enum Disposal {
341    /// Past the concurrent-stream limit: answer RST_STREAM and report it.
342    /// RFC 9113 section 5.1.2 requires a stream error here.
343    Refuse(u32),
344    /// Opened after our graceful GOAWAY: send nothing, report it, and let the
345    /// host decide. See [`Event::Unprocessed`].
346    Unprocessed,
347    /// Frames the peer had in flight for a stream that is gone: discard in
348    /// silence. The host already knows - it is the side that ended the stream.
349    Discard,
350}
351#[derive(Debug)]
352struct Stream {
353    id: u32,
354    send_window: i64,
355    recv_window: i64,
356    unreleased: u32,
357    /// The peer reset this stream and its remaining connection credit was
358    /// returned in bulk, so a late `release_capacity` for it is a no-op.
359    credited: bool,
360    local_end: bool,
361    remote_end: bool,
362    received_head: bool,
363    sent_head: bool,
364    recv_length: Option<u64>,
365    received: u64,
366    head_request: bool,
367    recv_no_body: bool,
368    send_no_body: bool,
369    send_length: Option<u64>,
370    sent: u64,
371}
372impl Stream {
373    fn closed(&self) -> bool {
374        self.local_end && self.remote_end
375    }
376}
377pub struct Connection {
378    role: Role,
379    limits: Limits,
380    streams: Vec<Stream>,
381    next_id: u32,
382    /// Highest remote stream id this connection has accepted **for processing**.
383    /// GOAWAY names it, so a stream that was reported but not processed - one
384    /// refused past the stream limit, or arriving after our own GOAWAY - must
385    /// not advance it: RFC 9113 section 6.8 lets the peer retry everything above
386    /// it on a new connection, and claiming one is processed loses that request.
387    last_remote: u32,
388    /// Highest remote stream id seen on the wire, processed or not. The
389    /// monotonicity check and [`Connection::seen`] use this, so frames the peer
390    /// had in flight for a stream we declined are still tolerated.
391    highest_remote: u32,
392    send_window: i64,
393    recv_window: i64,
394    initial_send: i64,
395    peer_frame: usize,
396    peer_streams: usize,
397    preface: bool,
398    settings_received: bool,
399    /// SETTINGS frames sent and not yet acknowledged, oldest first. RFC 9113
400    /// section 6.5.3 acknowledges them in order, so this is a queue: a second
401    /// frame sent while one is outstanding is ordinary, not an error.
402    settings_pending: VecDeque<Settings>,
403    /// Every local parameter the peer has acknowledged, merged in order.
404    local_settings: Settings,
405    /// Every parameter the peer has sent, merged in order.
406    remote_settings: Settings,
407    /// The limits the acknowledged frames establish. `limits`, the ones
408    /// enforced, is this relaxed by every outstanding frame: see
409    /// `enforce_settings`.
410    acked_limits: Limits,
411    /// Our SETTINGS_INITIAL_WINDOW_SIZE as acknowledged, and as enforced.
412    acked_recv_initial: i64,
413    acked_table: usize,
414    /// Whether this endpoint accepts PUSH_PROMISE: ENABLE_PUSH as acknowledged,
415    /// loosened by every outstanding frame, defaulting to enabled.
416    acked_push: bool,
417    push_allowed: bool,
418    recv_initial: i64,
419    decoder: hpack::Decoder,
420    encoder: hpack::Encoder,
421    block: Vec<u8>,
422    scratch: Vec<u8>,
423    continuation: Option<(u32, bool, usize)>,
424    /// What to do with the header block being assembled, when it does not
425    /// belong to a live stream. HPACK is connection state, so such a block
426    /// still has to advance the decoder before it is thrown away.
427    disposal: Option<Disposal>,
428    /// PINGs sent and not yet acknowledged. An acknowledgement with none
429    /// outstanding answers nothing this endpoint sent.
430    pings: usize,
431    /// Whether an acknowledgement with no PING outstanding fails the connection.
432    reject_unsolicited_ping_ack: bool,
433    /// The PUSH_PROMISE whose header block is being assembled: the promised
434    /// stream and whether the block is only to be decoded and dropped (the
435    /// associated stream is gone).
436    promise: Option<(u32, bool)>,
437    output: Vec<u8>,
438    output_pos: usize,
439    draining: bool,
440    failed: bool,
441    settings_deadline: Option<Instant>,
442}
443impl Connection {
444    /// A connection whose initial SETTINGS advertises `limits`: the
445    /// concurrent-stream, frame-size and header-list limits, in that
446    /// (ascending) identifier order.
447    pub fn new(role: Role, limits: Limits) -> Result<Self> {
448        Self::with_settings(role, limits, &Settings::from_limits(&limits))
449    }
450    /// A connection whose initial SETTINGS frame carries exactly `settings`,
451    /// serialised in ascending identifier order. `Settings::new()` sends an
452    /// empty frame, which is what Node's server sends.
453    ///
454    /// `limits` is what this endpoint enforces on its own. A parameter in
455    /// `settings` that corresponds to a limit replaces it once the peer
456    /// acknowledges the frame (and at once, if that relaxes it: the peer may
457    /// act on the new value before its ack reaches us). A client that
458    /// does not name ENABLE_PUSH leaves push enabled, as the protocol defaults
459    /// it, and surfaces each promise as [`Event::PushPromise`].
460    pub fn with_settings(role: Role, limits: Limits, settings: &Settings) -> Result<Self> {
461        if !(16384..=0xffffff).contains(&limits.frame_size)
462            || limits.streams == 0
463            || limits.streams > u32::MAX as usize
464        {
465            return Err(protocol("invalid limits"));
466        }
467        settings.validate(role)?;
468        let settings = settings.clone();
469        let mut result = Self {
470            role,
471            limits,
472            streams: Vec::with_capacity(limits.streams),
473            next_id: if role == Role::Client { 1 } else { 2 },
474            last_remote: 0,
475            highest_remote: 0,
476            send_window: 65535,
477            recv_window: 65535,
478            initial_send: 65535,
479            peer_frame: 16384,
480            peer_streams: usize::MAX,
481            preface: role == Role::Client,
482            settings_received: false,
483            settings_pending: VecDeque::new(),
484            local_settings: Settings::new(),
485            remote_settings: Settings::new(),
486            acked_limits: limits,
487            acked_recv_initial: 65535,
488            acked_table: 4096,
489            acked_push: true,
490            push_allowed: true,
491            recv_initial: 65535,
492            decoder: hpack::Decoder::new(4096, limits.header_list),
493            encoder: hpack::Encoder::new(4096),
494            block: Vec::new(),
495            scratch: Vec::new(),
496            continuation: None,
497            disposal: None,
498            pings: 0,
499            reject_unsolicited_ping_ack: false,
500            promise: None,
501            output: Vec::new(),
502            output_pos: 0,
503            draining: false,
504            failed: false,
505            settings_deadline: None,
506        };
507        if role == Role::Client {
508            result.output.extend_from_slice(PREFACE);
509        }
510        result.send_settings(settings)?;
511        Ok(result)
512    }
513    /// Send a SETTINGS frame carrying `settings` to a live connection -
514    /// Node's `session.settings()`. It may be called while earlier frames
515    /// are still unacknowledged; each is acknowledged in turn with
516    /// [`Event::SettingsAck`].
517    ///
518    /// A parameter that loosens what this endpoint enforces - a larger
519    /// MAX_FRAME_SIZE, INITIAL_WINDOW_SIZE, MAX_HEADER_LIST_SIZE or
520    /// MAX_CONCURRENT_STREAMS - applies at once, because the peer may act on
521    /// it before its acknowledgement arrives. One that tightens applies when
522    /// the peer acknowledges the frame (RFC 9113 section 6.5.3), so frames the
523    /// peer sent under the old value are never treated as errors.
524    ///
525    /// Values this endpoint could not honour are refused before anything is
526    /// sent: ENABLE_PUSH above 1 from a client, anything but 0 from a server, and the
527    /// out-of-range values RFC 9113 section 6.5.2 forbids.
528    pub fn settings(&mut self, settings: &Settings) -> Result<()> {
529        if self.failed {
530            return Err(protocol("failed connection"));
531        }
532        settings.validate(self.role)?;
533        self.send_settings(settings.clone())
534    }
535    fn send_settings(&mut self, settings: Settings) -> Result<()> {
536        let payload = settings.encode();
537        if payload.len() > self.peer_frame {
538            return Err(frame_error());
539        }
540        self.frame(4, 0, 0, &payload)?;
541        self.settings_pending.push_back(settings);
542        self.enforce_settings();
543        Ok(())
544    }
545    /// Recompute the enforced limits: the acknowledged ones, loosened by every
546    /// frame still outstanding. The peer may already be acting on any of them.
547    fn enforce_settings(&mut self) {
548        let mut limits = self.acked_limits;
549        let mut recv_initial = self.acked_recv_initial;
550        let mut table = self.acked_table;
551        let mut push = self.acked_push;
552        for settings in &self.settings_pending {
553            for (id, value) in settings.iter() {
554                let value = value as usize;
555                match id {
556                    Settings::MAX_CONCURRENT_STREAMS => limits.streams = limits.streams.max(value),
557                    Settings::INITIAL_WINDOW_SIZE => recv_initial = recv_initial.max(value as i64),
558                    Settings::MAX_FRAME_SIZE => limits.frame_size = limits.frame_size.max(value),
559                    Settings::MAX_HEADER_LIST_SIZE => {
560                        limits.header_list = limits.header_list.max(value)
561                    }
562                    Settings::HEADER_TABLE_SIZE => table = table.max(value),
563                    Settings::ENABLE_PUSH => push |= value != 0,
564                    _ => {}
565                }
566            }
567        }
568        // RFC 9113 section 6.9.2: a change to the initial window adjusts every
569        // open stream's window by the difference.
570        let delta = recv_initial - self.recv_initial;
571        if delta != 0 {
572            for s in &mut self.streams {
573                s.recv_window += delta;
574            }
575            self.recv_initial = recv_initial;
576        }
577        self.decoder.max_list_size = limits.header_list;
578        self.decoder.set_allowed(table);
579        self.push_allowed = push;
580        self.limits = limits;
581    }
582    /// What this endpoint enforces now, including the effect of SETTINGS it
583    /// has sent (see [`settings`](Self::settings)).
584    pub fn limits(&self) -> Limits {
585        self.limits
586    }
587    /// Every parameter this endpoint has sent and the peer has acknowledged -
588    /// Node's `session.localSettings`, less the defaults nobody sent.
589    pub fn local_settings(&self) -> &Settings {
590        &self.local_settings
591    }
592    /// Every parameter the peer has sent - Node's `session.remoteSettings`,
593    /// less the defaults the peer did not send.
594    pub fn remote_settings(&self) -> &Settings {
595        &self.remote_settings
596    }
597    /// SETTINGS frames sent and not yet acknowledged.
598    pub fn pending_settings(&self) -> usize {
599        self.settings_pending.len()
600    }
601    /// Host-supplied deadline for the oldest outstanding SETTINGS frame's
602    /// acknowledgement; no clock is sampled. Each acknowledgement clears it, so
603    /// a host with further frames outstanding sets the next one after each
604    /// [`Event::SettingsAck`].
605    pub fn set_settings_deadline(&mut self, deadline: Option<Instant>) {
606        self.settings_deadline = deadline;
607    }
608    pub fn next_timeout(&self) -> Option<Instant> {
609        if !self.settings_pending.is_empty() && !self.failed {
610            self.settings_deadline
611        } else {
612            None
613        }
614    }
615    pub fn handle_timeout(&mut self, now: Instant) -> Option<Error> {
616        if self.next_timeout().is_some_and(|d| d <= now) {
617            self.failed = true;
618            let mut payload = [0; 8];
619            payload[..4].copy_from_slice(&self.last_remote.to_be_bytes());
620            payload[7] = 4;
621            self.frame(7, 0, 0, &payload).expect("fixed-size GOAWAY");
622            Some(error(
623                "SETTINGS_TIMEOUT",
624                "SETTINGS acknowledgement timeout",
625            ))
626        } else {
627            None
628        }
629    }
630    /// Notify transport loss, then call `poll_failed_stream` until exhausted.
631    pub fn eof(&mut self) {
632        self.failed = true;
633    }
634    /// Exactly one terminal result for each still-open stream after connection failure.
635    /// Fully ended/reset streams have already produced their terminal event.
636    pub fn poll_failed_stream(&mut self) -> Option<u32> {
637        if !self.failed {
638            return None;
639        }
640        let stream = self.streams.iter_mut().find(|s| !s.remote_end)?;
641        stream.local_end = true;
642        stream.remote_end = true;
643        Some(stream.id)
644    }
645    pub fn output(&self) -> &[u8] {
646        &self.output[self.output_pos..]
647    }
648    pub fn consume_output(&mut self, n: usize) -> Result<()> {
649        if n > self.output().len() {
650            return Err(protocol("write acknowledgement exceeds output"));
651        }
652        self.output_pos += n;
653        if self.output_pos == self.output.len() {
654            self.output.clear();
655            self.output_pos = 0;
656        }
657        Ok(())
658    }
659    fn frame(&mut self, kind: u8, flags: u8, id: u32, payload: &[u8]) -> Result<()> {
660        encode_frame(kind, flags, id, payload, &mut self.output)
661    }
662    fn index(&self, id: u32) -> Result<usize> {
663        self.streams
664            .iter()
665            .position(|s| s.id == id)
666            .ok_or(protocol("unknown or idle stream"))
667    }
668    fn active(&self) -> usize {
669        self.streams.iter().filter(|s| !s.closed()).count()
670    }
671    /// A stream id this connection has already opened, refused or finished
672    /// with. Its record may be gone — dropped by `reset`, never created for a
673    /// refused stream, or recycled — while the peer, not yet having seen the
674    /// RST_STREAM or GOAWAY, still sends frames for it. RFC 9113 section 5.1
675    /// requires those to be tolerated; a frame for an id that was never used is
676    /// still a connection error.
677    fn seen(&self, id: u32) -> bool {
678        if id == 0 {
679            false
680        } else if (id % 2 == 1) == (self.role == Role::Client) {
681            id < self.next_id
682        } else {
683            id <= self.highest_remote
684        }
685    }
686    /// `STREAM_CLOSED` for a stream this connection has finished with, and the
687    /// idle/unknown protocol error for one it has never used.
688    fn gone(&self, id: u32) -> Error {
689        if self.seen(id) {
690            error("STREAM_CLOSED", "stream already terminated")
691        } else {
692            protocol("unknown or idle stream")
693        }
694    }
695    /// Give back the connection-level credit a terminated stream still holds.
696    /// RFC 9113 section 5.1: DATA the peer sent before it saw our RST_STREAM
697    /// counts against the connection window either way, so the credit has to go
698    /// back or the window shrinks for the life of the connection. No
699    /// stream-level WINDOW_UPDATE: that stream is over.
700    fn return_credit(&mut self, i: usize) -> Result<()> {
701        let n = std::mem::take(&mut self.streams[i].unreleased);
702        if n == 0 {
703            return Ok(());
704        }
705        self.recv_window += n as i64;
706        self.frame(8, 0, 0, &n.to_be_bytes())
707    }
708    /// Account DATA for a stream that is gone against the connection window and
709    /// return the credit at once: the payload is discarded, so no host release
710    /// will ever arrive for it.
711    fn discard_data(&mut self, flow: i64) -> Result<()> {
712        if flow > self.recv_window {
713            return Err(error("FLOW_CONTROL_ERROR", "receive window exceeded"));
714        }
715        if flow == 0 {
716            return Ok(());
717        }
718        self.frame(8, 0, 0, &(flow as u32).to_be_bytes())
719    }
720    fn add_stream(&mut self, id: u32) -> Result<usize> {
721        if self.active() >= self.limits.streams {
722            return Err(error("REFUSED_STREAM", "stream limit"));
723        }
724        let stream = Stream {
725            id,
726            send_window: self.initial_send,
727            recv_window: self.recv_initial,
728            unreleased: 0,
729            credited: false,
730            local_end: false,
731            remote_end: false,
732            received_head: false,
733            sent_head: false,
734            recv_length: None,
735            received: 0,
736            head_request: false,
737            recv_no_body: false,
738            send_no_body: false,
739            send_length: None,
740            sent: 0,
741        };
742        if let Some(i) = self
743            .streams
744            .iter()
745            .position(|s| s.closed() && s.unreleased == 0)
746        {
747            self.streams[i] = stream;
748            Ok(i)
749        } else {
750            if self.streams.len() >= self.limits.streams {
751                return Err(error(
752                    "REFUSED_STREAM",
753                    "release consumed capacity before opening streams",
754                ));
755            }
756            self.streams.push(stream);
757            Ok(self.streams.len() - 1)
758        }
759    }
760    pub fn open(&mut self, headers: &[Header], end_stream: bool) -> Result<u32> {
761        if self.role != Role::Client || self.draining || self.failed {
762            return Err(protocol("cannot open stream"));
763        }
764        if self.active() >= self.peer_streams {
765            return Err(error("REFUSED_STREAM", "peer stream limit"));
766        }
767        validate_headers(headers, true, false)?;
768        let id = self.next_id;
769        self.next_id = self
770            .next_id
771            .checked_add(2)
772            .filter(|n| *n <= 0x7fffffff)
773            .ok_or(protocol("stream IDs exhausted"))?;
774        self.add_stream(id)?;
775        self.send_headers(id, headers, end_stream)?;
776        Ok(id)
777    }
778    /// Promise a response to the request `headers` on `stream`, a request
779    /// stream the client opened (RFC 9113 section 8.4). Returns the promised
780    /// stream, which then carries the response through
781    /// [`send_headers`](Self::send_headers) and [`send_data`](Self::send_data).
782    /// Refused when the peer disabled push with ENABLE_PUSH = 0.
783    pub fn push(&mut self, stream: u32, headers: &[Header]) -> Result<u32> {
784        if self.role != Role::Server || self.draining || self.failed {
785            return Err(protocol("cannot push"));
786        }
787        if self.remote_settings.get(Settings::ENABLE_PUSH) == Some(0) {
788            return Err(protocol("push disabled by peer"));
789        }
790        let i = self.index(stream).map_err(|_| self.gone(stream))?;
791        if self.streams[i].local_end {
792            return Err(error("STREAM_CLOSED", "local stream closed"));
793        }
794        if self.active() >= self.peer_streams {
795            return Err(error("REFUSED_STREAM", "peer stream limit"));
796        }
797        validate_headers(headers, true, false)?;
798        let id = self.next_id;
799        let next = id
800            .checked_add(2)
801            .filter(|n| *n <= 0x7fffffff)
802            .ok_or(protocol("stream IDs exhausted"))?;
803        self.scratch.clear();
804        self.encoder.encode(headers, &mut self.scratch);
805        let first = self.scratch.len().min(self.peer_frame - 4);
806        let mut payload = id.to_be_bytes().to_vec();
807        payload.extend_from_slice(&self.scratch[..first]);
808        let j = self.add_stream(id)?;
809        self.next_id = next;
810        encode_frame(
811            5,
812            if first == self.scratch.len() { 4 } else { 0 },
813            stream,
814            &payload,
815            &mut self.output,
816        )?;
817        let mut start = first;
818        while start < self.scratch.len() {
819            let end = (start + self.peer_frame).min(self.scratch.len());
820            encode_frame(
821                9,
822                if end == self.scratch.len() { 4 } else { 0 },
823                stream,
824                &self.scratch[start..end],
825                &mut self.output,
826            )?;
827            start = end;
828        }
829        let s = &mut self.streams[j];
830        // The promised request has no body and the client sends nothing on it.
831        s.remote_end = true;
832        s.received_head = true;
833        s.head_request = headers
834            .iter()
835            .any(|h| h.name == ":method" && h.value == b"HEAD");
836        Ok(id)
837    }
838    pub fn send_headers(&mut self, id: u32, headers: &[Header], end_stream: bool) -> Result<()> {
839        if self.failed {
840            return Err(protocol("failed connection"));
841        }
842        let i = self.index(id).map_err(|_| self.gone(id))?;
843        let s = &self.streams[i];
844        if s.local_end {
845            return Err(error("STREAM_CLOSED", "local stream closed"));
846        }
847        validate_headers(headers, self.role == Role::Client, s.sent_head)?;
848        let informational = headers
849            .iter()
850            .find(|h| h.name == ":status")
851            .is_some_and(|h| h.value.starts_with(b"1"));
852        if informational && end_stream {
853            return Err(protocol("informational END_STREAM"));
854        }
855        if s.sent_head && !end_stream {
856            return Err(protocol("trailers must end stream"));
857        }
858        let no_body = self.role == Role::Server
859            && (s.head_request
860                || headers
861                    .iter()
862                    .any(|h| h.name == ":status" && matches!(h.value.as_slice(), b"204" | b"304")));
863        let length = if s.sent_head {
864            s.send_length
865        } else if no_body {
866            None
867        } else {
868            content_length(headers)?
869        };
870        if end_stream && length.is_some_and(|n| n != s.sent) {
871            return Err(protocol("outgoing content-length mismatch"));
872        }
873        self.scratch.clear();
874        self.encoder.encode(headers, &mut self.scratch);
875        let count = self.scratch.len().max(1).div_ceil(self.peer_frame);
876        for n in 0..count {
877            let start = n * self.peer_frame;
878            let end = (start + self.peer_frame).min(self.scratch.len());
879            let flags =
880                if n + 1 == count { 4 } else { 0 } | if n == 0 && end_stream { 1 } else { 0 };
881            encode_frame(
882                if n == 0 { 1 } else { 9 },
883                flags,
884                id,
885                &self.scratch[start..end],
886                &mut self.output,
887            )?;
888        }
889        let s = &mut self.streams[i];
890        s.sent_head |= !informational;
891        s.send_no_body = no_body;
892        s.send_length = length;
893        s.local_end = end_stream;
894        if self.role == Role::Client {
895            s.head_request = headers
896                .iter()
897                .any(|h| h.name == ":method" && h.value == b"HEAD");
898        }
899        Ok(())
900    }
901    /// Returns accepted bytes (zero on flow-control stall). Host retains remainder.
902    pub fn send_data(&mut self, id: u32, bytes: &[u8], end_stream: bool) -> Result<usize> {
903        let i = self.index(id).map_err(|_| self.gone(id))?;
904        let s = &self.streams[i];
905        if self.failed || s.local_end || !s.sent_head {
906            return Err(error("STREAM_CLOSED", "cannot send DATA"));
907        }
908        let n = bytes
909            .len()
910            .min(self.peer_frame)
911            .min(self.send_window.max(0) as usize)
912            .min(s.send_window.max(0) as usize);
913        if n == 0 && !bytes.is_empty() {
914            return Ok(0);
915        }
916        let end = end_stream && n == bytes.len();
917        if s.send_no_body && !bytes.is_empty() {
918            return Err(protocol("DATA on bodyless response"));
919        }
920        if s.send_length.is_some_and(|length| {
921            s.sent + n as u64 > length || (end && s.sent + n as u64 != length)
922        }) {
923            return Err(protocol("outgoing content-length mismatch"));
924        }
925        self.frame(0, u8::from(end), id, &bytes[..n])?;
926        self.send_window -= n as i64;
927        let s = &mut self.streams[i];
928        s.send_window -= n as i64;
929        s.sent += n as u64;
930        s.local_end = end;
931        Ok(n)
932    }
933    /// Return `n` bytes of a stream's receive window to the peer; `n` may not
934    /// exceed that stream's [`unreleased`](Self::unreleased) count.
935    ///
936    /// A terminated stream has already had its remaining credit returned in
937    /// bulk, so a late release for one is a **no-op, not an error** — a host
938    /// that buffers a body and releases when the application consumes it can
939    /// always call this, whatever happened to the stream meanwhile. An id this
940    /// connection has never used is still an error.
941    pub fn release_capacity(&mut self, id: u32, n: u32) -> Result<()> {
942        let Ok(i) = self.index(id) else {
943            return if self.seen(id) {
944                Ok(())
945            } else {
946                Err(protocol("unknown or idle stream"))
947            };
948        };
949        if n == 0 || self.streams[i].credited {
950            return Ok(());
951        }
952        let s = &mut self.streams[i];
953        if n > s.unreleased {
954            return Err(protocol("capacity exceeds received DATA"));
955        }
956        s.unreleased -= n;
957        s.recv_window += n as i64;
958        self.recv_window += n as i64;
959        self.frame(8, 0, 0, &n.to_be_bytes())?;
960        if !self.streams[i].remote_end {
961            self.frame(8, 0, id, &n.to_be_bytes())?;
962        }
963        Ok(())
964    }
965    /// Received DATA bytes for `id` whose flow-control credit the host has not
966    /// yet returned with [`release_capacity`](Self::release_capacity). `None`
967    /// once the stream is gone, its credit having been returned in bulk.
968    /// Padding never appears here: `receive` releases it as it is consumed.
969    pub fn unreleased(&self, id: u32) -> Option<u32> {
970        self.index(id).ok().map(|i| self.streams[i].unreleased)
971    }
972    /// Terminate a stream with RST_STREAM.
973    ///
974    /// The stream's outstanding connection-level credit is returned and its
975    /// table slot is freed at once, so resetting a stream that still holds
976    /// unreleased DATA — the ordinary "one stream errors while its siblings are
977    /// live" case — costs the connection nothing. Frames the peer already had
978    /// in flight for the stream are then ignored rather than failing the
979    /// connection (RFC 9113 section 5.1).
980    ///
981    /// The frame is sent even when the stream has no record left — it may have
982    /// been reset already, or refused before one existed, as after
983    /// [`Event::Unprocessed`]. Encoding what the host asks for is this type's
984    /// job; deciding not to is the host's. Only an id this connection has never
985    /// used is an error.
986    pub fn reset(&mut self, id: u32, code: u32) -> Result<()> {
987        let Ok(i) = self.index(id) else {
988            return if self.seen(id) {
989                self.frame(3, 0, id, &code.to_be_bytes())
990            } else {
991                Err(protocol("unknown or idle stream"))
992            };
993        };
994        self.return_credit(i)?;
995        self.streams.swap_remove(i);
996        self.frame(3, 0, id, &code.to_be_bytes())
997    }
998    /// RFC 9113 leaves a PING acknowledgement that answers nothing this
999    /// endpoint sent without a required reaction, and by default it is only
1000    /// reported as [`Event::Ping`]. With `reject` set it fails the connection
1001    /// with GOAWAY(INTERNAL_ERROR), as Node does: no legitimate peer sends one.
1002    pub fn set_reject_unsolicited_ping_ack(&mut self, reject: bool) {
1003        self.reject_unsolicited_ping_ack = reject;
1004    }
1005    pub fn ping(&mut self, data: [u8; 8]) -> Result<()> {
1006        self.frame(6, 0, 0, &data)?;
1007        self.pings += 1;
1008        Ok(())
1009    }
1010    /// Graceful close: GOAWAY(NO_ERROR) naming the last stream this connection
1011    /// has processed, then drain. A stream the peer opens before it sees the
1012    /// frame does not fail the connection and is not answered: it arrives as
1013    /// [`Event::Unprocessed`] and the host decides.
1014    pub fn shutdown(&mut self) -> Result<()> {
1015        self.goaway(0, self.last_remote, &[])
1016    }
1017    /// GOAWAY with an explicit error code, last stream id and opaque debug
1018    /// data, the form [`shutdown`](Self::shutdown) cannot express. The
1019    /// connection starts draining either way.
1020    pub fn goaway(&mut self, code: u32, last_stream: u32, opaque: &[u8]) -> Result<()> {
1021        if last_stream > 0x7fffffff {
1022            return Err(protocol("invalid last stream"));
1023        }
1024        // The peer would answer a GOAWAY over its own SETTINGS_MAX_FRAME_SIZE
1025        // with FRAME_SIZE_ERROR, so refuse the opaque data here instead.
1026        if 8 + opaque.len() > self.peer_frame {
1027            return Err(frame_error());
1028        }
1029        self.draining = true;
1030        self.scratch.clear();
1031        self.scratch.extend_from_slice(&last_stream.to_be_bytes());
1032        self.scratch.extend_from_slice(&code.to_be_bytes());
1033        self.scratch.extend_from_slice(opaque);
1034        encode_frame(7, 0, 0, &self.scratch, &mut self.output)
1035    }
1036    pub fn is_drained(&self) -> bool {
1037        self.draining && self.active() == 0 && self.output().is_empty()
1038    }
1039    pub fn receive<'a>(&mut self, input: &'a [u8]) -> Result<Step<'a>> {
1040        if self.failed {
1041            return Err(protocol("failed connection"));
1042        }
1043        let result = self.receive_inner(input);
1044        if let Err(e) = &result {
1045            self.failed = true;
1046            let code = match e.code {
1047                "FLOW_CONTROL_ERROR" => 3,
1048                "INTERNAL_ERROR" => 2,
1049                "FRAME_SIZE_ERROR" => 6,
1050                "COMPRESSION_ERROR" => 9,
1051                "ENHANCE_YOUR_CALM" => 11,
1052                _ => 1,
1053            };
1054            let mut payload = [0; 8];
1055            payload[..4].copy_from_slice(&self.last_remote.to_be_bytes());
1056            payload[4..].copy_from_slice(&(code as u32).to_be_bytes());
1057            self.frame(7, 0, 0, &payload)?;
1058        }
1059        result
1060    }
1061    fn receive_inner<'a>(&mut self, input: &'a [u8]) -> Result<Step<'a>> {
1062        if !self.preface {
1063            let n = input.len().min(PREFACE.len());
1064            if input[..n] != PREFACE[..n] {
1065                return Err(protocol("invalid client preface"));
1066            }
1067            if n < PREFACE.len() {
1068                return Ok(Step {
1069                    consumed: 0,
1070                    event: None,
1071                });
1072            }
1073            self.preface = true;
1074            return Ok(Step {
1075                consumed: PREFACE.len(),
1076                event: None,
1077            });
1078        }
1079        let Some(f) = decode_frame(input, self.limits.frame_size)? else {
1080            return Ok(Step {
1081                consumed: 0,
1082                event: None,
1083            });
1084        };
1085        if !self.settings_received && (f.kind != 4 || f.flags & 1 != 0) {
1086            return Err(protocol("first frame must be SETTINGS"));
1087        }
1088        if let Some((id, _, _)) = self.continuation {
1089            if f.kind != 9 || f.stream != id {
1090                return Err(protocol("interleaved header block"));
1091            }
1092        } else if f.kind == 9 {
1093            return Err(protocol("unexpected CONTINUATION"));
1094        }
1095        let mut step = Step {
1096            consumed: 9 + f.payload.len(),
1097            event: None,
1098        };
1099        match f.kind {
1100            0 => {
1101                if f.stream == 0 {
1102                    return Err(protocol("DATA on connection"));
1103                }
1104                let Ok(i) = self.index(f.stream) else {
1105                    // In flight when the stream was refused or reset. RFC 9113
1106                    // section 5.1 tolerates it, and the bytes still count
1107                    // against the connection window, so return the credit.
1108                    if !self.seen(f.stream) {
1109                        return Err(protocol("unknown or idle stream"));
1110                    }
1111                    self.discard_data(f.payload.len() as i64)?;
1112                    return Ok(step);
1113                };
1114                let s = &mut self.streams[i];
1115                if s.remote_end || !s.received_head {
1116                    return Err(protocol("DATA in invalid stream state"));
1117                }
1118                let payload = unpadded(f)?;
1119                let flow = f.payload.len() as i64;
1120                if flow > self.recv_window || flow > s.recv_window {
1121                    return Err(error("FLOW_CONTROL_ERROR", "receive window exceeded"));
1122                }
1123                self.recv_window -= flow;
1124                s.recv_window -= flow;
1125                s.unreleased += flow as u32;
1126                s.received += payload.len() as u64;
1127                let end = f.flags & 1 != 0;
1128                if s.recv_no_body && !payload.is_empty() {
1129                    return Err(protocol("DATA on bodyless response"));
1130                }
1131                if s.recv_length
1132                    .is_some_and(|n| s.received > n || (end && n != s.received))
1133                {
1134                    return Err(protocol("content-length mismatch"));
1135                }
1136                s.remote_end = end;
1137                // Padding is consumed by the protocol, never charged to the application.
1138                let padding = f.payload.len() - payload.len();
1139                if padding > 0 {
1140                    self.release_capacity(f.stream, padding as u32)?;
1141                }
1142                step.event = Some(Event::Data {
1143                    stream: f.stream,
1144                    bytes: payload,
1145                    end_stream: end,
1146                });
1147            }
1148            1 => {
1149                if f.stream == 0 {
1150                    return Err(protocol("HEADERS on connection"));
1151                }
1152                self.disposal = None;
1153                if self.index(f.stream).is_err() {
1154                    if self.role != Role::Server {
1155                        // A response the peer already had in flight when we
1156                        // reset the stream. Its record is gone, so decode the
1157                        // block to keep HPACK in step and ignore it (RFC 9113
1158                        // section 5.1). Only a stream we opened ourselves is
1159                        // unambiguous here; anything else is idle.
1160                        if !self.seen(f.stream) {
1161                            return Err(protocol("invalid new stream"));
1162                        }
1163                        self.disposal = Some(Disposal::Discard);
1164                    } else if f.stream % 2 == 0 || f.stream <= self.highest_remote {
1165                        return Err(protocol("invalid new stream"));
1166                    } else {
1167                        self.highest_remote = f.stream;
1168                        // A stream this connection cannot accept never fails
1169                        // the connection. The two reasons answer differently,
1170                        // and both were measured against Node 26.5.1 with a raw
1171                        // peer rather than assumed:
1172                        //
1173                        // * after a graceful GOAWAY, the stream is above the id
1174                        //   that GOAWAY named and is simply not processed (RFC
1175                        //   9113 section 6.8). Node sends no frame at all, so
1176                        //   neither do we - the host is told and decides.
1177                        // * past the concurrent-stream limit, RFC 9113 section
1178                        //   5.1.2 requires a stream error, and Node answers
1179                        //   RST_STREAM(REFUSED_STREAM).
1180                        self.disposal = if self.draining {
1181                            Some(Disposal::Unprocessed)
1182                        } else {
1183                            match self.add_stream(f.stream) {
1184                                Ok(_) => {
1185                                    // Accepted for processing, so GOAWAY may name it.
1186                                    self.last_remote = f.stream;
1187                                    None
1188                                }
1189                                Err(e) if e.code == "REFUSED_STREAM" => Some(Disposal::Refuse(7)),
1190                                Err(e) => return Err(e),
1191                            }
1192                        };
1193                    }
1194                }
1195                let mut payload = unpadded(f)?;
1196                if f.flags & 32 != 0 {
1197                    if payload.len() < 5 {
1198                        return Err(frame_error());
1199                    }
1200                    if u32be(payload) & 0x7fffffff == f.stream {
1201                        return Err(protocol("stream depends on itself"));
1202                    }
1203                    payload = &payload[5..];
1204                }
1205                self.block.clear();
1206                self.append_block(payload)?;
1207                let end = f.flags & 1 != 0;
1208                if f.flags & 4 != 0 {
1209                    step.event = self.finish_block(f.stream, end)?;
1210                } else {
1211                    self.continuation = Some((f.stream, end, 0));
1212                }
1213            }
1214            9 => {
1215                let (id, end, count) = self.continuation.unwrap();
1216                if count >= self.limits.continuations {
1217                    return Err(error("ENHANCE_YOUR_CALM", "CONTINUATION limit"));
1218                }
1219                self.append_block(f.payload)?;
1220                if f.flags & 4 != 0 {
1221                    self.continuation = None;
1222                    step.event = self.finish_block(id, end)?;
1223                } else {
1224                    self.continuation = Some((id, end, count + 1));
1225                }
1226            }
1227            2 => {
1228                if f.stream == 0 {
1229                    return Err(protocol("PRIORITY on connection"));
1230                }
1231                if f.payload.len() != 5 {
1232                    return Err(frame_error());
1233                }
1234                if u32be(f.payload) & 0x7fffffff == f.stream {
1235                    return Err(protocol("stream depends on itself"));
1236                }
1237            }
1238            3 => {
1239                if f.stream == 0 {
1240                    return Err(protocol("RST_STREAM on connection"));
1241                }
1242                if f.payload.len() != 4 {
1243                    return Err(frame_error());
1244                }
1245                let Ok(i) = self.index(f.stream) else {
1246                    // Crossed resets, or a reset for a stream already refused.
1247                    if !self.seen(f.stream) {
1248                        return Err(protocol("unknown or idle stream"));
1249                    }
1250                    return Ok(step);
1251                };
1252                self.return_credit(i)?;
1253                let s = &mut self.streams[i];
1254                s.credited = true;
1255                s.remote_end = true;
1256                s.local_end = true;
1257                step.event = Some(Event::Reset {
1258                    stream: f.stream,
1259                    code: u32be(f.payload),
1260                });
1261            }
1262            4 => {
1263                if f.stream != 0 {
1264                    return Err(protocol("SETTINGS on stream"));
1265                }
1266                if f.flags & 1 != 0 {
1267                    if !f.payload.is_empty() {
1268                        return Err(frame_error());
1269                    }
1270                    let Some(acked) = self.settings_pending.pop_front() else {
1271                        return Err(protocol("unsolicited SETTINGS ack"));
1272                    };
1273                    for (id, value) in acked.iter() {
1274                        match id {
1275                            Settings::MAX_CONCURRENT_STREAMS => {
1276                                self.acked_limits.streams = value as usize
1277                            }
1278                            Settings::INITIAL_WINDOW_SIZE => self.acked_recv_initial = value as i64,
1279                            Settings::MAX_FRAME_SIZE => {
1280                                self.acked_limits.frame_size = value as usize
1281                            }
1282                            Settings::MAX_HEADER_LIST_SIZE => {
1283                                self.acked_limits.header_list = value as usize
1284                            }
1285                            Settings::HEADER_TABLE_SIZE => self.acked_table = value as usize,
1286                            Settings::ENABLE_PUSH => self.acked_push = value != 0,
1287                            _ => {}
1288                        }
1289                    }
1290                    self.local_settings.merge(acked.iter());
1291                    self.enforce_settings();
1292                    // The deadline was for this frame; the host arms the next.
1293                    self.settings_deadline = None;
1294                    step.event = Some(Event::SettingsAck(acked));
1295                } else {
1296                    if f.payload.len() % 6 != 0 {
1297                        return Err(frame_error());
1298                    }
1299                    for setting in f.payload.as_chunks::<6>().0 {
1300                        let id = u16::from_be_bytes(setting[..2].try_into().unwrap());
1301                        let value = u32be(&setting[2..]);
1302                        match id {
1303                            1 => self.encoder.set_table_size((value as usize).min(4096)),
1304                            2 => {
1305                                if match self.role {
1306                                    Role::Server => value > 1,
1307                                    Role::Client => value != 0,
1308                                } {
1309                                    return Err(protocol("invalid ENABLE_PUSH"));
1310                                }
1311                            }
1312                            3 => self.peer_streams = value as usize,
1313                            4 => {
1314                                if value > 0x7fffffff {
1315                                    return Err(error(
1316                                        "FLOW_CONTROL_ERROR",
1317                                        "invalid initial window",
1318                                    ));
1319                                }
1320                                let delta = value as i64 - self.initial_send;
1321                                for s in &mut self.streams {
1322                                    if s.send_window + delta > 0x7fffffff {
1323                                        return Err(error("FLOW_CONTROL_ERROR", "window overflow"));
1324                                    }
1325                                    s.send_window += delta;
1326                                }
1327                                self.initial_send = value as i64;
1328                            }
1329                            5 => {
1330                                if !(16384..=0xffffff).contains(&value) {
1331                                    return Err(protocol("invalid MAX_FRAME_SIZE"));
1332                                }
1333                                self.peer_frame = value as usize;
1334                            }
1335                            _ => {}
1336                        }
1337                    }
1338                    self.settings_received = true;
1339                    let settings = SettingsFrame { payload: f.payload };
1340                    self.remote_settings.merge(settings.iter());
1341                    self.frame(4, 1, 0, &[])?;
1342                    step.event = Some(Event::Settings(settings));
1343                }
1344            }
1345            5 => {
1346                if self.role != Role::Client || !self.push_allowed {
1347                    return Err(protocol("server push disabled"));
1348                }
1349                if f.stream == 0 {
1350                    return Err(protocol("PUSH_PROMISE on connection"));
1351                }
1352                let payload = unpadded(f)?;
1353                if payload.len() < 4 {
1354                    return Err(frame_error());
1355                }
1356                let promised = u32be(payload) & 0x7fffffff;
1357                if promised == 0 || !promised.is_multiple_of(2) || promised <= self.highest_remote {
1358                    return Err(protocol("invalid promised stream"));
1359                }
1360                // A promise rides on a stream we opened. One we have already
1361                // reset may still have a promise in flight: decode it to keep
1362                // HPACK in step and cancel the promised stream.
1363                let discard = match self.index(f.stream) {
1364                    Ok(i) if self.streams[i].remote_end => {
1365                        return Err(error("STREAM_CLOSED", "PUSH_PROMISE after END_STREAM"));
1366                    }
1367                    Ok(_) => false,
1368                    Err(_) if self.seen(f.stream) => true,
1369                    Err(_) => return Err(protocol("PUSH_PROMISE on idle stream")),
1370                };
1371                self.highest_remote = promised;
1372                self.disposal = None;
1373                self.block.clear();
1374                self.append_block(&payload[4..])?;
1375                self.promise = Some((promised, discard));
1376                if f.flags & 4 != 0 {
1377                    step.event = self.finish_block(f.stream, false)?;
1378                } else {
1379                    self.continuation = Some((f.stream, false, 0));
1380                }
1381            }
1382            6 => {
1383                if f.stream != 0 {
1384                    return Err(protocol("PING on stream"));
1385                }
1386                if f.payload.len() != 8 {
1387                    return Err(frame_error());
1388                }
1389                let data = f.payload.try_into().unwrap();
1390                let ack = f.flags & 1 != 0;
1391                if !ack {
1392                    self.frame(6, 1, 0, f.payload)?;
1393                } else if self.pings > 0 {
1394                    self.pings -= 1;
1395                } else if self.reject_unsolicited_ping_ack {
1396                    // Node answers GOAWAY(INTERNAL_ERROR) and drops the
1397                    // connection (measured against a raw peer).
1398                    return Err(error("INTERNAL_ERROR", "unsolicited PING acknowledgement"));
1399                }
1400                step.event = Some(Event::Ping { ack, data });
1401            }
1402            7 => {
1403                if f.stream != 0 {
1404                    return Err(protocol("GOAWAY on stream"));
1405                }
1406                if f.payload.len() < 8 {
1407                    return Err(frame_error());
1408                }
1409                self.draining = true;
1410                step.event = Some(Event::Goaway {
1411                    last_stream: u32be(f.payload) & 0x7fffffff,
1412                    code: u32be(&f.payload[4..]),
1413                    debug: Some(&f.payload[8..]).filter(|d| !d.is_empty()),
1414                });
1415            }
1416            8 => {
1417                if f.payload.len() != 4 {
1418                    return Err(frame_error());
1419                }
1420                if f.stream != 0 && self.index(f.stream).is_err() {
1421                    // Credit for a stream that is already gone. RFC 9113
1422                    // section 6.9 requires this to be tolerated.
1423                    if !self.seen(f.stream) {
1424                        return Err(protocol("unknown or idle stream"));
1425                    }
1426                    return Ok(step);
1427                }
1428                let n = (u32be(f.payload) & 0x7fffffff) as i64;
1429                if n == 0 {
1430                    if f.stream != 0 {
1431                        self.reset(f.stream, 1)?;
1432                        step.event = Some(Event::Reset {
1433                            stream: f.stream,
1434                            code: 1,
1435                        });
1436                        return Ok(step);
1437                    }
1438                    return Err(protocol("zero WINDOW_UPDATE"));
1439                }
1440                let window = if f.stream == 0 {
1441                    &mut self.send_window
1442                } else {
1443                    let i = self.index(f.stream)?;
1444                    &mut self.streams[i].send_window
1445                };
1446                if *window + n > 0x7fffffff {
1447                    if f.stream != 0 {
1448                        self.reset(f.stream, 3)?;
1449                        step.event = Some(Event::Reset {
1450                            stream: f.stream,
1451                            code: 3,
1452                        });
1453                        return Ok(step);
1454                    }
1455                    return Err(error("FLOW_CONTROL_ERROR", "window overflow"));
1456                }
1457                *window += n;
1458                step.event = Some(Event::WindowUpdate { stream: f.stream });
1459            }
1460            _ => {}
1461        }
1462        Ok(step)
1463    }
1464    fn append_block(&mut self, bytes: &[u8]) -> Result<()> {
1465        if bytes.len() > self.limits.header_block.saturating_sub(self.block.len()) {
1466            return Err(error("ENHANCE_YOUR_CALM", "compressed header block limit"));
1467        }
1468        self.block.extend_from_slice(bytes);
1469        Ok(())
1470    }
1471    /// Complete a header block: the stream's own, or one being thrown away.
1472    fn finish_block(&mut self, id: u32, end: bool) -> Result<Option<Event<'static>>> {
1473        if let Some((promised, discard)) = self.promise.take() {
1474            return self.finish_promise(id, promised, discard);
1475        }
1476        let Some(disposal) = self.disposal.take() else {
1477            return self.finish_headers(id, end).map(Some);
1478        };
1479        // Decode before discarding: HPACK state belongs to the connection, not
1480        // the stream, and a skipped block desynchronises every block after it.
1481        let mut headers = Vec::new();
1482        self.decoder.decode(&self.block, &mut headers)?;
1483        match disposal {
1484            Disposal::Refuse(code) => {
1485                self.frame(3, 0, id, &code.to_be_bytes())?;
1486                Ok(Some(Event::Reset { stream: id, code }))
1487            }
1488            Disposal::Unprocessed => Ok(Some(Event::Unprocessed { stream: id })),
1489            Disposal::Discard => Ok(None),
1490        }
1491    }
1492    /// Complete a PUSH_PROMISE: reserve the promised stream, or decline it.
1493    fn finish_promise(
1494        &mut self,
1495        id: u32,
1496        promised: u32,
1497        discard: bool,
1498    ) -> Result<Option<Event<'static>>> {
1499        let mut headers = Vec::new();
1500        self.decoder.decode(&self.block, &mut headers)?;
1501        if discard {
1502            self.frame(3, 0, promised, &8u32.to_be_bytes())?;
1503            return Ok(None);
1504        }
1505        validate_headers(&headers, true, false)?;
1506        match self.add_stream(promised) {
1507            Ok(i) => {
1508                let s = &mut self.streams[i];
1509                // The client never sends on a pushed stream.
1510                s.local_end = true;
1511                s.head_request = headers
1512                    .iter()
1513                    .any(|h| h.name == ":method" && h.value == b"HEAD");
1514                self.last_remote = promised;
1515                Ok(Some(Event::PushPromise {
1516                    stream: id,
1517                    promised,
1518                    headers,
1519                }))
1520            }
1521            Err(e) if e.code == "REFUSED_STREAM" => {
1522                self.frame(3, 0, promised, &7u32.to_be_bytes())?;
1523                Ok(Some(Event::Reset {
1524                    stream: promised,
1525                    code: 7,
1526                }))
1527            }
1528            Err(e) => Err(e),
1529        }
1530    }
1531    fn finish_headers(&mut self, id: u32, end: bool) -> Result<Event<'static>> {
1532        let mut headers = Vec::new();
1533        self.decoder.decode(&self.block, &mut headers)?;
1534        let i = self.index(id)?;
1535        let s = &mut self.streams[i];
1536        if s.remote_end {
1537            return Err(error("STREAM_CLOSED", "headers after END_STREAM"));
1538        }
1539        validate_headers(&headers, self.role == Role::Server, s.received_head)?;
1540        let informational = headers
1541            .iter()
1542            .find(|h| h.name == ":status")
1543            .is_some_and(|h| h.value.starts_with(b"1"));
1544        if informational && end {
1545            return Err(protocol("informational END_STREAM"));
1546        }
1547        if s.received_head && !end {
1548            return Err(protocol("trailers without END_STREAM"));
1549        }
1550        let kind = if informational {
1551            HeadersKind::Informational
1552        } else if s.received_head {
1553            HeadersKind::Trailers
1554        } else {
1555            HeadersKind::Head
1556        };
1557        if !s.received_head && !informational {
1558            s.recv_no_body = self.role == Role::Client
1559                && (s.head_request
1560                    || headers.iter().any(|h| {
1561                        h.name == ":status" && matches!(h.value.as_slice(), b"204" | b"304")
1562                    }));
1563            s.recv_length = if s.recv_no_body {
1564                None
1565            } else {
1566                content_length(&headers)?
1567            };
1568            if self.role == Role::Server {
1569                s.head_request = headers
1570                    .iter()
1571                    .any(|h| h.name == ":method" && h.value == b"HEAD");
1572            }
1573            s.received_head = true;
1574        }
1575        if end && s.recv_length.is_some_and(|n| n != s.received) {
1576            return Err(protocol("content-length mismatch"));
1577        }
1578        s.remote_end = end;
1579        Ok(Event::Headers {
1580            stream: id,
1581            headers,
1582            end_stream: end,
1583            kind,
1584        })
1585    }
1586}
1587fn unpadded(f: Frame<'_>) -> Result<&[u8]> {
1588    if f.flags & 8 == 0 {
1589        return Ok(f.payload);
1590    }
1591    let pad = *f.payload.first().ok_or_else(frame_error)? as usize;
1592    if pad >= f.payload.len() {
1593        return Err(protocol("invalid padding"));
1594    }
1595    Ok(&f.payload[1..f.payload.len() - pad])
1596}
1597fn content_length(headers: &[Header]) -> Result<Option<u64>> {
1598    let mut found = None;
1599    for h in headers {
1600        if h.name == "content-length" {
1601            if found.is_some() || h.value.is_empty() || !h.value.iter().all(u8::is_ascii_digit) {
1602                return Err(protocol("invalid content-length"));
1603            }
1604            found = Some(
1605                h.value
1606                    .iter()
1607                    .try_fold(0u64, |n, b| {
1608                        n.checked_mul(10)?.checked_add((b - b'0') as u64)
1609                    })
1610                    .ok_or(protocol("content-length overflow"))?,
1611            );
1612        }
1613    }
1614    Ok(found)
1615}
1616fn validate_headers(headers: &[Header], request: bool, trailers: bool) -> Result<()> {
1617    let mut regular = false;
1618    let mut pseudo = [false; 5];
1619    for h in headers {
1620        if h.name.is_empty()
1621            || h.name.bytes().any(|b| b.is_ascii_uppercase())
1622            || h.value.iter().any(|b| matches!(b, 0 | 10 | 13))
1623            || h.value.first().is_some_and(|b| matches!(b, b' ' | b'\t'))
1624            || h.value.last().is_some_and(|b| matches!(b, b' ' | b'\t'))
1625        {
1626            return Err(protocol("invalid header field"));
1627        }
1628        if h.name.starts_with(':') {
1629            if regular || trailers {
1630                return Err(protocol("pseudo-header ordering"));
1631            }
1632            let index = match h.name.as_str() {
1633                ":method" if request => 0,
1634                ":scheme" if request => 1,
1635                ":path" if request => 2,
1636                ":authority" if request => 3,
1637                ":status" if !request => 4,
1638                _ => return Err(protocol("invalid pseudo-header")),
1639            };
1640            if pseudo[index] {
1641                return Err(protocol("duplicate pseudo-header"));
1642            }
1643            pseudo[index] = true;
1644        } else {
1645            regular = true;
1646            if !crate::http1::valid_token(h.name.as_bytes()) {
1647                return Err(protocol("invalid header name"));
1648            }
1649            if matches!(
1650                h.name.as_str(),
1651                "connection" | "proxy-connection" | "keep-alive" | "transfer-encoding" | "upgrade"
1652            ) || h.name == "te" && h.value != b"trailers"
1653            {
1654                return Err(protocol("connection-specific field"));
1655            }
1656        }
1657    }
1658    if !trailers {
1659        if request {
1660            let connect = headers
1661                .iter()
1662                .any(|h| h.name == ":method" && h.value == b"CONNECT");
1663            if !pseudo[0]
1664                || if connect {
1665                    !pseudo[3] || pseudo[1] || pseudo[2]
1666                } else {
1667                    !pseudo[1]
1668                        || !pseudo[2]
1669                        || headers
1670                            .iter()
1671                            .any(|h| h.name == ":path" && h.value.is_empty())
1672                }
1673            {
1674                return Err(protocol("missing request pseudo-header"));
1675            }
1676        } else {
1677            let Some(status) = headers.iter().find(|h| h.name == ":status") else {
1678                return Err(protocol("missing status"));
1679            };
1680            if status.value.len() != 3
1681                || !status.value.iter().all(u8::is_ascii_digit)
1682                || status.value.as_slice() < b"100".as_slice()
1683                || status.value == b"101"
1684            {
1685                return Err(protocol("invalid status"));
1686            }
1687        }
1688    }
1689    if trailers && headers.iter().any(|h| h.name == "content-length") {
1690        return Err(protocol("content-length in trailers"));
1691    }
1692    content_length(headers)?;
1693    Ok(())
1694}