Skip to main content

hreq_h2/proto/
settings.rs

1use crate::codec::{RecvError, UserError};
2use crate::error::Reason;
3use crate::frame;
4use crate::proto::*;
5use std::task::{Context, Poll};
6
7#[derive(Debug)]
8pub(crate) struct Settings {
9    /// Our local SETTINGS sync state with the remote.
10    local: Local,
11    /// Received SETTINGS frame pending processing. The ACK must be written to
12    /// the socket first then the settings applied **before** receiving any
13    /// further frames.
14    remote: Option<frame::Settings>,
15}
16
17#[derive(Debug)]
18enum Local {
19    /// We want to send these SETTINGS to the remote when the socket is ready.
20    ToSend(frame::Settings),
21    /// We have sent these SETTINGS and are waiting for the remote to ACK
22    /// before we apply them.
23    WaitingAck(frame::Settings),
24    /// Our local settings are in sync with the remote.
25    Synced,
26}
27
28impl Settings {
29    pub(crate) fn new(local: frame::Settings) -> Self {
30        Settings {
31            // We assume the initial local SETTINGS were flushed during
32            // the handshake process.
33            local: Local::WaitingAck(local),
34            remote: None,
35        }
36    }
37
38    pub(crate) fn recv_settings<T, B, C, P>(
39        &mut self,
40        frame: frame::Settings,
41        codec: &mut Codec<T, B>,
42        streams: &mut Streams<C, P>,
43    ) -> Result<(), RecvError>
44    where
45        T: AsyncWrite + Unpin,
46        B: Buf,
47        C: Buf,
48        P: Peer,
49    {
50        if frame.is_ack() {
51            match &self.local {
52                Local::WaitingAck(local) => {
53                    log::debug!("received settings ACK; applying {:?}", local);
54
55                    if let Some(max) = local.max_frame_size() {
56                        codec.set_max_recv_frame_size(max as usize);
57                    }
58
59                    if let Some(max) = local.max_header_list_size() {
60                        codec.set_max_recv_header_list_size(max as usize);
61                    }
62
63                    streams.apply_local_settings(local)?;
64                    self.local = Local::Synced;
65                    Ok(())
66                }
67                Local::ToSend(..) | Local::Synced => {
68                    // We haven't sent any SETTINGS frames to be ACKed, so
69                    // this is very bizarre! Remote is either buggy or malicious.
70                    proto_err!(conn: "received unexpected settings ack");
71                    Err(RecvError::Connection(Reason::PROTOCOL_ERROR))
72                }
73            }
74        } else {
75            // We always ACK before reading more frames, so `remote` should
76            // always be none!
77            assert!(self.remote.is_none());
78            self.remote = Some(frame);
79            Ok(())
80        }
81    }
82
83    pub(crate) fn send_settings(&mut self, frame: frame::Settings) -> Result<(), UserError> {
84        assert!(!frame.is_ack());
85        match &self.local {
86            Local::ToSend(..) | Local::WaitingAck(..) => Err(UserError::SendSettingsWhilePending),
87            Local::Synced => {
88                log::trace!("queue to send local settings: {:?}", frame);
89                self.local = Local::ToSend(frame);
90                Ok(())
91            }
92        }
93    }
94
95    pub(crate) fn poll_send<T, B, C, P>(
96        &mut self,
97        cx: &mut Context,
98        dst: &mut Codec<T, B>,
99        streams: &mut Streams<C, P>,
100    ) -> Poll<Result<(), RecvError>>
101    where
102        T: AsyncWrite + Unpin,
103        B: Buf,
104        C: Buf,
105        P: Peer,
106    {
107        if let Some(settings) = &self.remote {
108            if !dst.poll_ready(cx)?.is_ready() {
109                return Poll::Pending;
110            }
111
112            // Create an ACK settings frame
113            let frame = frame::Settings::ack();
114
115            // Buffer the settings frame
116            dst.buffer(frame.into()).expect("invalid settings frame");
117
118            log::trace!("ACK sent; applying settings");
119
120            if let Some(val) = settings.header_table_size() {
121                dst.set_send_header_table_size(val as usize);
122            }
123
124            if let Some(val) = settings.max_frame_size() {
125                dst.set_max_send_frame_size(val as usize);
126            }
127
128            streams.apply_remote_settings(settings)?;
129        }
130
131        self.remote = None;
132
133        match &self.local {
134            Local::ToSend(settings) => {
135                if !dst.poll_ready(cx)?.is_ready() {
136                    return Poll::Pending;
137                }
138
139                // Buffer the settings frame
140                dst.buffer(settings.clone().into())
141                    .expect("invalid settings frame");
142                log::trace!("local settings sent; waiting for ack: {:?}", settings);
143
144                self.local = Local::WaitingAck(settings.clone());
145            }
146            Local::WaitingAck(..) | Local::Synced => {}
147        }
148
149        Poll::Ready(Ok(()))
150    }
151}