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