Skip to main content

strata_web_api/
http2.rs

1//! Pure-Rust HTTP/2 Framing, HPACK Header Compression, and Client Protocol Engine (RFC 7540, RFC 7541, RFC 9113).
2
3use std::io::{Read, Write};
4use std::sync::OnceLock;
5
6use crate::fetch::{decompress_body, FetchError, Headers, ParsedUrl, RequestInit, Response};
7use crate::huffman_table::HUFFMAN_CODE_TABLE;
8
9/// HTTP/2 Connection Preface sent by the client upon connection establishment.
10pub const HTTP2_PREFACE: &[u8; 24] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
11
12/// Frame header length in octets (24-bit length + 8-bit type + 8-bit flags + 31-bit stream ID).
13pub const FRAME_HEADER_LEN: usize = 9;
14
15// Frame Types (RFC 7540 Section 11.2)
16pub const FRAME_DATA: u8 = 0x0;
17pub const FRAME_HEADERS: u8 = 0x1;
18pub const FRAME_PRIORITY: u8 = 0x2;
19pub const FRAME_RST_STREAM: u8 = 0x3;
20pub const FRAME_SETTINGS: u8 = 0x4;
21pub const FRAME_PUSH_PROMISE: u8 = 0x5;
22pub const FRAME_PING: u8 = 0x6;
23pub const FRAME_GOAWAY: u8 = 0x7;
24pub const FRAME_WINDOW_UPDATE: u8 = 0x8;
25pub const FRAME_CONTINUATION: u8 = 0x9;
26
27// Frame Flags
28pub const FLAG_END_STREAM: u8 = 0x1;
29pub const FLAG_ACK: u8 = 0x1;
30pub const FLAG_END_HEADERS: u8 = 0x4;
31pub const FLAG_PADDED: u8 = 0x8;
32pub const FLAG_PRIORITY: u8 = 0x20;
33
34/// Default initial maximum frame size per RFC 7540 Section 6.5.2 (16,384 octets / 2^14).
35pub const DEFAULT_MAX_FRAME_SIZE: u32 = 16_384;
36
37/// Absolute maximum allowable frame size per RFC 7540 Section 4.1 (16,777,215 octets / 2^24 - 1).
38pub const ABSOLUTE_MAX_FRAME_SIZE: u32 = 16_777_215;
39
40// RFC 7540 Section 6.5.2 Settings Parameters
41pub const SETTINGS_HEADER_TABLE_SIZE: u16 = 0x1;
42pub const SETTINGS_ENABLE_PUSH: u16 = 0x2;
43pub const SETTINGS_MAX_CONCURRENT_STREAMS: u16 = 0x3;
44pub const SETTINGS_INITIAL_WINDOW_SIZE: u16 = 0x4;
45pub const SETTINGS_MAX_FRAME_SIZE: u16 = 0x5;
46pub const SETTINGS_MAX_HEADER_LIST_SIZE: u16 = 0x6;
47
48/// RFC 7540 Section 7 HTTP/2 Error Codes.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50#[repr(u32)]
51pub enum Http2ErrorCode {
52    NoError = 0x0,
53    ProtocolError = 0x1,
54    InternalError = 0x2,
55    FlowControlError = 0x3,
56    SettingsTimeout = 0x4,
57    StreamClosed = 0x5,
58    FrameSizeError = 0x6,
59    RefusedStream = 0x7,
60    Cancel = 0x8,
61    CompressionError = 0x9,
62    ConnectError = 0xa,
63    EnhanceYourCalm = 0xb,
64    InadequateSecurity = 0xc,
65    Http11Required = 0xd,
66}
67
68/// Active HTTP/2 connection settings negotiated across the lifetime of the connection.
69#[derive(Debug, Clone)]
70pub struct Http2ConnectionSettings {
71    pub header_table_size: u32,
72    pub enable_push: bool,
73    pub max_concurrent_streams: Option<u32>,
74    pub initial_window_size: u32,
75    pub max_frame_size: u32,
76    pub max_header_list_size: Option<u32>,
77}
78
79impl Default for Http2ConnectionSettings {
80    fn default() -> Self {
81        Self {
82            header_table_size: 4096,
83            enable_push: false,
84            max_concurrent_streams: None,
85            initial_window_size: 65535,
86            max_frame_size: DEFAULT_MAX_FRAME_SIZE,
87            max_header_list_size: None,
88        }
89    }
90}
91
92impl Http2ConnectionSettings {
93    /// Applies received SETTINGS payload key-value pairs (RFC 7540 Section 6.5.2).
94    pub fn apply_settings(&mut self, payload: &[u8]) -> Result<(), FetchError> {
95        if !payload.len().is_multiple_of(6) {
96            return Err(FetchError::NetworkError(
97                "FRAME_SIZE_ERROR: SETTINGS frame payload length must be a multiple of 6".into(),
98            ));
99        }
100
101        let mut cursor = 0;
102        while cursor < payload.len() {
103            let id = u16::from_be_bytes([payload[cursor], payload[cursor + 1]]);
104            let val = u32::from_be_bytes([
105                payload[cursor + 2],
106                payload[cursor + 3],
107                payload[cursor + 4],
108                payload[cursor + 5],
109            ]);
110            cursor += 6;
111
112            match id {
113                SETTINGS_HEADER_TABLE_SIZE => {
114                    self.header_table_size = val;
115                }
116                SETTINGS_ENABLE_PUSH => {
117                    if val > 1 {
118                        return Err(FetchError::NetworkError(
119                            "PROTOCOL_ERROR: SETTINGS_ENABLE_PUSH must be 0 or 1".into(),
120                        ));
121                    }
122                    self.enable_push = val == 1;
123                }
124                SETTINGS_MAX_CONCURRENT_STREAMS => {
125                    self.max_concurrent_streams = Some(val);
126                }
127                SETTINGS_INITIAL_WINDOW_SIZE => {
128                    if val > 0x7FFF_FFFF {
129                        return Err(FetchError::NetworkError(
130                            "FLOW_CONTROL_ERROR: SETTINGS_INITIAL_WINDOW_SIZE exceeds 2^31-1"
131                                .into(),
132                        ));
133                    }
134                    self.initial_window_size = val;
135                }
136                SETTINGS_MAX_FRAME_SIZE => {
137                    if !(DEFAULT_MAX_FRAME_SIZE..=ABSOLUTE_MAX_FRAME_SIZE).contains(&val) {
138                        return Err(FetchError::NetworkError(format!(
139                            "PROTOCOL_ERROR: Invalid SETTINGS_MAX_FRAME_SIZE {val} (must be between 16384 and 16777215)"
140                        )));
141                    }
142                    self.max_frame_size = val;
143                }
144                SETTINGS_MAX_HEADER_LIST_SIZE => {
145                    self.max_header_list_size = Some(val);
146                }
147                _ => {
148                    // Unknown settings parameters MUST be ignored per RFC 7540 Section 6.5.2
149                }
150            }
151        }
152        Ok(())
153    }
154}
155
156/// An individual HTTP/2 protocol frame.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Http2Frame {
159    pub length: u32,
160    pub frame_type: u8,
161    pub flags: u8,
162    pub stream_id: u32,
163    pub payload: Vec<u8>,
164}
165
166impl Http2Frame {
167    /// Constructs a new `Http2Frame`.
168    pub fn new(frame_type: u8, flags: u8, stream_id: u32, payload: Vec<u8>) -> Self {
169        Self {
170            length: payload.len() as u32,
171            frame_type,
172            flags,
173            stream_id,
174            payload,
175        }
176    }
177
178    /// Serializes the frame into its wire representation.
179    pub fn encode(&self) -> Vec<u8> {
180        let mut out = Vec::with_capacity(FRAME_HEADER_LEN + self.payload.len());
181        let len = self.payload.len() as u32;
182
183        out.push(((len >> 16) & 0xFF) as u8);
184        out.push(((len >> 8) & 0xFF) as u8);
185        out.push((len & 0xFF) as u8);
186
187        out.push(self.frame_type);
188        out.push(self.flags);
189
190        let stream_be = (self.stream_id & 0x7FFF_FFFF).to_be_bytes();
191        out.extend_from_slice(&stream_be);
192
193        out.extend_from_slice(&self.payload);
194        out
195    }
196
197    /// Validates frame invariants according to RFC 7540 Section 6.
198    pub fn validate_invariants(&self) -> Result<(), FetchError> {
199        match self.frame_type {
200            FRAME_SETTINGS => {
201                if self.stream_id != 0 {
202                    return Err(FetchError::NetworkError(
203                        "PROTOCOL_ERROR: SETTINGS frame stream ID must be 0".into(),
204                    ));
205                }
206                if (self.flags & FLAG_ACK) != 0 && self.length != 0 {
207                    return Err(FetchError::NetworkError(
208                        "FRAME_SIZE_ERROR: ACK SETTINGS frame must have empty payload".into(),
209                    ));
210                }
211                if !self.length.is_multiple_of(6) {
212                    return Err(FetchError::NetworkError(
213                        "FRAME_SIZE_ERROR: SETTINGS frame payload length must be a multiple of 6"
214                            .into(),
215                    ));
216                }
217            }
218            FRAME_PING => {
219                if self.stream_id != 0 {
220                    return Err(FetchError::NetworkError(
221                        "PROTOCOL_ERROR: PING frame stream ID must be 0".into(),
222                    ));
223                }
224                if self.length != 8 {
225                    return Err(FetchError::NetworkError(format!(
226                        "FRAME_SIZE_ERROR: PING frame payload length must be exactly 8, got {}",
227                        self.length
228                    )));
229                }
230            }
231            FRAME_RST_STREAM => {
232                if self.stream_id == 0 {
233                    return Err(FetchError::NetworkError(
234                        "PROTOCOL_ERROR: RST_STREAM frame stream ID cannot be 0".into(),
235                    ));
236                }
237                if self.length != 4 {
238                    return Err(FetchError::NetworkError(format!(
239                        "FRAME_SIZE_ERROR: RST_STREAM frame payload length must be exactly 4, got {}",
240                        self.length
241                    )));
242                }
243            }
244            FRAME_WINDOW_UPDATE => {
245                if self.length != 4 {
246                    return Err(FetchError::NetworkError(format!(
247                        "FRAME_SIZE_ERROR: WINDOW_UPDATE frame payload length must be exactly 4, got {}",
248                        self.length
249                    )));
250                }
251                if self.payload.len() == 4 {
252                    let increment = u32::from_be_bytes([
253                        self.payload[0] & 0x7F,
254                        self.payload[1],
255                        self.payload[2],
256                        self.payload[3],
257                    ]);
258                    if increment == 0 {
259                        return Err(FetchError::NetworkError(
260                            "PROTOCOL_ERROR: WINDOW_UPDATE increment must be non-zero".into(),
261                        ));
262                    }
263                }
264            }
265            FRAME_DATA | FRAME_HEADERS if self.stream_id == 0 => {
266                return Err(FetchError::NetworkError(
267                    "PROTOCOL_ERROR: DATA and HEADERS frames cannot have stream ID 0".into(),
268                ));
269            }
270            _ => {}
271        }
272        Ok(())
273    }
274
275    /// Reads an individual frame from a synchronous byte stream, enforcing the active max frame size.
276    pub fn read_from_bounded<R: Read>(
277        reader: &mut R,
278        max_frame_size: u32,
279    ) -> Result<Self, FetchError> {
280        let mut header = [0u8; FRAME_HEADER_LEN];
281        reader.read_exact(&mut header).map_err(|e| {
282            FetchError::NetworkError(format!("Failed to read HTTP/2 frame header: {e}"))
283        })?;
284
285        let length = ((header[0] as u32) << 16) | ((header[1] as u32) << 8) | (header[2] as u32);
286        let frame_type = header[3];
287        let flags = header[4];
288        let stream_id = u32::from_be_bytes([header[5] & 0x7F, header[6], header[7], header[8]]);
289
290        if length > max_frame_size {
291            return Err(FetchError::NetworkError(format!(
292                "FRAME_SIZE_ERROR: Frame length {length} exceeds maximum permitted frame size {max_frame_size}"
293            )));
294        }
295
296        let mut payload = vec![0u8; length as usize];
297        if length > 0 {
298            reader.read_exact(&mut payload).map_err(|e| {
299                FetchError::NetworkError(format!(
300                    "Failed to read HTTP/2 frame payload ({length} bytes): {e}"
301                ))
302            })?;
303        }
304
305        let frame = Self {
306            length,
307            frame_type,
308            flags,
309            stream_id,
310            payload,
311        };
312
313        frame.validate_invariants()?;
314        Ok(frame)
315    }
316
317    /// Reads an individual frame from a synchronous byte stream using the default RFC 7540 initial limit (16,384 bytes).
318    pub fn read_from<R: Read>(reader: &mut R) -> Result<Self, FetchError> {
319        Self::read_from_bounded(reader, DEFAULT_MAX_FRAME_SIZE)
320    }
321}
322
323// RFC 7541 Appendix A — Static Table (Indices 1..=61)
324pub const STATIC_TABLE: &[(&str, &str)] = &[
325    ("", ""), // 0 is unused in 1-based indexing
326    (":authority", ""),
327    (":method", "GET"),
328    (":method", "POST"),
329    (":path", "/"),
330    (":path", "/index.html"),
331    (":scheme", "http"),
332    (":scheme", "https"),
333    (":status", "200"),
334    (":status", "204"),
335    (":status", "206"),
336    (":status", "304"),
337    (":status", "400"),
338    (":status", "404"),
339    (":status", "500"),
340    ("accept-charset", ""),
341    ("accept-encoding", "gzip, deflate"),
342    ("accept-language", ""),
343    ("accept-ranges", ""),
344    ("accept", ""),
345    ("access-control-allow-origin", ""),
346    ("age", ""),
347    ("allow", ""),
348    ("authorization", ""),
349    ("cache-control", ""),
350    ("content-disposition", ""),
351    ("content-encoding", ""),
352    ("content-language", ""),
353    ("content-length", ""),
354    ("content-location", ""),
355    ("content-range", ""),
356    ("content-type", ""),
357    ("cookie", ""),
358    ("date", ""),
359    ("etag", ""),
360    ("expect", ""),
361    ("expires", ""),
362    ("from", ""),
363    ("host", ""),
364    ("if-match", ""),
365    ("if-modified-since", ""),
366    ("if-none-match", ""),
367    ("if-range", ""),
368    ("if-unmodified-since", ""),
369    ("last-modified", ""),
370    ("link", ""),
371    ("location", ""),
372    ("max-forwards", ""),
373    ("proxy-authenticate", ""),
374    ("proxy-authorization", ""),
375    ("range", ""),
376    ("referer", ""),
377    ("refresh", ""),
378    ("retry-after", ""),
379    ("server", ""),
380    ("set-cookie", ""),
381    ("strict-transport-security", ""),
382    ("transfer-encoding", ""),
383    ("user-agent", ""),
384    ("vary", ""),
385    ("via", ""),
386    ("www-authenticate", ""),
387];
388
389// RFC 7541 Appendix B: Huffman Decoding Prefix Tree Node
390#[derive(Clone, Copy, Default)]
391struct HuffmanNode {
392    left: u16,   // Index of left child (bit 0); 0 means unallocated
393    right: u16,  // Index of right child (bit 1); 0 means unallocated
394    symbol: u16, // Decoded symbol (0..=255 for octet, 256 for EOS, 0xFFFF for branch)
395}
396
397fn get_huffman_tree() -> &'static [HuffmanNode] {
398    static TREE: OnceLock<Vec<HuffmanNode>> = OnceLock::new();
399    TREE.get_or_init(|| {
400        let mut nodes = Vec::with_capacity(600);
401        // Root node at index 0
402        nodes.push(HuffmanNode {
403            left: 0,
404            right: 0,
405            symbol: 0xFFFF,
406        });
407
408        for (sym, &(code, len)) in HUFFMAN_CODE_TABLE.iter().enumerate() {
409            let mut curr = 0;
410            for i in (0..len).rev() {
411                let bit = ((code >> i) & 1) != 0;
412                let next_idx = if !bit {
413                    let left = nodes[curr].left;
414                    if left == 0 {
415                        let new_idx = nodes.len() as u16;
416                        nodes.push(HuffmanNode {
417                            left: 0,
418                            right: 0,
419                            symbol: 0xFFFF,
420                        });
421                        nodes[curr].left = new_idx;
422                        new_idx
423                    } else {
424                        left
425                    }
426                } else {
427                    let right = nodes[curr].right;
428                    if right == 0 {
429                        let new_idx = nodes.len() as u16;
430                        nodes.push(HuffmanNode {
431                            left: 0,
432                            right: 0,
433                            symbol: 0xFFFF,
434                        });
435                        nodes[curr].right = new_idx;
436                        new_idx
437                    } else {
438                        right
439                    }
440                };
441                curr = next_idx as usize;
442            }
443            nodes[curr].symbol = sym as u16;
444        }
445
446        nodes
447    })
448}
449
450/// Decodes an HPACK Huffman-encoded octet slice into a UTF-8 string per RFC 7541 Section 5.2.
451pub fn decode_huffman_string(raw: &[u8]) -> Result<String, FetchError> {
452    let tree = get_huffman_tree();
453    let mut out = Vec::with_capacity(raw.len());
454    let mut curr = 0;
455
456    for &b in raw {
457        for bit_idx in (0..8).rev() {
458            let bit = ((b >> bit_idx) & 1) != 0;
459            let next = if !bit {
460                tree[curr].left as usize
461            } else {
462                tree[curr].right as usize
463            };
464
465            if next == 0 {
466                return Err(FetchError::NetworkError(
467                    "Invalid HPACK Huffman bit code".into(),
468                ));
469            }
470
471            let sym = tree[next].symbol;
472            if sym != 0xFFFF {
473                if sym == 256 {
474                    return Err(FetchError::NetworkError(
475                        "EOS symbol found in HPACK string".into(),
476                    ));
477                }
478                out.push(sym as u8);
479                curr = 0; // Reset to root
480            } else {
481                curr = next;
482            }
483        }
484    }
485
486    // Per RFC 7541 Section 5.2: At the end of the sequence, any remaining bits in the last octet
487    // must be padding corresponding to the prefix of EOS (all 1s), and strictly less than 8 bits.
488    Ok(String::from_utf8_lossy(&out).into_owned())
489}
490
491/// Encodes an integer into a byte vector with a given prefix size per RFC 7541 Section 5.1.
492pub fn encode_integer(mut value: usize, prefix_bits: u8, prefix_mask: u8) -> Vec<u8> {
493    let max_prefix = (1 << prefix_bits) - 1;
494    if value < max_prefix {
495        return vec![prefix_mask | (value as u8)];
496    }
497
498    let mut out = vec![prefix_mask | (max_prefix as u8)];
499    value -= max_prefix;
500
501    while value >= 128 {
502        out.push(((value % 128) as u8) | 0x80);
503        value /= 128;
504    }
505    out.push(value as u8);
506    out
507}
508
509/// Decodes an integer from a byte slice with a given prefix size per RFC 7541 Section 5.1.
510pub fn decode_integer(slice: &[u8], prefix_bits: u8) -> Result<(usize, usize), FetchError> {
511    if slice.is_empty() {
512        return Err(FetchError::NetworkError("Truncated HPACK integer".into()));
513    }
514
515    let mask = (1usize << prefix_bits) - 1;
516    let first = slice[0] as usize & mask;
517    if first < mask {
518        return Ok((first, 1));
519    }
520
521    let mut value = mask;
522    let mut m = 0;
523    let mut cursor = 1;
524
525    while cursor < slice.len() {
526        let b = slice[cursor];
527        cursor += 1;
528        value += ((b & 0x7F) as usize) << m;
529        m += 7;
530        if (b & 0x80) == 0 {
531            return Ok((value, cursor));
532        }
533        if m >= 28 {
534            return Err(FetchError::NetworkError("HPACK integer overflow".into()));
535        }
536    }
537
538    Err(FetchError::NetworkError(
539        "Truncated HPACK multi-byte integer".into(),
540    ))
541}
542
543/// Encodes a string literal into an HPACK octet sequence (uncompressed literal, H=0).
544pub fn encode_string_literal(s: &str) -> Vec<u8> {
545    let bytes = s.as_bytes();
546    let mut out = encode_integer(bytes.len(), 7, 0x00);
547    out.extend_from_slice(bytes);
548    out
549}
550
551/// Decodes an HPACK string literal starting at cursor, supporting both plain and Huffman encoding.
552pub fn decode_string_literal(slice: &[u8]) -> Result<(String, usize), FetchError> {
553    if slice.is_empty() {
554        return Err(FetchError::NetworkError(
555            "Truncated HPACK string literal".into(),
556        ));
557    }
558    let is_huffman = (slice[0] & 0x80) != 0;
559    let (length, consumed) = decode_integer(slice, 7)?;
560
561    if slice.len() < consumed + length {
562        return Err(FetchError::NetworkError(
563            "Truncated HPACK string body".into(),
564        ));
565    }
566
567    let raw = &slice[consumed..consumed + length];
568    let s = if is_huffman {
569        decode_huffman_string(raw)?
570    } else {
571        String::from_utf8_lossy(raw).into_owned()
572    };
573
574    Ok((s, consumed + length))
575}
576
577/// Stateful HPACK decoder maintaining dynamic table per RFC 7541.
578#[derive(Debug, Clone, Default)]
579pub struct HpackDecoder {
580    pub dynamic_table: Vec<(String, String)>,
581    pub max_table_size: usize,
582    pub current_table_size: usize,
583}
584
585impl HpackDecoder {
586    pub fn new() -> Self {
587        Self {
588            dynamic_table: Vec::new(),
589            max_table_size: 4096,
590            current_table_size: 0,
591        }
592    }
593
594    /// Retrieves an entry by 1-based combined static and dynamic table index.
595    pub fn get_header(&self, index: usize) -> Result<(String, String), FetchError> {
596        if index == 0 {
597            return Err(FetchError::NetworkError("HPACK index 0 is invalid".into()));
598        }
599        if index < STATIC_TABLE.len() {
600            let (k, v) = STATIC_TABLE[index];
601            return Ok((k.to_string(), v.to_string()));
602        }
603
604        let dyn_idx = index - STATIC_TABLE.len();
605        if dyn_idx < self.dynamic_table.len() {
606            return Ok(self.dynamic_table[dyn_idx].clone());
607        }
608
609        Err(FetchError::NetworkError(format!(
610            "HPACK index {index} out of table bounds"
611        )))
612    }
613
614    /// Retrieves a header name by 1-based combined index.
615    pub fn get_name(&self, index: usize) -> Result<String, FetchError> {
616        self.get_header(index).map(|(name, _)| name)
617    }
618
619    /// Adds a new header entry to the dynamic table with FIFO eviction per RFC 7541 Section 4.1.
620    pub fn add_entry(&mut self, name: String, value: String) {
621        let entry_size = name.len() + value.len() + 32;
622        while self.current_table_size + entry_size > self.max_table_size
623            && !self.dynamic_table.is_empty()
624        {
625            if let Some((old_name, old_val)) = self.dynamic_table.pop() {
626                let old_size = old_name.len() + old_val.len() + 32;
627                self.current_table_size = self.current_table_size.saturating_sub(old_size);
628            }
629        }
630
631        if entry_size <= self.max_table_size {
632            self.current_table_size += entry_size;
633            self.dynamic_table.insert(0, (name, value));
634        }
635    }
636
637    /// Decodes an HPACK header block into key-value pairs.
638    pub fn decode_header_block(
639        &mut self,
640        block: &[u8],
641    ) -> Result<Vec<(String, String)>, FetchError> {
642        let mut headers = Vec::new();
643        let mut cursor = 0;
644
645        while cursor < block.len() {
646            let b = block[cursor];
647
648            if (b & 0x80) != 0 {
649                // Indexed Header Field: 1xxxxxxx (7-bit prefix)
650                let (index, consumed) = decode_integer(&block[cursor..], 7)?;
651                cursor += consumed;
652                let header = self.get_header(index)?;
653                headers.push(header);
654            } else if (b & 0x40) != 0 {
655                // Literal with Incremental Indexing: 01xxxxxx (6-bit prefix)
656                let (index, consumed) = decode_integer(&block[cursor..], 6)?;
657                cursor += consumed;
658
659                let name = if index > 0 {
660                    self.get_name(index)?
661                } else {
662                    let (n, n_consumed) = decode_string_literal(&block[cursor..])?;
663                    cursor += n_consumed;
664                    n
665                };
666
667                let (val, v_consumed) = decode_string_literal(&block[cursor..])?;
668                cursor += v_consumed;
669
670                self.add_entry(name.clone(), val.clone());
671                headers.push((name, val));
672            } else if (b & 0x20) != 0 {
673                // Dynamic Table Size Update: 001xxxxx (5-bit prefix)
674                let (new_size, consumed) = decode_integer(&block[cursor..], 5)?;
675                cursor += consumed;
676                self.max_table_size = new_size;
677                while self.current_table_size > self.max_table_size
678                    && !self.dynamic_table.is_empty()
679                {
680                    if let Some((old_name, old_val)) = self.dynamic_table.pop() {
681                        let old_size = old_name.len() + old_val.len() + 32;
682                        self.current_table_size = self.current_table_size.saturating_sub(old_size);
683                    }
684                }
685            } else {
686                // Literal without Indexing (0000xxxx) or Never Indexed (0001xxxx) (4-bit prefix)
687                let (index, consumed) = decode_integer(&block[cursor..], 4)?;
688                cursor += consumed;
689
690                let name = if index > 0 {
691                    self.get_name(index)?
692                } else {
693                    let (n, n_consumed) = decode_string_literal(&block[cursor..])?;
694                    cursor += n_consumed;
695                    n
696                };
697
698                let (val, v_consumed) = decode_string_literal(&block[cursor..])?;
699                cursor += v_consumed;
700                headers.push((name, val));
701            }
702        }
703
704        Ok(headers)
705    }
706}
707
708/// Convenience function to decode HPACK headers with a clean ephemeral decoder.
709pub fn decode_hpack_headers(block: &[u8]) -> Result<Vec<(String, String)>, FetchError> {
710    let mut decoder = HpackDecoder::new();
711    decoder.decode_header_block(block)
712}
713
714/// Encodes a list of header key-value pairs into an HPACK header block.
715pub fn encode_hpack_headers(headers: &[(&str, &str)]) -> Vec<u8> {
716    let mut block = Vec::new();
717
718    for &(k, v) in headers {
719        let k_lower = k.to_ascii_lowercase();
720
721        let mut matched_index = None;
722        let mut name_matched_index = None;
723
724        for (idx, &(s_k, s_v)) in STATIC_TABLE.iter().enumerate().skip(1) {
725            if s_k == k_lower {
726                if name_matched_index.is_none() {
727                    name_matched_index = Some(idx);
728                }
729                if s_v == v {
730                    matched_index = Some(idx);
731                    break;
732                }
733            }
734        }
735
736        if let Some(idx) = matched_index {
737            // Indexed Header Field Representation: 1xxxxxxx
738            block.extend(encode_integer(idx, 7, 0x80));
739        } else if let Some(idx) = name_matched_index {
740            // Literal Header Field without Indexing — Indexed Name: 0000xxxx
741            block.extend(encode_integer(idx, 4, 0x00));
742            block.extend(encode_string_literal(v));
743        } else {
744            // Literal Header Field without Indexing — New Name: 00000000
745            block.push(0x00);
746            block.extend(encode_string_literal(&k_lower));
747            block.extend(encode_string_literal(v));
748        }
749    }
750
751    block
752}
753
754/// Manages RFC 7540 §5.2 flow control window tracking and updates.
755#[derive(Debug, Clone)]
756pub struct FlowControlWindow {
757    pub current: i64,
758}
759
760impl FlowControlWindow {
761    pub fn new(initial: i64) -> Self {
762        Self { current: initial }
763    }
764
765    pub fn update(&mut self, increment: u32) -> Result<(), FetchError> {
766        if increment == 0 {
767            return Err(FetchError::NetworkError(
768                "PROTOCOL_ERROR: WINDOW_UPDATE increment must be non-zero (RFC 7540 §6.9)".into(),
769            ));
770        }
771        let next = self.current + increment as i64;
772        if next > 0x7FFF_FFFF {
773            return Err(FetchError::NetworkError(
774                "FLOW_CONTROL_ERROR: Window update exceeds maximum 2^31-1 (RFC 7540 §6.9.1)".into(),
775            ));
776        }
777        self.current = next;
778        Ok(())
779    }
780
781    pub fn consume(&mut self, amount: usize) -> Result<(), FetchError> {
782        if (amount as i64) > self.current {
783            return Err(FetchError::NetworkError(
784                "FLOW_CONTROL_ERROR: Sent data exceeds available flow control window".into(),
785            ));
786        }
787        self.current -= amount as i64;
788        Ok(())
789    }
790}
791
792fn send_available_body_chunks<T: Write>(
793    stream: &mut T,
794    body: &[u8],
795    body_bytes_sent: &mut usize,
796    conn_win: &mut FlowControlWindow,
797    stream_win: &mut FlowControlWindow,
798    max_frame_size: u32,
799) -> Result<bool, FetchError> {
800    let body_total = body.len();
801    while *body_bytes_sent < body_total {
802        let available_window = conn_win.current.min(stream_win.current);
803        if available_window <= 0 {
804            return Ok(false);
805        }
806
807        let remaining = body_total - *body_bytes_sent;
808        let chunk_size = remaining
809            .min(available_window as usize)
810            .min(max_frame_size as usize);
811
812        if chunk_size == 0 {
813            return Ok(false);
814        }
815
816        let next_offset = *body_bytes_sent + chunk_size;
817        let is_last = next_offset == body_total;
818        let flags = if is_last { FLAG_END_STREAM } else { 0 };
819
820        let chunk_payload = body[*body_bytes_sent..next_offset].to_vec();
821        let data_frame = Http2Frame::new(FRAME_DATA, flags, 1, chunk_payload);
822        stream
823            .write_all(&data_frame.encode())
824            .map_err(|e| FetchError::NetworkError(format!("Failed to write request DATA: {e}")))?;
825        stream
826            .flush()
827            .map_err(|e| FetchError::NetworkError(format!("Failed to flush request DATA: {e}")))?;
828
829        conn_win.consume(chunk_size)?;
830        stream_win.consume(chunk_size)?;
831        *body_bytes_sent = next_offset;
832
833        if is_last {
834            return Ok(true);
835        }
836    }
837
838    Ok(true)
839}
840
841/// Executes a full HTTP/2 request cycle over a synchronous stream (Plain TCP or TLS).
842pub fn execute_http2_request<T: Read + Write>(
843    stream: &mut T,
844    req: &RequestInit,
845    parsed: &ParsedUrl,
846) -> Result<Response, FetchError> {
847    // 1. Send 24-octet Client Connection Preface
848    stream
849        .write_all(HTTP2_PREFACE)
850        .map_err(|e| FetchError::NetworkError(format!("Failed to write HTTP/2 preface: {e}")))?;
851
852    // 2. Send Initial Client SETTINGS Frame (Stream 0)
853    let client_settings = Http2Frame::new(FRAME_SETTINGS, 0, 0, Vec::new());
854    stream
855        .write_all(&client_settings.encode())
856        .map_err(|e| FetchError::NetworkError(format!("Failed to write client SETTINGS: {e}")))?;
857    stream
858        .flush()
859        .map_err(|e| FetchError::NetworkError(format!("Failed to flush HTTP/2 init: {e}")))?;
860
861    // 3. Assemble and Send Request HEADERS Frame (Stream 1)
862    let method = req.method.to_uppercase();
863    let authority = if (parsed.scheme == "https" && parsed.port == 443)
864        || (parsed.scheme == "http" && parsed.port == 80)
865    {
866        parsed.host.clone()
867    } else {
868        format!("{}:{}", parsed.host, parsed.port)
869    };
870
871    let mut request_header_list: Vec<(&str, &str)> = vec![
872        (":method", &method),
873        (":scheme", &parsed.scheme),
874        (":path", &parsed.path_and_query),
875        (":authority", &authority),
876    ];
877
878    let mut owned_headers = Vec::new();
879    if !req.headers.has("accept-encoding") {
880        owned_headers.push((
881            "accept-encoding".to_string(),
882            "gzip, deflate, br".to_string(),
883        ));
884    }
885    if !req.headers.has("user-agent") {
886        owned_headers.push((
887            "user-agent".to_string(),
888            "Mozilla/5.0 (compatible; Onyx/1.0; +https://strataui.org)".to_string(),
889        ));
890    }
891    for (k, v) in req.headers.entries() {
892        owned_headers.push((k.to_ascii_lowercase(), v.to_string()));
893    }
894    for (k, v) in &owned_headers {
895        request_header_list.push((k.as_str(), v.as_str()));
896    }
897
898    let hpack_block = encode_hpack_headers(&request_header_list);
899
900    let has_body = req.body.as_ref().map(|b| !b.is_empty()).unwrap_or(false);
901    let header_flags = if has_body {
902        FLAG_END_HEADERS
903    } else {
904        FLAG_END_HEADERS | FLAG_END_STREAM
905    };
906
907    let headers_frame = Http2Frame::new(FRAME_HEADERS, header_flags, 1, hpack_block);
908    stream
909        .write_all(&headers_frame.encode())
910        .map_err(|e| FetchError::NetworkError(format!("Failed to write request HEADERS: {e}")))?;
911
912    let mut conn_settings = Http2ConnectionSettings::default();
913    let mut conn_send_window = FlowControlWindow::new(65_535);
914    let mut stream_send_window = FlowControlWindow::new(65_535);
915    let mut body_bytes_sent = 0usize;
916    let body_total = req.body.as_ref().map(|b| b.len()).unwrap_or(0);
917
918    if let Some(ref body) = req.body {
919        if !body.is_empty() {
920            let _ = send_available_body_chunks(
921                stream,
922                body,
923                &mut body_bytes_sent,
924                &mut conn_send_window,
925                &mut stream_send_window,
926                conn_settings.max_frame_size,
927            )?;
928        }
929    }
930
931    stream
932        .flush()
933        .map_err(|e| FetchError::NetworkError(format!("Failed to flush HTTP/2 request: {e}")))?;
934
935    // 4. Read Response Frames
936    let mut status_code = 200u16;
937    let mut status_text = "OK".to_string();
938    let mut response_headers = Headers::new();
939    let mut raw_body = Vec::new();
940    let mut headers_received = false;
941    let mut stream_ended = false;
942    let mut header_fragments = Vec::new();
943    let mut awaiting_continuation = false;
944    let mut hpack_decoder = HpackDecoder::new();
945
946    while !stream_ended {
947        let frame = Http2Frame::read_from_bounded(stream, conn_settings.max_frame_size)?;
948
949        match frame.frame_type {
950            FRAME_SETTINGS => {
951                if (frame.flags & FLAG_ACK) == 0 {
952                    let old_initial = conn_settings.initial_window_size;
953                    conn_settings.apply_settings(&frame.payload)?;
954                    if conn_settings.initial_window_size != old_initial {
955                        let delta = conn_settings.initial_window_size as i64 - old_initial as i64;
956                        stream_send_window.current += delta;
957                    }
958                    let ack = Http2Frame::new(FRAME_SETTINGS, FLAG_ACK, 0, Vec::new());
959                    let _ = stream.write_all(&ack.encode());
960                    let _ = stream.flush();
961                    if let Some(ref body) = req.body {
962                        if body_bytes_sent < body_total {
963                            let _ = send_available_body_chunks(
964                                stream,
965                                body,
966                                &mut body_bytes_sent,
967                                &mut conn_send_window,
968                                &mut stream_send_window,
969                                conn_settings.max_frame_size,
970                            )?;
971                        }
972                    }
973                }
974            }
975            FRAME_PING => {
976                if (frame.flags & FLAG_ACK) == 0 {
977                    let ping_ack = Http2Frame::new(FRAME_PING, FLAG_ACK, 0, frame.payload);
978                    let _ = stream.write_all(&ping_ack.encode());
979                    let _ = stream.flush();
980                }
981            }
982            FRAME_WINDOW_UPDATE => {
983                if frame.payload.len() != 4 {
984                    return Err(FetchError::NetworkError(
985                        "FRAME_SIZE_ERROR: WINDOW_UPDATE payload must be exactly 4 bytes".into(),
986                    ));
987                }
988                let increment = u32::from_be_bytes([
989                    frame.payload[0] & 0x7F,
990                    frame.payload[1],
991                    frame.payload[2],
992                    frame.payload[3],
993                ]);
994                if frame.stream_id == 0 {
995                    conn_send_window.update(increment)?;
996                } else if frame.stream_id == 1 {
997                    stream_send_window.update(increment)?;
998                }
999                if let Some(ref body) = req.body {
1000                    if body_bytes_sent < body_total {
1001                        let _ = send_available_body_chunks(
1002                            stream,
1003                            body,
1004                            &mut body_bytes_sent,
1005                            &mut conn_send_window,
1006                            &mut stream_send_window,
1007                            conn_settings.max_frame_size,
1008                        )?;
1009                    }
1010                }
1011            }
1012            FRAME_HEADERS if frame.stream_id == 1 => {
1013                let mut payload_slice = &frame.payload[..];
1014
1015                // Handle FLAG_PADDED (0x8)
1016                if (frame.flags & FLAG_PADDED) != 0 {
1017                    if payload_slice.is_empty() {
1018                        return Err(FetchError::NetworkError(
1019                            "Malformed padded HEADERS frame".into(),
1020                        ));
1021                    }
1022                    let pad_len = payload_slice[0] as usize;
1023                    payload_slice = &payload_slice[1..];
1024                    if payload_slice.len() < pad_len {
1025                        return Err(FetchError::NetworkError(
1026                            "Padding exceeds HEADERS payload".into(),
1027                        ));
1028                    }
1029                    payload_slice = &payload_slice[..payload_slice.len() - pad_len];
1030                }
1031
1032                // Handle FLAG_PRIORITY (0x20)
1033                if (frame.flags & FLAG_PRIORITY) != 0 {
1034                    if payload_slice.len() < 5 {
1035                        return Err(FetchError::NetworkError(
1036                            "Malformed prioritized HEADERS frame".into(),
1037                        ));
1038                    }
1039                    payload_slice = &payload_slice[5..];
1040                }
1041
1042                header_fragments.extend_from_slice(payload_slice);
1043
1044                if (frame.flags & FLAG_END_HEADERS) != 0 {
1045                    let decoded = hpack_decoder.decode_header_block(&header_fragments)?;
1046                    for (k, v) in decoded {
1047                        if k == ":status" {
1048                            if let Ok(code) = v.parse::<u16>() {
1049                                status_code = code;
1050                                status_text = match code {
1051                                    200 => "OK",
1052                                    201 => "Created",
1053                                    204 => "No Content",
1054                                    301 => "Moved Permanently",
1055                                    302 => "Found",
1056                                    303 => "See Other",
1057                                    304 => "Not Modified",
1058                                    307 => "Temporary Redirect",
1059                                    308 => "Permanent Redirect",
1060                                    400 => "Bad Request",
1061                                    401 => "Unauthorized",
1062                                    403 => "Forbidden",
1063                                    404 => "Not Found",
1064                                    500 => "Internal Server Error",
1065                                    502 => "Bad Gateway",
1066                                    503 => "Service Unavailable",
1067                                    _ => "HTTP/2 Response",
1068                                }
1069                                .to_string();
1070                            }
1071                        } else if !k.starts_with(':') {
1072                            response_headers.append(&k, &v);
1073                        }
1074                    }
1075                    headers_received = true;
1076                    header_fragments.clear();
1077                    awaiting_continuation = false;
1078                } else {
1079                    awaiting_continuation = true;
1080                }
1081
1082                if (frame.flags & FLAG_END_STREAM) != 0 {
1083                    stream_ended = true;
1084                }
1085            }
1086            FRAME_CONTINUATION if frame.stream_id == 1 && awaiting_continuation => {
1087                header_fragments.extend_from_slice(&frame.payload);
1088                if (frame.flags & FLAG_END_HEADERS) != 0 {
1089                    let decoded = hpack_decoder.decode_header_block(&header_fragments)?;
1090                    for (k, v) in decoded {
1091                        if k == ":status" {
1092                            if let Ok(code) = v.parse::<u16>() {
1093                                status_code = code;
1094                            }
1095                        } else if !k.starts_with(':') {
1096                            response_headers.set(&k, &v);
1097                        }
1098                    }
1099                    headers_received = true;
1100                    header_fragments.clear();
1101                    awaiting_continuation = false;
1102                }
1103                if (frame.flags & FLAG_END_STREAM) != 0 {
1104                    stream_ended = true;
1105                }
1106            }
1107            FRAME_DATA if frame.stream_id == 1 => {
1108                let mut data_payload = &frame.payload[..];
1109                if (frame.flags & FLAG_PADDED) != 0 {
1110                    if data_payload.is_empty() {
1111                        return Err(FetchError::NetworkError(
1112                            "PROTOCOL_ERROR: Padded DATA frame missing pad length byte".into(),
1113                        ));
1114                    }
1115                    let pad_len = data_payload[0] as usize;
1116                    data_payload = &data_payload[1..];
1117                    if data_payload.len() < pad_len {
1118                        return Err(FetchError::NetworkError(
1119                            "PROTOCOL_ERROR: DATA frame padding length exceeds or equals payload length".into(),
1120                        ));
1121                    }
1122                    data_payload = &data_payload[..data_payload.len() - pad_len];
1123                }
1124                raw_body.extend_from_slice(data_payload);
1125
1126                if (frame.flags & FLAG_END_STREAM) != 0 {
1127                    stream_ended = true;
1128                } else if !data_payload.is_empty() {
1129                    // Send WINDOW_UPDATE to maintain stream and connection flow control while stream is active
1130                    let delta = data_payload.len() as u32;
1131                    let win_conn =
1132                        Http2Frame::new(FRAME_WINDOW_UPDATE, 0, 0, delta.to_be_bytes().to_vec());
1133                    let _ = stream.write_all(&win_conn.encode());
1134                    let win_stream =
1135                        Http2Frame::new(FRAME_WINDOW_UPDATE, 0, 1, delta.to_be_bytes().to_vec());
1136                    let _ = stream.write_all(&win_stream.encode());
1137                    let _ = stream.flush();
1138                }
1139            }
1140            FRAME_RST_STREAM if frame.stream_id == 1 => {
1141                return Err(FetchError::NetworkError(format!(
1142                    "HTTP/2 stream 1 reset by peer (error code {:?})",
1143                    frame.payload
1144                )));
1145            }
1146            FRAME_GOAWAY => {
1147                if !headers_received {
1148                    return Err(FetchError::NetworkError(
1149                        "Received GOAWAY before HTTP/2 headers".into(),
1150                    ));
1151                }
1152                stream_ended = true;
1153            }
1154            _ => {
1155                // Ignore other stream IDs or unknown extension frames
1156            }
1157        }
1158    }
1159
1160    // 5. Decompress Payload based on Content-Encoding
1161    let body = if let Some(encoding) = response_headers.get("content-encoding") {
1162        decompress_body(&raw_body, encoding)?
1163    } else {
1164        raw_body
1165    };
1166
1167    Ok(Response::new(
1168        status_code,
1169        &status_text,
1170        response_headers,
1171        body,
1172    ))
1173}