Skip to main content

ntex_h2/frame/
settings.rs

1use std::fmt;
2
3use ntex_bytes::{BufMut, BytesMut};
4
5use crate::frame::{Frame, FrameError, FrameSize, Head, Kind, StreamId, util};
6
7#[derive(Copy, Clone, Default, Eq, PartialEq)]
8pub struct Settings {
9    flags: SettingsFlags,
10    // Fields
11    header_table_size: Option<u32>,
12    enable_push: Option<u32>,
13    max_concurrent_streams: Option<u32>,
14    initial_window_size: Option<u32>,
15    max_frame_size: Option<u32>,
16    max_header_list_size: Option<u32>,
17    enable_connect_protocol: Option<u32>,
18}
19
20/// An enum that lists all valid settings that can be sent in a SETTINGS
21/// frame.
22///
23/// Each setting has a value that is a 32 bit unsigned integer (6.5.1.).
24#[derive(Copy, Clone, Debug)]
25pub(super) enum Setting {
26    HeaderTableSize(u32),
27    EnablePush(u32),
28    MaxConcurrentStreams(u32),
29    InitialWindowSize(u32),
30    MaxFrameSize(u32),
31    MaxHeaderListSize(u32),
32    EnableConnectProtocol(u32),
33}
34
35#[derive(Copy, Clone, Eq, PartialEq, Default)]
36pub struct SettingsFlags(u8);
37
38const ACK: u8 = 0x1;
39const ALL: u8 = ACK;
40
41/// The default value of `SETTINGS_HEADER_TABLE_SIZE`
42pub const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: usize = 4_096;
43
44/// The default value of `SETTINGS_INITIAL_WINDOW_SIZE`
45pub const DEFAULT_INITIAL_WINDOW_SIZE: i32 = 65_535;
46
47/// The default value of `MAX_FRAME_SIZE`
48pub const DEFAULT_MAX_FRAME_SIZE: FrameSize = 16_384;
49
50/// `INITIAL_WINDOW_SIZE` upper bound
51pub const MAX_INITIAL_WINDOW_SIZE: usize = (1 << 31) - 1;
52
53/// `MAX_FRAME_SIZE` upper bound
54pub const MAX_MAX_FRAME_SIZE: FrameSize = (1 << 24) - 1;
55
56// ===== impl Settings =====
57
58impl Settings {
59    pub fn ack() -> Settings {
60        Settings {
61            flags: SettingsFlags::ack(),
62            ..Settings::default()
63        }
64    }
65
66    pub fn is_ack(&self) -> bool {
67        self.flags.is_ack()
68    }
69
70    #[allow(clippy::cast_possible_wrap)]
71    pub fn initial_window_size(&self) -> Option<i32> {
72        self.initial_window_size.map(|v| v as i32)
73    }
74
75    pub fn set_initial_window_size(&mut self, size: Option<u32>) {
76        self.initial_window_size = size;
77    }
78
79    pub fn max_concurrent_streams(&self) -> Option<u32> {
80        self.max_concurrent_streams
81    }
82
83    pub fn set_max_concurrent_streams(&mut self, max: Option<u32>) {
84        self.max_concurrent_streams = max;
85    }
86
87    pub fn max_frame_size(&self) -> Option<u32> {
88        self.max_frame_size
89    }
90
91    /// Set max frame size
92    ///
93    /// # Panics
94    ///
95    /// Value must be in range 16kb..
96    pub fn set_max_frame_size(&mut self, size: u32) {
97        assert!((DEFAULT_MAX_FRAME_SIZE..=MAX_MAX_FRAME_SIZE).contains(&size));
98        self.max_frame_size = Some(size);
99    }
100
101    pub fn max_header_list_size(&self) -> Option<u32> {
102        self.max_header_list_size
103    }
104
105    pub fn set_max_header_list_size(&mut self, size: Option<u32>) {
106        self.max_header_list_size = size;
107    }
108
109    pub fn is_push_enabled(&self) -> Option<bool> {
110        self.enable_push.map(|val| val != 0)
111    }
112
113    pub fn set_enable_push(&mut self, enable: bool) {
114        self.enable_push = Some(u32::from(enable));
115    }
116
117    pub fn is_extended_connect_protocol_enabled(&self) -> Option<bool> {
118        self.enable_connect_protocol.map(|val| val != 0)
119    }
120
121    pub fn set_enable_connect_protocol(&mut self, val: Option<u32>) {
122        self.enable_connect_protocol = val;
123    }
124
125    pub fn header_table_size(&self) -> Option<u32> {
126        self.header_table_size
127    }
128
129    /*
130    pub fn set_header_table_size(&mut self, size: Option<u32>) {
131        self.header_table_size = size;
132    }
133    */
134
135    pub fn load(head: Head, payload: &[u8]) -> Result<Settings, FrameError> {
136        debug_assert_eq!(head.kind(), crate::frame::Kind::Settings);
137
138        if !head.stream_id().is_zero() {
139            return Err(FrameError::InvalidStreamId);
140        }
141
142        // Load the flag
143        let flag = SettingsFlags::load(head.flag());
144
145        if flag.is_ack() {
146            // Ensure that the payload is empty
147            if !payload.is_empty() {
148                return Err(FrameError::InvalidPayloadLength);
149            }
150
151            // Return the ACK frame
152            return Ok(Settings::ack());
153        }
154
155        // Ensure the payload length is correct, each setting is 6 bytes long.
156        if !payload.len().is_multiple_of(6) {
157            log::debug!("invalid settings payload length; len={:?}", payload.len());
158            return Err(FrameError::InvalidPayloadAckSettings);
159        }
160
161        let mut settings = Settings::default();
162        debug_assert!(!settings.flags.is_ack());
163
164        for raw in payload.chunks(6) {
165            match Setting::load(raw) {
166                Some(Setting::HeaderTableSize(val)) => {
167                    settings.header_table_size = Some(val);
168                }
169                Some(Setting::EnablePush(val)) => match val {
170                    0 | 1 => {
171                        settings.enable_push = Some(val);
172                    }
173                    _ => {
174                        return Err(FrameError::InvalidSettingValue);
175                    }
176                },
177                Some(Setting::MaxConcurrentStreams(val)) => {
178                    settings.max_concurrent_streams = Some(val);
179                }
180                Some(Setting::InitialWindowSize(val)) => {
181                    if val as usize > MAX_INITIAL_WINDOW_SIZE {
182                        return Err(FrameError::InvalidSettingValue);
183                    }
184                    settings.initial_window_size = Some(val);
185                }
186                Some(Setting::MaxFrameSize(val)) => {
187                    if (DEFAULT_MAX_FRAME_SIZE..=MAX_MAX_FRAME_SIZE).contains(&val) {
188                        settings.max_frame_size = Some(val);
189                    } else {
190                        return Err(FrameError::InvalidSettingValue);
191                    }
192                }
193                Some(Setting::MaxHeaderListSize(val)) => {
194                    settings.max_header_list_size = Some(val);
195                }
196                Some(Setting::EnableConnectProtocol(val)) => match val {
197                    0 | 1 => {
198                        settings.enable_connect_protocol = Some(val);
199                    }
200                    _ => {
201                        return Err(FrameError::InvalidSettingValue);
202                    }
203                },
204                None => {}
205            }
206        }
207
208        Ok(settings)
209    }
210
211    fn payload_len(&self) -> usize {
212        let mut len = 0;
213        self.for_each(|_| len += 6);
214        len
215    }
216
217    pub fn encode(&self, dst: &mut BytesMut) {
218        log::trace!("encoding SETTINGS; len={self:?}");
219
220        // Create & encode an appropriate frame head
221        let head = Head::new(Kind::Settings, self.flags.into(), StreamId::zero());
222        let payload_len = self.payload_len();
223        head.encode(payload_len, dst);
224
225        // Encode the settings
226        self.for_each(|setting| {
227            log::trace!("encoding setting; val={setting:?}");
228            setting.encode(dst);
229        });
230    }
231
232    fn for_each<F: FnMut(Setting)>(&self, mut f: F) {
233        if let Some(v) = self.header_table_size {
234            f(Setting::HeaderTableSize(v));
235        }
236
237        if let Some(v) = self.enable_push {
238            f(Setting::EnablePush(v));
239        }
240
241        if let Some(v) = self.max_concurrent_streams {
242            f(Setting::MaxConcurrentStreams(v));
243        }
244
245        if let Some(v) = self.initial_window_size {
246            f(Setting::InitialWindowSize(v));
247        }
248
249        if let Some(v) = self.max_frame_size {
250            f(Setting::MaxFrameSize(v));
251        }
252
253        if let Some(v) = self.max_header_list_size {
254            f(Setting::MaxHeaderListSize(v));
255        }
256
257        if let Some(v) = self.enable_connect_protocol {
258            f(Setting::EnableConnectProtocol(v));
259        }
260    }
261}
262
263impl From<Settings> for Frame {
264    fn from(src: Settings) -> Frame {
265        Frame::Settings(src)
266    }
267}
268
269impl fmt::Debug for Settings {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        let mut builder = f.debug_struct("Settings");
272        builder.field("flags", &self.flags);
273
274        self.for_each(|setting| match setting {
275            Setting::EnablePush(v) => {
276                builder.field("enable_push", &v);
277            }
278            Setting::HeaderTableSize(v) => {
279                builder.field("header_table_size", &v);
280            }
281            Setting::InitialWindowSize(v) => {
282                builder.field("initial_window_size", &v);
283            }
284            Setting::MaxConcurrentStreams(v) => {
285                builder.field("max_concurrent_streams", &v);
286            }
287            Setting::MaxFrameSize(v) => {
288                builder.field("max_frame_size", &v);
289            }
290            Setting::MaxHeaderListSize(v) => {
291                builder.field("max_header_list_size", &v);
292            }
293            Setting::EnableConnectProtocol(v) => {
294                builder.field("enable_connect_protocol", &v);
295            }
296        });
297
298        builder.finish()
299    }
300}
301
302// ===== impl Setting =====
303
304impl Setting {
305    /// Creates a new `Setting` with the correct variant corresponding to the
306    /// given setting id, based on the settings IDs defined in section
307    /// 6.5.2.
308    pub(super) const fn from_id(id: u16, val: u32) -> Option<Setting> {
309        match id {
310            1 => Some(Setting::HeaderTableSize(val)),
311            2 => Some(Setting::EnablePush(val)),
312            3 => Some(Setting::MaxConcurrentStreams(val)),
313            4 => Some(Setting::InitialWindowSize(val)),
314            5 => Some(Setting::MaxFrameSize(val)),
315            6 => Some(Setting::MaxHeaderListSize(val)),
316            8 => Some(Setting::EnableConnectProtocol(val)),
317            _ => None,
318        }
319    }
320
321    /// Creates a new `Setting` by parsing the given buffer of 6 bytes, which
322    /// contains the raw byte representation of the setting, according to the
323    /// "SETTINGS format" defined in section 6.5.1.
324    ///
325    /// The `raw` parameter should have length at least 6 bytes, since the
326    /// length of the raw setting is exactly 6 bytes.
327    ///
328    /// # Panics
329    ///
330    /// If given a buffer shorter than 6 bytes, the function will panic.
331    fn load(raw: &[u8]) -> Option<Setting> {
332        let id: u16 = (u16::from(raw[0]) << 8) | u16::from(raw[1]);
333        let val: u32 = unpack_octets_4!(raw, 2, u32);
334
335        Setting::from_id(id, val)
336    }
337
338    fn encode(self, dst: &mut BytesMut) {
339        let (kind, val) = match self {
340            Setting::HeaderTableSize(v) => (1, v),
341            Setting::EnablePush(v) => (2, v),
342            Setting::MaxConcurrentStreams(v) => (3, v),
343            Setting::InitialWindowSize(v) => (4, v),
344            Setting::MaxFrameSize(v) => (5, v),
345            Setting::MaxHeaderListSize(v) => (6, v),
346            Setting::EnableConnectProtocol(v) => (8, v),
347        };
348
349        dst.put_u16(kind);
350        dst.put_u32(val);
351    }
352}
353
354// ===== impl SettingsFlags =====
355
356impl SettingsFlags {
357    pub fn empty() -> SettingsFlags {
358        SettingsFlags(0)
359    }
360
361    pub fn load(bits: u8) -> SettingsFlags {
362        SettingsFlags(bits & ALL)
363    }
364
365    pub fn ack() -> SettingsFlags {
366        SettingsFlags(ACK)
367    }
368
369    pub fn is_ack(self) -> bool {
370        self.0 & ACK == ACK
371    }
372}
373
374impl From<SettingsFlags> for u8 {
375    #[inline]
376    fn from(src: SettingsFlags) -> u8 {
377        src.0
378    }
379}
380
381impl fmt::Debug for SettingsFlags {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        util::debug_flags(f, self.0)
384            .flag_if(self.is_ack(), "ACK")
385            .finish()
386    }
387}