trillium-http 1.1.0

the http implementation for the trillium toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use super::H2ErrorCode;
use crate::HttpConfig;
use fieldwork::Fieldwork;

/// `SETTINGS_HEADER_TABLE_SIZE` (RFC 9113 §6.5.2).
const SETTINGS_HEADER_TABLE_SIZE: u16 = 0x1;
/// `SETTINGS_ENABLE_PUSH` (RFC 9113 §6.5.2).
const SETTINGS_ENABLE_PUSH: u16 = 0x2;
/// `SETTINGS_MAX_CONCURRENT_STREAMS` (RFC 9113 §6.5.2).
const SETTINGS_MAX_CONCURRENT_STREAMS: u16 = 0x3;
/// `SETTINGS_INITIAL_WINDOW_SIZE` (RFC 9113 §6.5.2).
const SETTINGS_INITIAL_WINDOW_SIZE: u16 = 0x4;
/// `SETTINGS_MAX_FRAME_SIZE` (RFC 9113 §6.5.2).
const SETTINGS_MAX_FRAME_SIZE: u16 = 0x5;
/// `SETTINGS_MAX_HEADER_LIST_SIZE` (RFC 9113 §6.5.2).
const SETTINGS_MAX_HEADER_LIST_SIZE: u16 = 0x6;
/// `SETTINGS_ENABLE_CONNECT_PROTOCOL` (RFC 8441 §3) — advertises that the server
/// accepts extended CONNECT requests carrying a `:protocol` pseudo-header.
const SETTINGS_ENABLE_CONNECT_PROTOCOL: u16 = 0x8;

/// The upper bound on `SETTINGS_INITIAL_WINDOW_SIZE` (RFC 9113 §6.5.2).
const MAX_INITIAL_WINDOW_SIZE: u32 = (1 << 31) - 1;
/// The lower bound on `SETTINGS_MAX_FRAME_SIZE` (RFC 9113 §6.5.2).
const MIN_MAX_FRAME_SIZE: u32 = 16_384;
/// The upper bound on `SETTINGS_MAX_FRAME_SIZE` (RFC 9113 §6.5.2).
const MAX_MAX_FRAME_SIZE: u32 = (1 << 24) - 1;

/// Each setting on the wire is (id:u16, value:u32).
const SETTING_ENTRY_LEN: usize = 6;

/// H2 connection settings per RFC 9113 §6.5.2.
///
/// `None` fields mean the setting was absent, implying the RFC default
/// (4096 for header table, 1 for push, unlimited for concurrent streams / header list size,
/// 65535 for initial window, 16384 for max frame size).
///
/// Use [`H2Settings::server_defaults`] for a reasonable outgoing configuration; use [`decode`] for
/// incoming settings.
///
/// [`decode`]: H2Settings::decode
#[derive(Clone, Copy, Eq, Fieldwork, Default)]
#[fieldwork(get, set, with(option_set_some))]
pub struct H2Settings {
    /// The maximum size of the HPACK dynamic header table the peer may use when encoding.
    ///
    /// Default: 4096.
    header_table_size: Option<u32>,

    /// Whether the peer is permitted to initiate server push.
    ///
    /// Default: true. Trillium always advertises `Some(false)` from [`Self::from_config`]
    /// because we never send `PUSH_PROMISE`; a peer that advertises `Some(true)` is a protocol
    /// error for a server since clients cannot push.
    enable_push: Option<bool>,

    /// The maximum number of concurrent streams the peer may initiate.
    ///
    /// Default: unlimited. RFC 9113 recommends at least 100.
    max_concurrent_streams: Option<u32>,

    /// The initial flow-control window size for streams, in octets.
    ///
    /// Default: 65535. Must not exceed 2^31 - 1.
    initial_window_size: Option<u32>,

    /// The maximum frame payload size the peer is willing to receive, in octets.
    ///
    /// Default: 16384. Must be in [16384, 2^24 - 1].
    max_frame_size: Option<u32>,

    /// The maximum size of a header list the peer is willing to receive, in octets.
    ///
    /// Default: unlimited.
    max_header_list_size: Option<u32>,

    /// `SETTINGS_ENABLE_CONNECT_PROTOCOL` (RFC 8441 §3) — when `Some(true)`, advertises
    /// that the server accepts extended CONNECT requests (with a `:protocol`
    /// pseudo-header), enabling WebSocket-over-h2 and WebTransport-over-h2.
    ///
    /// `None` means the setting is absent (peer-default false). Peers MUST treat values
    /// other than 0/1 as a connection-level `PROTOCOL_ERROR` per RFC 8441 §3.
    enable_connect_protocol: Option<bool>,

    // GREASE setting included in encoded output per RFC 8701 when non-zero.
    // Chosen at construction time so encoded_len() and encode() agree.
    // Zero when decoded from a peer (GREASE is skipped during decode).
    #[field = false]
    grease_id: u16,

    #[field = false]
    grease_value: u32,
}

impl std::fmt::Debug for H2Settings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("H2Settings")
            .field("header_table_size", &self.header_table_size)
            .field("enable_push", &self.enable_push)
            .field("max_concurrent_streams", &self.max_concurrent_streams)
            .field("initial_window_size", &self.initial_window_size)
            .field("max_frame_size", &self.max_frame_size)
            .field("max_header_list_size", &self.max_header_list_size)
            .field("enable_connect_protocol", &self.enable_connect_protocol)
            .finish_non_exhaustive()
    }
}

/// `PartialEq` ignores GREASE — it's an encoding detail, not semantically meaningful.
impl PartialEq for H2Settings {
    fn eq(&self, other: &Self) -> bool {
        self.header_table_size == other.header_table_size
            && self.enable_push == other.enable_push
            && self.max_concurrent_streams == other.max_concurrent_streams
            && self.initial_window_size == other.initial_window_size
            && self.max_frame_size == other.max_frame_size
            && self.max_header_list_size == other.max_header_list_size
            && self.enable_connect_protocol == other.enable_connect_protocol
    }
}

impl H2Settings {
    /// [`max_frame_size`][Self::max_frame_size] with the RFC 9113 §6.5.2 default of 16384
    /// applied when the field is `None`. Use this when you need a concrete value for
    /// framing.
    pub(crate) fn effective_max_frame_size(&self) -> u32 {
        self.max_frame_size.unwrap_or(16_384)
    }

    /// [`initial_window_size`][Self::initial_window_size] with the RFC 9113 §6.5.2 default
    /// of 65535 applied when the field is `None`. Use this when seeding a new stream's send
    /// window.
    pub(crate) fn effective_initial_window_size(&self) -> u32 {
        self.initial_window_size.unwrap_or(65_535)
    }

    /// [`max_concurrent_streams`][Self::max_concurrent_streams] with the RFC 9113 §6.5.2
    /// "no limit" default applied when the field is `None`. The spec leaves the initial
    /// value unbounded, so callers should treat the absence of an advertised limit as
    /// permission to open as many streams as the stream-id space allows.
    #[cfg(feature = "unstable")]
    pub(crate) fn effective_max_concurrent_streams(&self) -> u32 {
        self.max_concurrent_streams.unwrap_or(u32::MAX)
    }

    /// Build an outgoing SETTINGS frame from the h2 fields of an [`HttpConfig`][crate::HttpConfig].
    ///
    /// Disables server push (`SETTINGS_ENABLE_PUSH` = 0, trillium never sends `PUSH_PROMISE`) and
    /// selects a random GREASE setting per RFC 8701 for forward-compat checking. The remaining
    /// advertised values come from the config:
    ///
    /// | Setting | Source |
    /// |---|---|
    /// | `SETTINGS_INITIAL_WINDOW_SIZE` | `h2_initial_stream_window_size` |
    /// | `SETTINGS_MAX_CONCURRENT_STREAMS` | `h2_max_concurrent_streams` |
    /// | `SETTINGS_MAX_FRAME_SIZE` | `h2_max_frame_size` |
    /// | `SETTINGS_MAX_HEADER_LIST_SIZE` | `max_header_list_size` |
    pub(crate) fn from_config(config: &HttpConfig) -> Self {
        // RFC 8701: the reserved GREASE settings are 0x0A0A, 0x1A1A, ..., 0xFAFA.
        let n = u16::from(fastrand::u8(0..16));
        let grease_id = 0x0A0A | (n << 12) | (n << 4);
        Self {
            enable_push: Some(false),
            max_concurrent_streams: Some(config.h2_max_concurrent_streams()),
            max_header_list_size: Some(
                config.max_header_list_size().try_into().unwrap_or(u32::MAX),
            ),
            initial_window_size: Some(config.h2_initial_stream_window_size()),
            max_frame_size: Some(config.h2_max_frame_size()),
            // Only advertise SETTINGS_ENABLE_CONNECT_PROTOCOL when actually enabled —
            // omitting it (None) is equivalent to advertising 0 per RFC 8441 §3 default.
            enable_connect_protocol: config.extended_connect_enabled().then_some(true),
            grease_id,
            grease_value: fastrand::u32(..),
            ..Default::default()
        }
    }

    /// A reasonable outgoing settings frame for a trillium server, using the default
    /// `HttpConfig`. Convenience wrapper around [`Self::from_config`] for tests and ad-hoc
    /// use; production code builds via `from_config` with the real configured values.
    #[cfg(test)]
    pub(crate) fn server_defaults() -> Self {
        Self::from_config(&HttpConfig::DEFAULT)
    }

    /// The number of bytes this settings payload will occupy when encoded.
    pub(crate) fn encoded_len(&self) -> usize {
        let mut entries = 0;
        if self.header_table_size.is_some() {
            entries += 1;
        }
        if self.enable_push.is_some() {
            entries += 1;
        }
        if self.max_concurrent_streams.is_some() {
            entries += 1;
        }
        if self.initial_window_size.is_some() {
            entries += 1;
        }
        if self.max_frame_size.is_some() {
            entries += 1;
        }
        if self.max_header_list_size.is_some() {
            entries += 1;
        }
        if self.enable_connect_protocol.is_some() {
            entries += 1;
        }
        if self.grease_id != 0 {
            entries += 1;
        }
        entries * SETTING_ENTRY_LEN
    }

    /// Decode settings from a SETTINGS frame payload.
    ///
    /// Payload length is expected to already be a multiple of 6 octets (the outer frame codec
    /// checks this and raises `FRAME_SIZE_ERROR` otherwise).
    ///
    /// # Errors
    ///
    /// Returns an [`H2ErrorCode`] if any setting has an out-of-range value:
    /// - `PROTOCOL_ERROR` for an `ENABLE_PUSH` value other than 0 or 1, or a `MAX_FRAME_SIZE`
    ///   outside \[16384, 2^24 - 1\].
    /// - `FLOW_CONTROL_ERROR` for an `INITIAL_WINDOW_SIZE` above 2^31 - 1.
    /// - `FRAME_SIZE_ERROR` if the payload length is not a multiple of 6.
    pub(crate) fn decode(payload: &[u8]) -> Result<Self, H2ErrorCode> {
        if !payload.len().is_multiple_of(SETTING_ENTRY_LEN) {
            return Err(H2ErrorCode::FrameSizeError);
        }
        let mut settings = Self::default();
        for entry in payload.chunks_exact(SETTING_ENTRY_LEN) {
            let id = u16::from_be_bytes([entry[0], entry[1]]);
            let value = u32::from_be_bytes([entry[2], entry[3], entry[4], entry[5]]);
            match id {
                SETTINGS_HEADER_TABLE_SIZE => settings.header_table_size = Some(value),
                SETTINGS_ENABLE_PUSH => match value {
                    0 => settings.enable_push = Some(false),
                    1 => settings.enable_push = Some(true),
                    _ => return Err(H2ErrorCode::ProtocolError),
                },
                SETTINGS_MAX_CONCURRENT_STREAMS => settings.max_concurrent_streams = Some(value),
                SETTINGS_INITIAL_WINDOW_SIZE => {
                    if value > MAX_INITIAL_WINDOW_SIZE {
                        return Err(H2ErrorCode::FlowControlError);
                    }
                    settings.initial_window_size = Some(value);
                }
                SETTINGS_MAX_FRAME_SIZE => {
                    if !(MIN_MAX_FRAME_SIZE..=MAX_MAX_FRAME_SIZE).contains(&value) {
                        return Err(H2ErrorCode::ProtocolError);
                    }
                    settings.max_frame_size = Some(value);
                }
                SETTINGS_MAX_HEADER_LIST_SIZE => settings.max_header_list_size = Some(value),
                SETTINGS_ENABLE_CONNECT_PROTOCOL => match value {
                    0 => settings.enable_connect_protocol = Some(false),
                    1 => settings.enable_connect_protocol = Some(true),
                    _ => return Err(H2ErrorCode::ProtocolError),
                },
                _ => log::trace!("skipping unknown setting identifier {id:#x}"),
            }
        }
        Ok(settings)
    }

    /// Encode these settings into `buf`. Returns the number of bytes written, or `None` if the
    /// buffer is too small (check [`encoded_len`](Self::encoded_len) first).
    pub(crate) fn encode(&self, buf: &mut [u8]) -> Option<usize> {
        if buf.len() < self.encoded_len() {
            return None;
        }
        let mut written = 0;
        if let Some(v) = self.header_table_size {
            written += write_entry(SETTINGS_HEADER_TABLE_SIZE, v, &mut buf[written..]);
        }
        if let Some(b) = self.enable_push {
            written += write_entry(SETTINGS_ENABLE_PUSH, u32::from(b), &mut buf[written..]);
        }
        if let Some(v) = self.max_concurrent_streams {
            written += write_entry(SETTINGS_MAX_CONCURRENT_STREAMS, v, &mut buf[written..]);
        }
        if let Some(v) = self.initial_window_size {
            written += write_entry(SETTINGS_INITIAL_WINDOW_SIZE, v, &mut buf[written..]);
        }
        if let Some(v) = self.max_frame_size {
            written += write_entry(SETTINGS_MAX_FRAME_SIZE, v, &mut buf[written..]);
        }
        if let Some(v) = self.max_header_list_size {
            written += write_entry(SETTINGS_MAX_HEADER_LIST_SIZE, v, &mut buf[written..]);
        }
        if let Some(b) = self.enable_connect_protocol {
            written += write_entry(
                SETTINGS_ENABLE_CONNECT_PROTOCOL,
                u32::from(b),
                &mut buf[written..],
            );
        }
        if self.grease_id != 0 {
            written += write_entry(self.grease_id, self.grease_value, &mut buf[written..]);
        }
        Some(written)
    }
}

fn write_entry(id: u16, value: u32, buf: &mut [u8]) -> usize {
    buf[0..2].copy_from_slice(&id.to_be_bytes());
    buf[2..6].copy_from_slice(&value.to_be_bytes());
    SETTING_ENTRY_LEN
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roundtrip_all_fields() {
        let settings = H2Settings::server_defaults()
            .with_header_table_size(4096)
            .with_initial_window_size(65_536)
            .with_max_frame_size(32_768);
        let mut buf = vec![0; 256];
        let len = settings.encode(&mut buf).unwrap();
        assert_eq!(len, settings.encoded_len());
        let decoded = H2Settings::decode(&buf[..len]).unwrap();
        assert_eq!(decoded, settings);
    }

    #[test]
    fn roundtrip_empty_still_grease() {
        // server_defaults always has GREASE
        let settings = H2Settings::server_defaults();
        let mut buf = vec![0; 256];
        let len = settings.encode(&mut buf).unwrap();
        assert!(len > 0);
        let decoded = H2Settings::decode(&buf[..len]).unwrap();
        assert_eq!(decoded, settings);
    }

    #[test]
    fn decode_default_empty_payload() {
        let settings = H2Settings::decode(&[]).unwrap();
        assert_eq!(settings, H2Settings::default());
    }

    #[test]
    fn odd_payload_length_is_frame_size_error() {
        // 5 bytes — not a multiple of 6
        assert_eq!(
            H2Settings::decode(&[0, 1, 0, 0, 0]),
            Err(H2ErrorCode::FrameSizeError),
        );
    }

    #[test]
    fn invalid_enable_push_is_protocol_error() {
        let mut payload = [0; 6];
        write_entry(SETTINGS_ENABLE_PUSH, 2, &mut payload);
        assert_eq!(
            H2Settings::decode(&payload),
            Err(H2ErrorCode::ProtocolError),
        );
    }

    #[test]
    fn enable_push_zero_and_one_both_ok() {
        for value in [0u32, 1] {
            let mut payload = [0; 6];
            write_entry(SETTINGS_ENABLE_PUSH, value, &mut payload);
            let decoded = H2Settings::decode(&payload).unwrap();
            assert_eq!(decoded.enable_push, Some(value == 1));
        }
    }

    #[test]
    fn oversized_initial_window_is_flow_control_error() {
        let mut payload = [0; 6];
        write_entry(SETTINGS_INITIAL_WINDOW_SIZE, 1 << 31, &mut payload);
        assert_eq!(
            H2Settings::decode(&payload),
            Err(H2ErrorCode::FlowControlError),
        );
    }

    #[test]
    fn initial_window_at_max_is_allowed() {
        let mut payload = [0; 6];
        write_entry(
            SETTINGS_INITIAL_WINDOW_SIZE,
            MAX_INITIAL_WINDOW_SIZE,
            &mut payload,
        );
        let decoded = H2Settings::decode(&payload).unwrap();
        assert_eq!(decoded.initial_window_size, Some(MAX_INITIAL_WINDOW_SIZE));
    }

    #[test]
    fn undersized_max_frame_size_is_protocol_error() {
        let mut payload = [0; 6];
        write_entry(SETTINGS_MAX_FRAME_SIZE, 16_383, &mut payload);
        assert_eq!(
            H2Settings::decode(&payload),
            Err(H2ErrorCode::ProtocolError),
        );
    }

    #[test]
    fn oversized_max_frame_size_is_protocol_error() {
        let mut payload = [0; 6];
        write_entry(SETTINGS_MAX_FRAME_SIZE, 1 << 24, &mut payload);
        assert_eq!(
            H2Settings::decode(&payload),
            Err(H2ErrorCode::ProtocolError),
        );
    }

    #[test]
    fn max_frame_size_at_bounds_allowed() {
        for value in [MIN_MAX_FRAME_SIZE, MAX_MAX_FRAME_SIZE] {
            let mut payload = [0; 6];
            write_entry(SETTINGS_MAX_FRAME_SIZE, value, &mut payload);
            let decoded = H2Settings::decode(&payload).unwrap();
            assert_eq!(decoded.max_frame_size, Some(value));
        }
    }

    #[test]
    fn unknown_identifiers_are_skipped() {
        // A made-up setting ID 0x9999 with value 42, followed by MAX_CONCURRENT_STREAMS=50.
        let mut payload = [0; 12];
        write_entry(0x9999, 42, &mut payload[..6]);
        write_entry(SETTINGS_MAX_CONCURRENT_STREAMS, 50, &mut payload[6..]);
        let decoded = H2Settings::decode(&payload).unwrap();
        assert_eq!(decoded.max_concurrent_streams, Some(50));
    }

    #[test]
    fn grease_id_matches_rfc_8701_pattern() {
        // Every GREASE id must match NaNa for n in 0..=15.
        for _ in 0..100 {
            let settings = H2Settings::server_defaults();
            let id = settings.grease_id;
            let n = (id >> 12) & 0xf;
            assert_eq!(id, 0x0A0A | (n << 12) | (n << 4), "bad GREASE id {id:#x}");
        }
    }

    #[test]
    fn grease_skipped_on_decode() {
        let settings = H2Settings::server_defaults();
        let mut buf = vec![0; 256];
        let len = settings.encode(&mut buf).unwrap();
        let decoded = H2Settings::decode(&buf[..len]).unwrap();
        // decoded has no grease id
        assert_eq!(decoded.grease_id, 0);
    }

    #[test]
    fn enable_connect_protocol_roundtrip() {
        // Setting absent on encode → not in output → decoded as None.
        let absent = H2Settings::default();
        let mut buf = vec![0; 64];
        let len = absent.encode(&mut buf).unwrap();
        let decoded = H2Settings::decode(&buf[..len]).unwrap();
        assert_eq!(decoded.enable_connect_protocol, None);

        // Setting present (true) survives roundtrip.
        let on = H2Settings::default().with_enable_connect_protocol(true);
        let mut buf = vec![0; 64];
        let len = on.encode(&mut buf).unwrap();
        let decoded = H2Settings::decode(&buf[..len]).unwrap();
        assert_eq!(decoded.enable_connect_protocol, Some(true));
    }

    #[test]
    fn invalid_enable_connect_protocol_is_protocol_error() {
        let mut payload = [0; 6];
        write_entry(SETTINGS_ENABLE_CONNECT_PROTOCOL, 2, &mut payload);
        assert_eq!(
            H2Settings::decode(&payload),
            Err(H2ErrorCode::ProtocolError),
        );
    }

    #[test]
    fn later_setting_overrides_earlier() {
        let mut payload = [0; 12];
        write_entry(SETTINGS_MAX_CONCURRENT_STREAMS, 10, &mut payload[..6]);
        write_entry(SETTINGS_MAX_CONCURRENT_STREAMS, 100, &mut payload[6..]);
        let decoded = H2Settings::decode(&payload).unwrap();
        assert_eq!(decoded.max_concurrent_streams, Some(100));
    }
}