Debian Codegraph @

third_party/rust/neqo-http3/src/send_message.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 cell::RefCell,
9 cmp::min,
10 fmt::{self, Debug, Display, Formatter},
11 num::NonZeroUsize,
12 rc::Rc,
13 };
14
15 use neqo_common::{qdebug, qtrace, Encoder, Header, MessageType};
16 use neqo_qpack::encoder::QPackEncoder;
17 use neqo_transport::{Connection, StreamId};
18
19 use crate::{
20 frames::HFrame,
21 headers_checks::{headers_valid, is_interim, trailers_valid},
22 BufferedStream, CloseType, Error, Http3StreamInfo, Http3StreamType, HttpSendStream, Res,
23 SendStream, SendStreamEvents, Stream,
24 };
25
26 const MIN_DATA_FRAME_SIZE: usize = 3; // Minimal DATA frame size: 2 (header) + 1 (payload)
27 const MAX_DATA_HEADER_SIZE_2: usize = (1 << 6) - 1; // Maximal amount of data with DATA frame header size 2
28 const MAX_DATA_HEADER_SIZE_2_LIMIT: usize = MAX_DATA_HEADER_SIZE_2 + 3; // 63 + 3 (size of the next buffer data frame header)
29 const MAX_DATA_HEADER_SIZE_3: usize = (1 << 14) - 1; // Maximal amount of data with DATA frame header size 3
30 const MAX_DATA_HEADER_SIZE_3_LIMIT: usize = MAX_DATA_HEADER_SIZE_3 + 5; // 16383 + 5 (size of the next buffer data frame header)
31 const MAX_DATA_HEADER_SIZE_5: usize = (1 << 30) - 1; // Maximal amount of data with DATA frame header size 3
32 const MAX_DATA_HEADER_SIZE_5_LIMIT: usize = MAX_DATA_HEADER_SIZE_5 + 9; // 1073741823 + 9 (size of the next buffer data frame header)
33
34 /// A HTTP message, request and response, consists of headers, optional data and an optional
35 /// trailer header block. This state machine does not reflect what was already sent to the
36 /// transport layer but only reflect what has been supplied to the `SendMessage`. It is
37 /// represented by the following states:
38 /// `WaitingForHeaders` - the headers have not been supplied yet. In this state only a
39 /// request/response header can be added. When headers are supplied
40 /// the state changes to `WaitingForData`. A response may contain
41 /// multiple messages only if all but the last one are informational(1xx)
42 /// responses. The informational responses can only contain headers,
43 /// therefore after an informational response is received the state
44 /// machine states in `WaitingForHeaders` state.
45 /// `WaitingForData` - in this state, data and trailers can be supplied. This state means that
46 /// a request or response header is already supplied.
47 /// `TrailersSet` - trailers have been supplied. At this stage no more data or headers can be
48 /// supply only a fin.
49 /// `Done` - in this state no more data or headers can be added. This state is entered when the
50 /// message is closed.
51 #[derive(Debug, PartialEq)]
52 enum MessageState {
53 WaitingForHeaders,
54 WaitingForData,
55 TrailersSet,
56 Done,
57 }
58
59 impl MessageState {
60 fn new_headers(&mut self, headers: &[Header], message_type: MessageType) -> Res<()> {
61 match &self {
62 Self::WaitingForHeaders => {
63 // This is only a debug assertion because we expect that application will
64 // do the right thing here and performing the check costs.
65 debug_assert!(headers_valid(headers, message_type).is_ok());
66 match message_type {
67 MessageType::Request => {
68 *self = Self::WaitingForData;
69 }
70 MessageType::Response => {
71 if !is_interim(headers)? {
72 *self = Self::WaitingForData;
73 }
74 }
75 }
76 Ok(())
77 }
78 Self::WaitingForData => {
79 trailers_valid(headers)?;
80 *self = Self::TrailersSet;
81 Ok(())
82 }
83 Self::TrailersSet | Self::Done => Err(Error::InvalidInput),
84 }
85 }
86
87 fn new_data(&self) -> Res<()> {
88 if &Self::WaitingForData == self {
89 Ok(())
90 } else {
91 Err(Error::InvalidInput)
92 }
93 }
94
95 fn fin(&mut self) -> Res<()> {
96 match &self {
97 Self::WaitingForHeaders | Self::Done => Err(Error::InvalidInput),
98 Self::WaitingForData | Self::TrailersSet => {
99 *self = Self::Done;
100 Ok(())
101 }
102 }
103 }
104
105 fn done(&self) -> bool {
106 &Self::Done == self
107 }
108 }
109
110 #[derive(Debug)]
111 pub struct SendMessage {
112 state: MessageState,
113 message_type: MessageType,
114 stream_type: Http3StreamType,
115 stream: BufferedStream,
116 encoder: Rc<RefCell<QPackEncoder>>,
117 conn_events: Box<dyn SendStreamEvents>,
118 }
119
120 impl SendMessage {
121 pub fn new(
122 message_type: MessageType,
123 stream_type: Http3StreamType,
124 stream_id: StreamId,
125 encoder: Rc<RefCell<QPackEncoder>>,
126 conn_events: Box<dyn SendStreamEvents>,
127 ) -> Self {
128 qdebug!("Create a request stream_id={stream_id}");
129 Self {
130 state: MessageState::WaitingForHeaders,
131 message_type,
132 stream_type,
133 stream: BufferedStream::new(stream_id),
134 encoder,
135 conn_events,
136 }
137 }
138
139 /// # Errors
140 ///
141 /// `ClosedCriticalStream` if the encoder stream is closed.
142 /// `InternalError` if an unexpected error occurred.
143 fn encode(
144 encoder: &mut QPackEncoder,
145 headers: &[Header],
146 conn: &mut Connection,
147 stream_id: StreamId,
148 ) -> Vec<u8> {
149 qdebug!("Encoding headers");
150 let header_block = encoder.encode_header_block(conn, headers, stream_id);
151 let hframe = HFrame::Headers {
152 header_block: header_block.to_vec(),
153 };
154 let mut d = Encoder::default();
155 hframe.encode(&mut d);
156 d.into()
157 }
158
159 fn stream_id(&self) -> StreamId {
160 Option::<StreamId>::from(&self.stream).expect("stream has ID")
161 }
162
163 fn get_stream_info(&self) -> Http3StreamInfo {
164 Http3StreamInfo::new(self.stream_id(), Http3StreamType::Http)
165 }
166 }
167
168 impl Stream for SendMessage {
169 fn stream_type(&self) -> Http3StreamType {
170 self.stream_type
171 }
172 }
173 impl SendStream for SendMessage {
174 fn send_data(&mut self, conn: &mut Connection, buf: &[u8]) -> Res<usize> {
175 qtrace!("[{self}] send_body: len={}", buf.len());
176
177 self.state.new_data()?;
178
179 self.stream.send_buffer(conn)?;
180 if self.stream.has_buffered_data() {
181 return Ok(0);
182 }
183 let available = conn
184 .stream_avail_send_space(self.stream_id())
185 .map_err(|e| Error::map_stream_send_errors(&e.into()))?;
186 if available < MIN_DATA_FRAME_SIZE {
187 // Setting this once, instead of every time the available send space
188 // is exhausted, would suffice. That said, function call should be
189 // cheap, thus not worth optimizing.
190 conn.stream_set_writable_event_low_watermark(
191 self.stream_id(),
192 NonZeroUsize::new(MIN_DATA_FRAME_SIZE).ok_or(Error::Internal)?,
193 )?;
194 return Ok(0);
195 }
196 let to_send = if available <= MAX_DATA_HEADER_SIZE_2_LIMIT {
197 // 63 + 3
198 min(min(buf.len(), available - 2), MAX_DATA_HEADER_SIZE_2)
199 } else if available <= MAX_DATA_HEADER_SIZE_3_LIMIT {
200 // 16383 + 5
201 min(min(buf.len(), available - 3), MAX_DATA_HEADER_SIZE_3)
202 } else if available <= MAX_DATA_HEADER_SIZE_5 {
203 // 1073741823 + 9
204 min(min(buf.len(), available - 5), MAX_DATA_HEADER_SIZE_5_LIMIT)
205 } else {
206 min(buf.len(), available - 9)
207 };
208
209 qdebug!("[{self}] send_request_body: available={available} to_send={to_send}");
210
211 let data_frame = HFrame::Data {
212 len: to_send as u64,
213 };
214 let mut enc = Encoder::default();
215 data_frame.encode(&mut enc);
216 let sent_fh = self
217 .stream
218 .send_atomic(conn, enc.as_ref())
219 .map_err(|e| Error::map_stream_send_errors(&e))?;
220 debug_assert!(sent_fh);
221
222 let sent = self
223 .stream
224 .send_atomic(conn, &buf[..to_send])
225 .map_err(|e| Error::map_stream_send_errors(&e))?;
226 debug_assert!(sent);
227 Ok(to_send)
228 }
229
230 fn done(&self) -> bool {
231 !self.stream.has_buffered_data() && self.state.done()
232 }
233
234 fn stream_writable(&self) {
235 if !self.stream.has_buffered_data() && !self.state.done() {
236 // DataWritable is just a signal for an application to try to write more data,
237 // if writing fails it is fine. Therefore we do not need to properly check
238 // whether more credits are available on the transport layer.
239 self.conn_events.data_writable(self.get_stream_info());
240 }
241 }
242
243 /// # Errors
244 ///
245 /// `InternalError` if an unexpected error occurred.
246 /// `InvalidStreamId` if the stream does not exist,
247 /// `AlreadyClosed` if the stream has already been closed.
248 /// `TransportStreamDoesNotExist` if the transport stream does not exist (this may happen if
249 /// `process_output` has not been called when needed, and HTTP3 layer has not picked up the
250 /// info that the stream has been closed.)
251 fn send(&mut self, conn: &mut Connection) -> Res<()> {
252 let sent = Error::map_error(self.stream.send_buffer(conn), Error::HttpInternal(5))?;
253
254 qtrace!("[{self}] {sent} bytes sent");
255 if !self.stream.has_buffered_data() {
256 if self.state.done() {
257 Error::map_error(
258 conn.stream_close_send(self.stream_id()),
259 Error::HttpInternal(6),
260 )?;
261 qtrace!("[{self}] done sending request");
262 } else {
263 // DataWritable is just a signal for an application to try to write more data,
264 // if writing fails it is fine. Therefore we do not need to properly check
265 // whether more credits are available on the transport layer.
266 self.conn_events.data_writable(self.get_stream_info());
267 }
268 }
269 Ok(())
270 }
271
272 // SendMessage owns headers and sends them. It may also own data for the server side.
273 // This method returns if they're still being sent. Request body (if any) is sent by
274 // http client afterwards using `send_request_body` after receiving DataWritable event.
275 fn has_data_to_send(&self) -> bool {
276 self.stream.has_buffered_data()
277 }
278
279 fn close(&mut self, conn: &mut Connection) -> Res<()> {
280 self.state.fin()?;
281 if !self.stream.has_buffered_data() {
282 conn.stream_close_send(self.stream_id())?;
283 }
284
285 self.conn_events
286 .send_closed(self.get_stream_info(), CloseType::Done);
287 Ok(())
288 }
289
290 fn handle_stop_sending(&mut self, close_type: CloseType) {
291 if !self.state.done() {
292 self.conn_events
293 .send_closed(self.get_stream_info(), close_type);
294 }
295 }
296
297 fn http_stream(&mut self) -> Option<&mut dyn HttpSendStream> {
298 Some(self)
299 }
300
301 fn send_data_atomic(&mut self, conn: &mut Connection, buf: &[u8]) -> Res<()> {
302 let data_frame = HFrame::Data {
303 len: buf.len() as u64,
304 };
305 let mut enc = Encoder::default();
306 data_frame.encode(&mut enc);
307 self.stream.buffer(enc.as_ref());
308 self.stream.buffer(buf);
309 _ = self.stream.send_buffer(conn)?;
310 Ok(())
311 }
312 }
313
314 impl HttpSendStream for SendMessage {
315 fn send_headers(&mut self, headers: &[Header], conn: &mut Connection) -> Res<()> {
316 self.state.new_headers(headers, self.message_type)?;
317 let buf = Self::encode(
318 &mut self.encoder.borrow_mut(),
319 headers,
320 conn,
321 self.stream_id(),
322 );
323 self.stream.buffer(&buf);
324 Ok(())
325 }
326
327 fn set_new_listener(&mut self, conn_events: Box<dyn SendStreamEvents>) {
328 self.stream_type = Http3StreamType::ExtendedConnect;
329 self.conn_events = conn_events;
330 }
331 }
332
333 impl Display for SendMessage {
334 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
335 write!(f, "SendMesage {}", self.stream_id())
336 }
337 }