Debian Codegraph @

third_party/rust/neqo-http3/src/connection.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 collections::{BTreeSet, HashMap},
10 fmt::{self, Debug, Display, Formatter},
11 mem,
12 rc::Rc,
13 };
14
15 use neqo_common::{qdebug, qerror, qinfo, qtrace, qwarn, Decoder, Header, MessageType, Role};
16 use neqo_qpack::{decoder::QPackDecoder, encoder::QPackEncoder};
17 use neqo_transport::{
18 streams::SendOrder, AppError, CloseReason, Connection, DatagramTracking, State, StreamId,
19 StreamType, ZeroRttState,
20 };
21 use strum::Display;
22
23 use crate::{
24 client_events::Http3ClientEvents,
25 control_stream_local::ControlStreamLocal,
26 control_stream_remote::ControlStreamRemote,
27 features::extended_connect::{
28 webtransport_session::WebTransportSession,
29 webtransport_streams::{WebTransportRecvStream, WebTransportSendStream},
30 ExtendedConnectEvents, ExtendedConnectFeature, ExtendedConnectType,
31 },
32 frames::HFrame,
33 push_controller::PushController,
34 qpack_decoder_receiver::DecoderRecvStream,
35 qpack_encoder_receiver::EncoderRecvStream,
36 recv_message::{RecvMessage, RecvMessageInfo},
37 request_target::{AsRequestTarget, RequestTarget as _},
38 send_message::SendMessage,
39 settings::{HSettingType, HSettings, HttpZeroRttChecker},
40 stream_type_reader::NewStreamHeadReader,
41 CloseType, Error, Http3Parameters, Http3StreamType, HttpRecvStreamEvents, NewStreamType,
42 Priority, PriorityHandler, ReceiveOutput, RecvStream, RecvStreamEvents, Res, SendStream,
43 SendStreamEvents,
44 };
45
46 pub struct RequestDescription<'b, 't, T>
47 where
48 T: AsRequestTarget<'t> + ?Sized + Debug,
49 {
50 pub method: &'b str,
51 pub connect_type: Option<ExtendedConnectType>,
52 pub target: &'t T,
53 pub headers: &'b [Header],
54 pub priority: Priority,
55 }
56
57 #[derive(Display)]
58 pub enum WebTransportSessionAcceptAction {
59 Accept,
60 Reject(Vec<Header>),
61 }
62
63 #[derive(Debug)]
64 enum Http3RemoteSettingsState {
65 NotReceived,
66 Received(HSettings),
67 ZeroRtt(HSettings),
68 }
69
70 /// States:
71 /// - `Initializing`: this is the state during the QUIC handshake,
72 /// - `ZeroRtt`: 0-RTT has been enabled and is active
73 /// - Connected
74 /// - GoingAway(StreamId): The connection has received a `GOAWAY` frame
75 /// - Closing(CloseReason): The connection is closed. The closing has been initiated by this end of
76 /// the connection, e.g., the `CONNECTION_CLOSE` frame has been sent. In this state, the
77 /// connection waits a certain amount of time to retransmit the `CONNECTION_CLOSE` frame if
78 /// needed.
79 /// - Closed(CloseReason): This is the final close state: closing has been initialized by the peer
80 /// and an ack for the `CONNECTION_CLOSE` frame has been sent or the closing has been initiated by
81 /// this end of the connection and the ack for the `CONNECTION_CLOSE` has been received or the
82 /// waiting time has passed.
83 #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Clone)]
84 pub enum Http3State {
85 Initializing,
86 ZeroRtt,
87 Connected,
88 GoingAway(StreamId),
89 Closing(CloseReason),
90 Closed(CloseReason),
91 }
92
93 impl Http3State {
94 #[must_use]
95 pub const fn active(&self) -> bool {
96 matches!(self, Self::Connected | Self::GoingAway(_) | Self::ZeroRtt)
97 }
98 }
99
100 /**
101 # HTTP/3 core implementation
102
103 This is the core implementation of HTTP/3 protocol. It implements most of the features of the
104 protocol. `Http3Client` and `Http3ServerHandler` implement only client and server side behavior.
105
106 The API consists of:
107 - functions that correspond to the `Http3Client` and `Http3ServerHandler` API:
108 - `new`
109 - `close`
110 - `fetch` - only used by the client-side implementation
111 - `read_data`
112 - `stream_reset_send`
113 - `stream_stop_sending`
114 - `cancel_fetch`
115 - `stream_close_send`
116 - functions that correspond to [`WebTransport`](https://w3c.github.io/webtransport/) functions:
117 - `webtransport_create_session` - only used by the client-side implementation
118 - `webtransport_session_accept` - only used by the server-side implementation
119 - `webtransport_close_session`
120 - `webtransport_create_stream_local` - this function is called when an application wants to open
121 a new `WebTransport` stream. For example `Http3Client::webtransport_create_stream` will call
122 this function.
123 - `webtransport_create_stream_remote` - this is called when a `WebTransport` stream has been
124 opened by the peer and this function sets up the appropriate handler for the stream.
125 - functions that are called by `process_http3`
126 - `process_sending` - some send-streams are buffered streams(see the Streams section) and this
127 function is called to trigger sending of the buffer data.
128 - functions that are called to handle `ConnectionEvent`s:
129 - `add_new_stream`
130 - `handle_stream_readable`
131 - `handle_stream_reset`
132 - `handle_stream_stop_sending`
133 - `handle_state_change`
134 - `handle_zero_rtt_rejected`
135 - Additional functions:
136 - `set_features_listener`
137 - `stream_has_pending_data`
138 - `has_data_to_send`
139 - `add_streams`
140 - `add_recv_stream`
141 - `queue_control_frame`
142 - `queue_update_priority`
143 - `set_0rtt_settings`
144 - `get_settings`
145 - `state`
146 - `webtransport_enabled`
147
148 ## Streams
149
150 Each `Http3Connection` holds a list of stream handlers. Each send and receive-handler is registered in
151 `send_streams` and `recv_streams`. Unidirectional streams are registered only on one of the lists
152 and bidirectional streams are registered in both lists and the 2 handlers are independent, e.g. one
153 can be closed and removed and second may still be active.
154
155 The only streams that are not registered are the local control stream, local QPACK decoder stream,
156 and local QPACK encoder stream. These streams are send-streams and sending data on this stream is
157 handled a bit differently. This is done in the `process_sending` function, i.e. the control data is
158 sent first and QPACK data is sent after regular stream data is sent because this stream may have
159 new data only after regular streams are handled (TODO we may improve this a bit to send QPACK
160 commands before headers.)
161
162 There are the following types of streams:
163 - `Control`: there is only a receiver stream of this type and the handler is `ControlStreamRemote`.
164 - `Decoder`: there is only a receiver stream of this type and the handler is `DecoderRecvStream`.
165 - `Encoder`: there is only a receiver stream of this type and the handler is `EncoderRecvStream`.
166 - `NewStream`: there is only a receiver stream of this type and the handler is
167 `NewStreamHeadReader`.
168 - `Http`: `SendMessage` and `RecvMessage` handlers are responsible for this type of streams.
169 - `Push`: `RecvMessage` is responsible for this type of streams.
170 - `ExtendedConnect`: `WebTransportSession` is responsible sender and receiver handler.
171 - `WebTransport(StreamId)`: `WebTransportSendStream` and `WebTransportRecvStream` are responsible
172 sender and receiver handler.
173 - `Unknown`: These are all other stream types that are not unknown to the current implementation
174 and should be handled properly by the spec, e.g., in our implementation the streams are
175 reset.
176
177 The streams are registered in `send_streams` and `recv_streams` in following ways depending if they
178 are local or remote:
179 - local streams:
180 - all local stream will be registered with the appropriate handler.
181 - remote streams:
182 - all new incoming streams are registered with `NewStreamHeadReader`. This is triggered by
183 `ConnectionEvent::NewStream` and `add_new_stream` is called.
184 - reading from a `NewStreamHeadReader` stream, via the `receive` function, will decode a stream
185 type. `NewStreamHeadReader::receive` will return `ReceiveOutput::NewStream(_)` when a stream
186 type has been decoded. After this point the stream:
187 - will be regegistered with the appropriate handler,
188 - will be canceled if is an unknown stream type or
189 - the connection will fail if it is unallowed stream type (receiving HTTP request on the
190 client-side).
191
192 The output is handled in `handle_new_stream`, for control, qpack streams and partially
193 `WebTransport` streams, otherwise the output is handled by `Http3Client` and `Http3ServerHandler`.
194
195
196 ### Receiving data
197
198 Reading from a stream is triggered by `ConnectionEvent::RecvStreamReadable` events for the stream.
199 The receive handler is retrieved from `recv_streams` and its `RecvStream::receive` function is
200 called.
201
202 Receiving data on `Http` streams is also triggered by the `read_data` function.
203 `ConnectionEvent::RecvStreamReadable` events will trigger reading `HEADERS` frame and frame headers
204 for `DATA` frames which will produce `Http3ClientEvent` or `Http3ServerEvent` events. The content of
205 `DATA` frames is read by the application using the `read_data` function. The `read_data` function
206 may read frame headers for consecutive `DATA` frames.
207
208 On a `WebTransport(_)` stream data will be read only by the `read_data` function. The
209 `RecvStream::receive` function only produces an `Http3ClientEvent` or `Http3ServerEvent` event.
210
211 The `receive` and `read_data` functions may detect that the stream is done, e.g. FIN received. In
212 this case, the stream will be removed from the `recv_stream` register, see `remove_recv_stream`.
213
214 ### Sending data
215
216 All sender stream handlers have buffers. Data is first written into a buffer before being supplied
217 to the QUIC layer. All data except the `DATA` frame and `WebTransport(_)`’s payload are written
218 into the buffer. This includes stream type byte, e.g. `WEBTRANSPORT_STREAM` as well. In the case of
219 `Http` and `WebTransport(_)` applications can write directly to the QUIC layer using the
220 `send_data` function to avoid copying data. Sending data via the `send_data` function is only
221 possible if there is no buffered data.
222
223 If a stream has buffered data it will be registered in the `streams_with_pending_data` queue and
224 actual sending will be performed in the `process_sending` function call. (This is done in this way,
225 i.e. data is buffered first and then sent, for 2 reasons: in this way, sending will happen in a
226 single function, therefore error handling and clean up is easier and the QUIC layer may not be
227 able to accept all data and being able to buffer data is required in any case.)
228
229 The `send` and `send_data` functions may detect that the stream is closed and all outstanding data
230 has been transferred to the QUIC layer. In this case, the stream will be removed from the
231 `send_stream` register.
232
233 ### `ControlStreamRemote`
234
235 The `ControlStreamRemote` handler uses `FrameReader` to read and decode frames received on the
236 control frame. The `receive` returns `ReceiveOutput::ControlFrames(_)` with a list of control
237 frames read (the list may be empty). The control frames are handled by `Http3Connection` and/or by
238 `Http3Client` and `Http3ServerHandler`.
239
240 ### `DecoderRecvStream` and `EncoderRecvStream`
241
242 The `receive` functions of these handlers call corresponding `receive` functions of `QPackDecoder`
243 and `QPackDecoder`.
244
245 `DecoderRecvStream` returns `ReceiveOutput::UnblockedStreams(_)` that may contain a list of stream
246 ids that are unblocked by receiving qpack decoder commands. `Http3Connection` will handle this
247 output by calling `receive` for the listed stream ids.
248
249 `EncoderRecvStream` only returns `ReceiveOutput::NoOutput`.
250
251 Both handlers may return an error that will close the connection.
252
253 ### `NewStreamHeadReader`
254
255 A new incoming receiver stream registers a `NewStreamHeadReader` handler. This handler reads the
256 first bytes of a stream to detect a stream type. The `receive` function returns
257 `ReceiveOutput::NoOutput` if a stream type is still not known by reading the available stream data
258 or `ReceiveOutput::NewStream(_)`. The handling of the output is explained above.
259
260 ### `SendMessage` and `RecvMessage`
261
262 `RecvMessage::receive` only returns `ReceiveOutput::NoOutput`. It also have an event listener of
263 type `HttpRecvStreamEvents`. The listener is called when headers are ready, or data is ready, etc.
264
265 For example for `Http` stream the listener will produce `HeaderReady` and `DataReadable` events.
266
267 ### `WebTransportSession`
268
269 A `WebTransport` session is connected to a control stream that is in essence an HTTP transaction.
270 Therefore, `WebTransportSession` will internally use a `SendMessage` and `RecvMessage` handler to
271 handle parsing and sending of HTTP part of the control stream. When HTTP headers are exchanged,
272 `WebTransportSession` will take over handling of stream data. `WebTransportSession` sets
273 `WebTransportSessionListener` as the `RecvMessage` event listener.
274
275 `WebTransportSendStream` and `WebTransportRecvStream` are associated with a `WebTransportSession`
276 and they will be canceled if the session is closed. To be able to do this `WebTransportSession`
277 holds a list of its active streams and clean up is done in `remove_extended_connect`.
278
279 ### `WebTransportSendStream` and `WebTransportRecvStream`
280
281 `WebTransport` streams are associated with a session. `WebTransportSendStream` and
282 `WebTransportRecvStream` hold a reference to the session and are registered in the session upon
283 creation by `Http3Connection`. The `WebTransportSendStream` and `WebTransportRecvStream`
284 handlers will be unregistered from the session if they are closed, reset, or canceled.
285
286 The call to function `receive` may produce `Http3ClientEvent::DataReadable`. Actual reading of
287 data is done in the `read_data` function.
288 */
289 #[derive(Debug)]
290 pub struct Http3Connection {
291 role: Role,
292 state: Http3State,
293 local_params: Http3Parameters,
294 control_stream_local: ControlStreamLocal,
295 qpack_encoder: Rc<RefCell<QPackEncoder>>,
296 qpack_decoder: Rc<RefCell<QPackDecoder>>,
297 settings_state: Http3RemoteSettingsState,
298 streams_with_pending_data: BTreeSet<StreamId>,
299 send_streams: HashMap<StreamId, Box<dyn SendStream>>,
300 recv_streams: HashMap<StreamId, Box<dyn RecvStream>>,
301 webtransport: ExtendedConnectFeature,
302 }
303
304 impl Display for Http3Connection {
305 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
306 write!(f, "Http3 connection")
307 }
308 }
309
310 impl Http3Connection {
311 /// Create a new connection.
312 pub fn new(conn_params: Http3Parameters, role: Role) -> Self {
313 Self {
314 state: Http3State::Initializing,
315 control_stream_local: ControlStreamLocal::new(),
316 qpack_encoder: Rc::new(RefCell::new(QPackEncoder::new(
317 conn_params.get_qpack_settings(),
318 true,
319 ))),
320 qpack_decoder: Rc::new(RefCell::new(QPackDecoder::new(
321 conn_params.get_qpack_settings(),
322 ))),
323 webtransport: ExtendedConnectFeature::new(
324 ExtendedConnectType::WebTransport,
325 conn_params.get_webtransport(),
326 ),
327 local_params: conn_params,
328 settings_state: Http3RemoteSettingsState::NotReceived,
329 streams_with_pending_data: BTreeSet::new(),
330 send_streams: HashMap::new(),
331 recv_streams: HashMap::new(),
332 role,
333 }
334 }
335
336 /// This function is called when a not default feature needs to be negotiated. This is currently
337 /// only used for the `WebTransport` feature. The negotiation is done via the `SETTINGS` frame
338 /// and when the peer's `SETTINGS` frame has been received the listener will be called.
339 pub fn set_features_listener(&mut self, feature_listener: Http3ClientEvents) {
340 self.webtransport.set_listener(feature_listener);
341 }
342
343 /// This function creates and initializes, i.e. send stream type, the control and qpack
344 /// streams.
345 fn initialize_http3_connection(&mut self, conn: &mut Connection) -> Res<()> {
346 qdebug!("[{self}] Initialize the http3 connection");
347 self.control_stream_local.create(conn)?;
348
349 self.send_settings();
350 self.create_qpack_streams(conn)?;
351 Ok(())
352 }
353
354 fn send_settings(&mut self) {
355 qdebug!("[{self}] Send settings");
356 self.control_stream_local.queue_frame(&HFrame::Settings {
357 settings: HSettings::from(&self.local_params),
358 });
359 self.control_stream_local.queue_frame(&HFrame::Grease);
360 }
361
362 /// Save settings for adding to the session ticket.
363 pub(crate) fn save_settings(&self) -> Vec<u8> {
364 HttpZeroRttChecker::save(&self.local_params)
365 }
366
367 fn create_qpack_streams(&self, conn: &mut Connection) -> Res<()> {
368 qdebug!("[{self}] create_qpack_streams");
369 self.qpack_encoder
370 .borrow_mut()
371 .add_send_stream(conn.stream_create(StreamType::UniDi)?);
372 self.qpack_decoder
373 .borrow_mut()
374 .add_send_stream(conn.stream_create(StreamType::UniDi)?);
375 Ok(())
376 }
377
378 /// Inform an [`Http3Connection`] that a stream has data to send and that
379 /// [`SendStream::send`] should be called for the stream.
380 pub fn stream_has_pending_data(&mut self, stream_id: StreamId) {
381 self.streams_with_pending_data.insert(stream_id);
382 }
383
384 /// Return true if there is a stream that needs to send data.
385 pub fn has_data_to_send(&self) -> bool {
386 !self.streams_with_pending_data.is_empty()
387 }
388
389 /// This function calls the `send` function for all streams that have data to send. If a stream
390 /// has data to send it will be added to the `streams_with_pending_data` list.
391 ///
392 /// Control and QPACK streams are handled differently and are never added to the list.
393 fn send_non_control_streams(&mut self, conn: &mut Connection) -> Res<()> {
394 let to_send = mem::take(&mut self.streams_with_pending_data);
395 for stream_id in to_send {
396 let done = if let Some(s) = &mut self.send_streams.get_mut(&stream_id) {
397 s.send(conn)?;
398 if s.has_data_to_send() {
399 self.streams_with_pending_data.insert(stream_id);
400 }
401 s.done()
402 } else {
403 false
404 };
405 if done {
406 self.remove_send_stream(stream_id, conn);
407 }
408 }
409 Ok(())
410 }
411
412 /// Call `send` for all streams that need to send data. See explanation for the main structure
413 /// for more details.
414 pub fn process_sending(&mut self, conn: &mut Connection) -> Res<()> {
415 // check if control stream has data to send.
416 self.control_stream_local
417 .send(conn, &mut self.recv_streams)?;
418
419 self.send_non_control_streams(conn)?;
420
421 self.qpack_decoder.borrow_mut().send(conn)?;
422 match self.qpack_encoder.borrow_mut().send_encoder_updates(conn) {
423 Ok(())
424 | Err(neqo_qpack::Error::EncoderStreamBlocked | neqo_qpack::Error::DynamicTableFull) => {
425 }
426 Err(e) => return Err(Error::QpackError(e)),
427 }
428 Ok(())
429 }
430
431 /// We have a resumption token which remembers previous settings. Update the setting.
432 pub fn set_0rtt_settings(&mut self, conn: &mut Connection, settings: HSettings) -> Res<()> {
433 self.initialize_http3_connection(conn)?;
434 self.set_qpack_settings(&settings)?;
435 self.settings_state = Http3RemoteSettingsState::ZeroRtt(settings);
436 self.state = Http3State::ZeroRtt;
437 Ok(())
438 }
439
440 /// Returns the settings for a connection. This is used for creating a resumption token.
441 pub fn get_settings(&self) -> Option<HSettings> {
442 if let Http3RemoteSettingsState::Received(settings) = &self.settings_state {
443 Some(settings.clone())
444 } else {
445 None
446 }
447 }
448
449 /// This is called when a `ConnectionEvent::NewStream` event is received. This register the
450 /// stream with a `NewStreamHeadReader` handler.
451 pub fn add_new_stream(&mut self, stream_id: StreamId) {
452 qtrace!("[{self}] A new stream: {stream_id}");
453 self.recv_streams.insert(
454 stream_id,
455 Box::new(NewStreamHeadReader::new(stream_id, self.role)),
456 );
457 }
458
459 /// The function calls `receive` for a stream. It also deals with the outcome of a read by
460 /// calling `handle_stream_manipulation_output`.
461 fn stream_receive(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<ReceiveOutput> {
462 qtrace!("[{self}] Readable stream {stream_id}");
463
464 if let Some(recv_stream) = self.recv_streams.get_mut(&stream_id) {
465 let res = recv_stream.receive(conn);
466 return self
467 .handle_stream_manipulation_output(res, stream_id, conn)
468 .map(|(output, _)| output);
469 }
470 Ok(ReceiveOutput::NoOutput)
471 }
472
473 fn handle_unblocked_streams(
474 &mut self,
475 unblocked_streams: Vec<StreamId>,
476 conn: &mut Connection,
477 ) -> Res<()> {
478 for stream_id in unblocked_streams {
479 qdebug!("[{self}] Stream {stream_id} is unblocked");
480 if let Some(r) = self.recv_streams.get_mut(&stream_id) {
481 let res = r
482 .http_stream()
483 .ok_or(Error::HttpInternal(10))?
484 .header_unblocked(conn);
485 let res = self.handle_stream_manipulation_output(res, stream_id, conn)?;
486 debug_assert!(matches!(res, (ReceiveOutput::NoOutput, _)));
487 }
488 }
489 Ok(())
490 }
491
492 /// This function handles reading from all streams, i.e. control, qpack, request/response
493 /// stream and unidi stream that are still do not have a type.
494 /// The function cannot handle:
495 /// 1) a `Push(_)`, `Http` or `WebTransportStream(_)` stream
496 /// 2) frames `MaxPushId`, `PriorityUpdateRequest`, `PriorityUpdateRequestPush` or `Goaway` must
497 /// be handled by `Http3Client`/`Server`.
498 ///
499 /// The function returns `ReceiveOutput`.
500 pub fn handle_stream_readable(
501 &mut self,
502 conn: &mut Connection,
503 stream_id: StreamId,
504 ) -> Res<ReceiveOutput> {
505 let mut output = self.stream_receive(conn, stream_id)?;
506
507 if let ReceiveOutput::NewStream(stream_type) = output {
508 output = self.handle_new_stream(conn, stream_type, stream_id)?;
509 }
510
511 match output {
512 ReceiveOutput::UnblockedStreams(unblocked_streams) => {
513 self.handle_unblocked_streams(unblocked_streams, conn)?;
514 Ok(ReceiveOutput::NoOutput)
515 }
516 ReceiveOutput::ControlFrames(control_frames) => {
517 let mut rest = Vec::new();
518 for cf in control_frames {
519 if let Some(not_handled) = self.handle_control_frame(cf)? {
520 rest.push(not_handled);
521 }
522 }
523 Ok(ReceiveOutput::ControlFrames(rest))
524 }
525 ReceiveOutput::NewStream(
526 NewStreamType::Push(_)
527 | NewStreamType::Http(_)
528 | NewStreamType::WebTransportStream(_),
529 )
530 | ReceiveOutput::NoOutput => Ok(output),
531 ReceiveOutput::NewStream(_) => {
532 unreachable!("NewStream should have been handled already")
533 }
534 }
535 }
536
537 /// This is called when a RESET frame has been received.
538 pub fn handle_stream_reset(
539 &mut self,
540 stream_id: StreamId,
541 app_error: AppError,
542 conn: &mut Connection,
543 ) -> Res<()> {
544 qinfo!("[{self}] Handle a stream reset stream_id={stream_id} app_err={app_error}");
545
546 self.close_recv(stream_id, CloseType::ResetRemote(app_error), conn)
547 }
548
549 pub fn handle_stream_stop_sending(
550 &mut self,
551 stream_id: StreamId,
552 app_error: AppError,
553 conn: &mut Connection,
554 ) -> Res<()> {
555 qinfo!("[{self}] Handle stream_stop_sending stream_id={stream_id} app_err={app_error}");
556
557 if self.send_stream_is_critical(stream_id) {
558 return Err(Error::HttpClosedCriticalStream);
559 }
560
561 self.close_send(stream_id, CloseType::ResetRemote(app_error), conn);
562 Ok(())
563 }
564
565 /// This is called when `neqo_transport::Connection` state has been change to take proper
566 /// actions in the HTTP3 layer.
567 pub fn handle_state_change(&mut self, conn: &mut Connection, state: &State) -> Res<bool> {
568 qdebug!("[{self}] Handle state change {state:?}");
569 match state {
570 State::Handshaking => {
571 if self.role == Role::Server
572 && conn.zero_rtt_state() == ZeroRttState::AcceptedServer
573 {
574 self.state = Http3State::ZeroRtt;
575 self.initialize_http3_connection(conn)?;
576 Ok(true)
577 } else {
578 Ok(false)
579 }
580 }
581 State::Connected => {
582 debug_assert!(matches!(
583 self.state,
584 Http3State::Initializing | Http3State::ZeroRtt
585 ));
586 if self.state == Http3State::Initializing {
587 self.initialize_http3_connection(conn)?;
588 }
589 self.state = Http3State::Connected;
590 Ok(true)
591 }
592 State::Closing { error, .. } | State::Draining { error, .. } => {
593 if matches!(self.state, Http3State::Closing(_) | Http3State::Closed(_)) {
594 Ok(false)
595 } else {
596 self.state = Http3State::Closing(error.clone());
597 Ok(true)
598 }
599 }
600 State::Closed(error) => {
601 if matches!(self.state, Http3State::Closed(_)) {
602 Ok(false)
603 } else {
604 self.state = Http3State::Closed(error.clone());
605 Ok(true)
606 }
607 }
608 _ => Ok(false),
609 }
610 }
611
612 /// This is called when 0RTT has been reset to clear `send_streams`, `recv_streams` and
613 /// settings.
614 pub fn handle_zero_rtt_rejected(&mut self) -> Res<()> {
615 if self.state == Http3State::ZeroRtt {
616 self.state = Http3State::Initializing;
617 self.control_stream_local = ControlStreamLocal::new();
618 self.qpack_encoder = Rc::new(RefCell::new(QPackEncoder::new(
619 self.local_params.get_qpack_settings(),
620 true,
621 )));
622 self.qpack_decoder = Rc::new(RefCell::new(QPackDecoder::new(
623 self.local_params.get_qpack_settings(),
624 )));
625 self.settings_state = Http3RemoteSettingsState::NotReceived;
626 self.streams_with_pending_data.clear();
627 // TODO: investigate whether this code can automatically retry failed transactions.
628 self.send_streams.clear();
629 self.recv_streams.clear();
630 Ok(())
631 } else {
632 debug_assert!(false, "Zero rtt rejected in the wrong state");
633 Err(Error::HttpInternal(3))
634 }
635 }
636
637 pub fn handle_datagram(&mut self, datagram: &[u8]) {
638 let mut decoder = Decoder::new(datagram);
639 let session = decoder
640 .decode_varint()
641 .and_then(|id| self.recv_streams.get_mut(&StreamId::from(id * 4)))
642 .and_then(|stream| stream.webtransport());
643 if let Some(s) = session {
644 s.borrow_mut().datagram(decoder.decode_remainder().to_vec());
645 }
646 }
647
648 fn check_stream_exists(&self, stream_type: Http3StreamType) -> Res<()> {
649 if self
650 .recv_streams
651 .values()
652 .any(|c| c.stream_type() == stream_type)
653 {
654 Err(Error::HttpStreamCreation)
655 } else {
656 Ok(())
657 }
658 }
659
660 /// If the new stream is a control or QPACK stream, this function creates a proper handler
661 /// and perform a read.
662 /// if the new stream is a `Push(_)`, `Http` or `WebTransportStream(_)` stream, the function
663 /// returns `ReceiveOutput::NewStream(_)` and the caller will handle it.
664 /// If the stream is of a unknown type the stream will be closed.
665 fn handle_new_stream(
666 &mut self,
667 conn: &mut Connection,
668 stream_type: NewStreamType,
669 stream_id: StreamId,
670 ) -> Res<ReceiveOutput> {
671 match stream_type {
672 NewStreamType::Control => {
673 self.check_stream_exists(Http3StreamType::Control)?;
674 self.recv_streams
675 .insert(stream_id, Box::new(ControlStreamRemote::new(stream_id)));
676 }
677
678 NewStreamType::Push(push_id) => {
679 qinfo!("[{self}] A new push stream {stream_id} push_id:{push_id}");
680 }
681 NewStreamType::Decoder => {
682 qdebug!("[{self}] A new remote qpack encoder stream {stream_id}");
683 self.check_stream_exists(Http3StreamType::Decoder)?;
684 self.recv_streams.insert(
685 stream_id,
686 Box::new(DecoderRecvStream::new(
687 stream_id,
688 Rc::clone(&self.qpack_decoder),
689 )),
690 );
691 }
692 NewStreamType::Encoder => {
693 qdebug!("[{self}] A new remote qpack decoder stream {stream_id}");
694 self.check_stream_exists(Http3StreamType::Encoder)?;
695 self.recv_streams.insert(
696 stream_id,
697 Box::new(EncoderRecvStream::new(
698 stream_id,
699 Rc::clone(&self.qpack_encoder),
700 )),
701 );
702 }
703 NewStreamType::Http(_) => {
704 qinfo!("[{self}] A new http stream {stream_id}");
705 }
706 NewStreamType::WebTransportStream(session_id) => {
707 let session_exists = self
708 .send_streams
709 .get(&StreamId::from(session_id))
710 .is_some_and(|s| s.stream_type() == Http3StreamType::ExtendedConnect);
711 if !session_exists {
712 conn.stream_stop_sending(stream_id, Error::HttpStreamCreation.code())?;
713 return Ok(ReceiveOutput::NoOutput);
714 }
715 // Set incoming WebTransport streams to be fair (share bandwidth).
716 // We may call this with an invalid stream ID, so ignore that error.
717 match conn.stream_fairness(stream_id, true) {
718 Ok(()) | Err(neqo_transport::Error::InvalidStreamId) => (),
719 Err(e) => return Err(Error::from(e)),
720 }
721 qinfo!("[{self}] A new WebTransport stream {stream_id} for session {session_id}");
722 }
723 NewStreamType::Unknown => {
724 conn.stream_stop_sending(stream_id, Error::HttpStreamCreation.code())?;
725 }
726 }
727
728 match stream_type {
729 NewStreamType::Control | NewStreamType::Decoder | NewStreamType::Encoder => {
730 self.stream_receive(conn, stream_id)
731 }
732 NewStreamType::Push(_)
733 | NewStreamType::Http(_)
734 | NewStreamType::WebTransportStream(_) => Ok(ReceiveOutput::NewStream(stream_type)),
735 NewStreamType::Unknown => Ok(ReceiveOutput::NoOutput),
736 }
737 }
738
739 /// This is called when an application closes the connection.
740 pub fn close(&mut self, error: AppError) {
741 qdebug!("[{self}] Close connection error {error:?}");
742 self.state = Http3State::Closing(CloseReason::Application(error));
743 if (!self.send_streams.is_empty() || !self.recv_streams.is_empty()) && (error == 0) {
744 qwarn!("close(0) called when streams still active");
745 }
746 self.send_streams.clear();
747 self.recv_streams.clear();
748 }
749
750 /// This function will not handle the output of the function completely, but only
751 /// handle the indication that a stream is closed. There are 2 cases:
752 /// - an error occurred or
753 /// - the stream is done, i.e. the second value in `output` tuple is true if the stream is done
754 /// and can be removed from the `recv_streams`
755 ///
756 /// How it is handling `output`:
757 /// - if the stream is done, it removes the stream from `recv_streams`
758 /// - if the stream is not done and there is no error, return `output` and the caller will
759 /// handle it.
760 /// - in case of an error:
761 /// - if it is only a stream error and the stream is not critical, send `STOP_SENDING` frame,
762 /// remove the stream from `recv_streams` and inform the listener that the stream has been
763 /// reset.
764 /// - otherwise this is a connection error. In this case, propagate the error to the caller
765 /// that will handle it properly.
766 fn handle_stream_manipulation_output<U>(
767 &mut self,
768 output: Res<(U, bool)>,
769 stream_id: StreamId,
770 conn: &mut Connection,
771 ) -> Res<(U, bool)>
772 where
773 U: Default,
774 {
775 match &output {
776 Ok((_, true)) => {
777 self.remove_recv_stream(stream_id, conn);
778 }
779 Ok((_, false)) => {}
780 Err(e) => {
781 if e.stream_reset_error() && !self.recv_stream_is_critical(stream_id) {
782 drop(conn.stream_stop_sending(stream_id, e.code()));
783 self.close_recv(stream_id, CloseType::LocalError(e.code()), conn)?;
784 return Ok((U::default(), false));
785 }
786 }
787 }
788 output
789 }
790
791 fn create_fetch_headers<'b, 't, T>(request: &RequestDescription<'b, 't, T>) -> Res<Vec<Header>>
792 where
793 T: AsRequestTarget<'t> + ?Sized + Debug,
794 {
795 let target = request
796 .target
797 .as_request_target()
798 .map_err(|_| Error::InvalidRequestTarget)?;
799
800 // Transform pseudo-header fields
801 let mut final_headers = vec![
802 Header::new(":method", request.method),
803 Header::new(":scheme", target.scheme()),
804 Header::new(":authority", target.authority()),
805 Header::new(":path", target.path()),
806 ];
807 if let Some(conn_type) = request.connect_type {
808 final_headers.push(Header::new(":protocol", conn_type.string()));
809 }
810
811 final_headers.extend_from_slice(request.headers);
812 Ok(final_headers)
813 }
814
815 pub fn fetch<'b, 't, T>(
816 &mut self,
817 conn: &mut Connection,
818 send_events: Box<dyn SendStreamEvents>,
819 recv_events: Box<dyn HttpRecvStreamEvents>,
820 push_handler: Option<Rc<RefCell<PushController>>>,
821 request: &RequestDescription<'b, 't, T>,
822 ) -> Res<StreamId>
823 where
824 T: AsRequestTarget<'t> + ?Sized + Debug,
825 {
826 qinfo!(
827 "[{self}] Fetch method={} target: {:?}",
828 request.method,
829 request.target,
830 );
831 let id = self.create_bidi_transport_stream(conn)?;
832 self.fetch_with_stream(id, conn, send_events, recv_events, push_handler, request)?;
833 Ok(id)
834 }
835
836 fn create_bidi_transport_stream(&self, conn: &mut Connection) -> Res<StreamId> {
837 // Requests cannot be created when a connection is in states: Initializing, GoingAway,
838 // Closing and Closed.
839 match self.state() {
840 Http3State::GoingAway(..) | Http3State::Closing(..) | Http3State::Closed(..) => {
841 return Err(Error::AlreadyClosed)
842 }
843 Http3State::Initializing => return Err(Error::Unavailable),
844 _ => {}
845 }
846
847 let id = conn
848 .stream_create(StreamType::BiDi)
849 .map_err(|e| Error::map_stream_create_errors(&e))?;
850 conn.stream_keep_alive(id, true)?;
851 Ok(id)
852 }
853
854 fn fetch_with_stream<'b, 't, T>(
855 &mut self,
856 stream_id: StreamId,
857 conn: &mut Connection,
858 send_events: Box<dyn SendStreamEvents>,
859 recv_events: Box<dyn HttpRecvStreamEvents>,
860 push_handler: Option<Rc<RefCell<PushController>>>,
861 request: &RequestDescription<'b, 't, T>,
862 ) -> Res<()>
863 where
864 T: AsRequestTarget<'t> + ?Sized + Debug,
865 {
866 let final_headers = Self::create_fetch_headers(request)?;
867
868 let stream_type = if request.connect_type.is_some() {
869 Http3StreamType::ExtendedConnect
870 } else {
871 Http3StreamType::Http
872 };
873
874 let mut send_message = SendMessage::new(
875 MessageType::Request,
876 stream_type,
877 stream_id,
878 Rc::clone(&self.qpack_encoder),
879 send_events,
880 );
881
882 send_message
883 .http_stream()
884 .ok_or(Error::Internal)?
885 .send_headers(&final_headers, conn)?;
886
887 self.add_streams(
888 stream_id,
889 Box::new(send_message),
890 Box::new(RecvMessage::new(
891 &RecvMessageInfo {
892 message_type: MessageType::Response,
893 stream_type,
894 stream_id,
895 first_frame_type: None,
896 },
897 Rc::clone(&self.qpack_decoder),
898 recv_events,
899 push_handler,
900 PriorityHandler::new(false, request.priority),
901 )),
902 );
903
904 // Call immediately send so that at least headers get sent. This will make Firefox faster,
905 // since it can send request body immediately in most cases and does not need to do
906 // a complete process loop.
907 self.send_streams
908 .get_mut(&stream_id)
909 .ok_or(Error::InvalidStreamId)?
910 .send(conn)?;
911 Ok(())
912 }
913
914 /// Stream data are read directly into a buffer supplied as a parameter of this function to
915 /// avoid copying data.
916 ///
917 /// # Errors
918 ///
919 /// It returns an error if a stream does not exist or an error happens while reading a stream,
920 /// e.g. early close, protocol error, etc.
921 pub fn read_data(
922 &mut self,
923 conn: &mut Connection,
924 stream_id: StreamId,
925 buf: &mut [u8],
926 ) -> Res<(usize, bool)> {
927 qdebug!("[{self}] read_data from stream {stream_id}");
928 let res = self
929 .recv_streams
930 .get_mut(&stream_id)
931 .ok_or(Error::InvalidStreamId)?
932 .read_data(conn, buf);
933 self.handle_stream_manipulation_output(res, stream_id, conn)
934 }
935
936 /// This is called when an application resets a stream.
937 /// The application reset will close both sides.
938 pub fn stream_reset_send(
939 &mut self,
940 conn: &mut Connection,
941 stream_id: StreamId,
942 error: AppError,
943 ) -> Res<()> {
944 qinfo!("[{self}] Reset sending side of stream {stream_id} error={error}");
945
946 if self.send_stream_is_critical(stream_id) {
947 return Err(Error::InvalidStreamId);
948 }
949
950 self.close_send(stream_id, CloseType::ResetApp(error), conn);
951 conn.stream_reset_send(stream_id, error)?;
952 Ok(())
953 }
954
955 pub fn stream_stop_sending(
956 &mut self,
957 conn: &mut Connection,
958 stream_id: StreamId,
959 error: AppError,
960 ) -> Res<()> {
961 qinfo!("[{self}] Send stop sending for stream {stream_id} error={error}");
962 if self.recv_stream_is_critical(stream_id) {
963 return Err(Error::InvalidStreamId);
964 }
965
966 self.close_recv(stream_id, CloseType::ResetApp(error), conn)?;
967
968 // Stream may be already be closed and we may get an error here, but we do not care.
969 conn.stream_stop_sending(stream_id, error)?;
970 Ok(())
971 }
972
973 /// Set the stream `SendOrder`.
974 ///
975 /// # Errors
976 ///
977 /// Returns `InvalidStreamId` if the stream id doesn't exist
978 pub fn stream_set_sendorder(
979 conn: &mut Connection,
980 stream_id: StreamId,
981 sendorder: Option<SendOrder>,
982 ) -> Res<()> {
983 conn.stream_sendorder(stream_id, sendorder)
984 .map_err(|_| Error::InvalidStreamId)
985 }
986
987 /// Set the stream Fairness. Fair streams will share bandwidth with other
988 /// streams of the same sendOrder group (or the unordered group). Unfair streams
989 /// will give bandwidth preferentially to the lowest streamId with data to send.
990 ///
991 /// # Errors
992 ///
993 /// Returns `InvalidStreamId` if the stream id doesn't exist
994 pub fn stream_set_fairness(
995 conn: &mut Connection,
996 stream_id: StreamId,
997 fairness: bool,
998 ) -> Res<()> {
999 conn.stream_fairness(stream_id, fairness)
1000 .map_err(|_| Error::InvalidStreamId)
1001 }
1002
1003 pub fn cancel_fetch(
1004 &mut self,
1005 stream_id: StreamId,
1006 error: AppError,
1007 conn: &mut Connection,
1008 ) -> Res<()> {
1009 qinfo!("[{self}] cancel_fetch {stream_id} error={error}");
1010 let send_stream = self.send_streams.get(&stream_id);
1011 let recv_stream = self.recv_streams.get(&stream_id);
1012 match (send_stream, recv_stream) {
1013 (None, None) => return Err(Error::InvalidStreamId),
1014 (Some(s), None) => {
1015 if !matches!(
1016 s.stream_type(),
1017 Http3StreamType::Http | Http3StreamType::ExtendedConnect
1018 ) {
1019 return Err(Error::InvalidStreamId);
1020 }
1021 // Stream may be already be closed and we may get an error here, but we do not care.
1022 drop(self.stream_reset_send(conn, stream_id, error));
1023 }
1024 (None, Some(s)) => {
1025 if !matches!(
1026 s.stream_type(),
1027 Http3StreamType::Http
1028 | Http3StreamType::Push
1029 | Http3StreamType::ExtendedConnect
1030 ) {
1031 return Err(Error::InvalidStreamId);
1032 }
1033
1034 // Stream may be already be closed and we may get an error here, but we do not care.
1035 drop(self.stream_stop_sending(conn, stream_id, error));
1036 }
1037 (Some(s), Some(r)) => {
1038 debug_assert_eq!(s.stream_type(), r.stream_type());
1039 if !matches!(
1040 s.stream_type(),
1041 Http3StreamType::Http | Http3StreamType::ExtendedConnect
1042 ) {
1043 return Err(Error::InvalidStreamId);
1044 }
1045 // Stream may be already be closed and we may get an error here, but we do not care.
1046 drop(self.stream_reset_send(conn, stream_id, error));
1047 // Stream may be already be closed and we may get an error here, but we do not care.
1048 drop(self.stream_stop_sending(conn, stream_id, error));
1049 }
1050 }
1051 Ok(())
1052 }
1053
1054 /// This is called when an application wants to close the sending side of a stream.
1055 pub fn stream_close_send(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> {
1056 qdebug!("[{self}] Close the sending side for stream {stream_id}");
1057 debug_assert!(self.state.active());
1058 let send_stream = self
1059 .send_streams
1060 .get_mut(&stream_id)
1061 .ok_or(Error::InvalidStreamId)?;
1062 // The following function may return InvalidStreamId from the transport layer if the stream
1063 // has been closed already. It is ok to ignore it here.
1064 drop(send_stream.close(conn));
1065 if send_stream.done() {
1066 self.remove_send_stream(stream_id, conn);
1067 } else if send_stream.has_data_to_send() {
1068 self.streams_with_pending_data.insert(stream_id);
1069 }
1070 Ok(())
1071 }
1072
1073 pub fn webtransport_create_session<'x, 't: 'x, T>(
1074 &mut self,
1075 conn: &mut Connection,
1076 events: Box<dyn ExtendedConnectEvents>,
1077 target: &'t T,
1078 headers: &'t [Header],
1079 ) -> Res<StreamId>
1080 where
1081 T: AsRequestTarget<'x> + ?Sized + Debug,
1082 {
1083 qinfo!("[{self}] Create WebTransport");
1084 if !self.webtransport_enabled() {
1085 return Err(Error::Unavailable);
1086 }
1087
1088 let id = self.create_bidi_transport_stream(conn)?;
1089
1090 let extended_conn = Rc::new(RefCell::new(WebTransportSession::new(
1091 id,
1092 events,
1093 self.role,
1094 Rc::clone(&self.qpack_encoder),
1095 Rc::clone(&self.qpack_decoder),
1096 )));
1097 self.add_streams(
1098 id,
1099 Box::new(Rc::clone(&extended_conn)),
1100 Box::new(Rc::clone(&extended_conn)),
1101 );
1102
1103 let final_headers = Self::create_fetch_headers(&RequestDescription {
1104 method: "CONNECT",
1105 target,
1106 headers,
1107 connect_type: Some(ExtendedConnectType::WebTransport),
1108 priority: Priority::default(),
1109 })?;
1110 extended_conn
1111 .borrow_mut()
1112 .send_request(&final_headers, conn)?;
1113 self.streams_with_pending_data.insert(id);
1114 Ok(id)
1115 }
1116
1117 pub(crate) fn webtransport_session_accept(
1118 &mut self,
1119 conn: &mut Connection,
1120 stream_id: StreamId,
1121 events: Box<dyn ExtendedConnectEvents>,
1122 accept_res: &WebTransportSessionAcceptAction,
1123 ) -> Res<()> {
1124 qtrace!("Respond to WebTransport session with accept={accept_res}");
1125 if !self.webtransport_enabled() {
1126 return Err(Error::Unavailable);
1127 }
1128 let mut recv_stream = self.recv_streams.get_mut(&stream_id);
1129 if let Some(r) = &mut recv_stream {
1130 if !r
1131 .http_stream()
1132 .ok_or(Error::InvalidStreamId)?
1133 .extended_connect_wait_for_response()
1134 {
1135 return Err(Error::InvalidStreamId);
1136 }
1137 }
1138
1139 let send_stream = self.send_streams.get_mut(&stream_id);
1140 conn.stream_keep_alive(stream_id, true)?;
1141
1142 match (send_stream, recv_stream, accept_res) {
1143 (None, None, _) => Err(Error::InvalidStreamId),
1144 (None, Some(_), _) | (Some(_), None, _) => {
1145 // TODO this needs a better error
1146 self.cancel_fetch(stream_id, Error::HttpRequestRejected.code(), conn)?;
1147 Err(Error::InvalidStreamId)
1148 }
1149 (Some(s), Some(_r), WebTransportSessionAcceptAction::Reject(headers)) => {
1150 if s.http_stream()
1151 .ok_or(Error::InvalidStreamId)?
1152 .send_headers(headers, conn)
1153 .is_ok()
1154 {
1155 drop(self.stream_close_send(conn, stream_id));
1156 // TODO issue 1294: add a timer to clean up the recv_stream if the peer does not
1157 // do that in a short time.
1158 self.streams_with_pending_data.insert(stream_id);
1159 } else {
1160 self.cancel_fetch(stream_id, Error::HttpRequestRejected.code(), conn)?;
1161 }
1162 Ok(())
1163 }
1164 (Some(s), Some(_r), WebTransportSessionAcceptAction::Accept) => {
1165 if s.http_stream()
1166 .ok_or(Error::InvalidStreamId)?
1167 .send_headers(&[Header::new(":status", "200")], conn)
1168 .is_ok()
1169 {
1170 let extended_conn =
1171 Rc::new(RefCell::new(WebTransportSession::new_with_http_streams(
1172 stream_id,
1173 events,
1174 self.role,
1175 self.recv_streams
1176 .remove(&stream_id)
1177 .ok_or(Error::Internal)?,
1178 self.send_streams
1179 .remove(&stream_id)
1180 .ok_or(Error::Internal)?,
1181 )?));
1182 self.add_streams(
1183 stream_id,
1184 Box::new(Rc::clone(&extended_conn)),
1185 Box::new(extended_conn),
1186 );
1187 self.streams_with_pending_data.insert(stream_id);
1188 } else {
1189 self.cancel_fetch(stream_id, Error::HttpRequestRejected.code(), conn)?;
1190 return Err(Error::InvalidStreamId);
1191 }
1192 Ok(())
1193 }
1194 }
1195 }
1196
1197 pub(crate) fn webtransport_close_session(
1198 &mut self,
1199 conn: &mut Connection,
1200 session_id: StreamId,
1201 error: u32,
1202 message: &str,
1203 ) -> Res<()> {
1204 qtrace!("Close WebTransport session {session_id:?}");
1205 let send_stream = self
1206 .send_streams
1207 .get_mut(&session_id)
1208 .ok_or(Error::InvalidStreamId)?;
1209 if send_stream.stream_type() != Http3StreamType::ExtendedConnect {
1210 return Err(Error::InvalidStreamId);
1211 }
1212
1213 send_stream.close_with_message(conn, error, message)?;
1214 if send_stream.done() {
1215 self.remove_send_stream(session_id, conn);
1216 } else if send_stream.has_data_to_send() {
1217 self.streams_with_pending_data.insert(session_id);
1218 }
1219 Ok(())
1220 }
1221
1222 pub fn webtransport_create_stream_local(
1223 &mut self,
1224 conn: &mut Connection,
1225 session_id: StreamId,
1226 stream_type: StreamType,
1227 send_events: Box<dyn SendStreamEvents>,
1228 recv_events: Box<dyn RecvStreamEvents>,
1229 ) -> Res<StreamId> {
1230 qtrace!("Create new WebTransport stream session={session_id} type={stream_type:?}");
1231
1232 let wt = self
1233 .recv_streams
1234 .get(&session_id)
1235 .ok_or(Error::InvalidStreamId)?
1236 .webtransport()
1237 .ok_or(Error::InvalidStreamId)?;
1238 if !wt.borrow().is_active() {
1239 return Err(Error::InvalidStreamId);
1240 }
1241
1242 let stream_id = conn
1243 .stream_create(stream_type)
1244 .map_err(|e| Error::map_stream_create_errors(&e))?;
1245 // Set outgoing WebTransport streams to be fair (share bandwidth)
1246 conn.stream_fairness(stream_id, true)?;
1247
1248 self.webtransport_create_stream_internal(
1249 wt,
1250 stream_id,
1251 session_id,
1252 send_events,
1253 recv_events,
1254 true,
1255 )?;
1256 Ok(stream_id)
1257 }
1258
1259 pub fn webtransport_create_stream_remote(
1260 &mut self,
1261 session_id: StreamId,
1262 stream_id: StreamId,
1263 send_events: Box<dyn SendStreamEvents>,
1264 recv_events: Box<dyn RecvStreamEvents>,
1265 ) -> Res<()> {
1266 qtrace!("Create new WebTransport stream session={session_id} stream_id={stream_id}");
1267
1268 let wt = self
1269 .recv_streams
1270 .get(&session_id)
1271 .ok_or(Error::InvalidStreamId)?
1272 .webtransport()
1273 .ok_or(Error::InvalidStreamId)?;
1274
1275 self.webtransport_create_stream_internal(
1276 wt,
1277 stream_id,
1278 session_id,
1279 send_events,
1280 recv_events,
1281 false,
1282 )?;
1283 Ok(())
1284 }
1285
1286 fn webtransport_create_stream_internal(
1287 &mut self,
1288 webtransport_session: Rc<RefCell<WebTransportSession>>,
1289 stream_id: StreamId,
1290 session_id: StreamId,
1291 send_events: Box<dyn SendStreamEvents>,
1292 recv_events: Box<dyn RecvStreamEvents>,
1293 local: bool,
1294 ) -> Res<()> {
1295 webtransport_session.borrow_mut().add_stream(stream_id)?;
1296 if stream_id.stream_type() == StreamType::UniDi {
1297 if local {
1298 self.send_streams.insert(
1299 stream_id,
1300 Box::new(WebTransportSendStream::new(
1301 stream_id,
1302 session_id,
1303 send_events,
1304 webtransport_session,
1305 true,
1306 )),
1307 );
1308 } else {
1309 self.recv_streams.insert(
1310 stream_id,
1311 Box::new(WebTransportRecvStream::new(
1312 stream_id,
1313 session_id,
1314 recv_events,
1315 webtransport_session,
1316 )),
1317 );
1318 }
1319 } else {
1320 self.add_streams(
1321 stream_id,
1322 Box::new(WebTransportSendStream::new(
1323 stream_id,
1324 session_id,
1325 send_events,
1326 Rc::clone(&webtransport_session),
1327 local,
1328 )),
1329 Box::new(WebTransportRecvStream::new(
1330 stream_id,
1331 session_id,
1332 recv_events,
1333 webtransport_session,
1334 )),
1335 );
1336 }
1337 Ok(())
1338 }
1339
1340 pub fn webtransport_send_datagram(
1341 &mut self,
1342 session_id: StreamId,
1343 conn: &mut Connection,
1344 buf: &[u8],
1345 id: impl Into<DatagramTracking>,
1346 ) -> Res<()> {
1347 self.recv_streams
1348 .get_mut(&session_id)
1349 .ok_or(Error::InvalidStreamId)?
1350 .webtransport()
1351 .ok_or(Error::InvalidStreamId)?
1352 .borrow_mut()
1353 .send_datagram(conn, buf, id)
1354 }
1355
1356 /// If the control stream has received frames `MaxPushId`, `Goaway`, `PriorityUpdateRequest` or
1357 /// `PriorityUpdateRequestPush` which handling is specific to the client and server, we must
1358 /// give them to the specific client/server handler.
1359 fn handle_control_frame(&mut self, f: HFrame) -> Res<Option<HFrame>> {
1360 qdebug!("[{self}] Handle a control frame {f:?}");
1361 if !matches!(f, HFrame::Settings { .. })
1362 && !matches!(
1363 self.settings_state,
1364 Http3RemoteSettingsState::Received { .. }
1365 )
1366 {
1367 return Err(Error::HttpMissingSettings);
1368 }
1369 match f {
1370 HFrame::Settings { settings } => {
1371 self.handle_settings(settings)?;
1372 Ok(None)
1373 }
1374 HFrame::Goaway { .. }
1375 | HFrame::MaxPushId { .. }
1376 | HFrame::CancelPush { .. }
1377 | HFrame::PriorityUpdateRequest { .. }
1378 | HFrame::PriorityUpdatePush { .. } => Ok(Some(f)),
1379 _ => Err(Error::HttpFrameUnexpected),
1380 }
1381 }
1382
1383 fn set_qpack_settings(&self, settings: &HSettings) -> Res<()> {
1384 let mut qpe = self.qpack_encoder.borrow_mut();
1385 qpe.set_max_capacity(settings.get(HSettingType::MaxTableCapacity))?;
1386 qpe.set_max_blocked_streams(settings.get(HSettingType::BlockedStreams))?;
1387 Ok(())
1388 }
1389
1390 fn handle_settings(&mut self, new_settings: HSettings) -> Res<()> {
1391 qdebug!("[{self}] Handle SETTINGS frame");
1392 match &self.settings_state {
1393 Http3RemoteSettingsState::NotReceived => {
1394 self.set_qpack_settings(&new_settings)?;
1395 self.webtransport.handle_settings(&new_settings);
1396 self.settings_state = Http3RemoteSettingsState::Received(new_settings);
1397 Ok(())
1398 }
1399 Http3RemoteSettingsState::ZeroRtt(settings) => {
1400 self.webtransport.handle_settings(&new_settings);
1401 let mut qpack_changed = false;
1402 for st in &[
1403 HSettingType::MaxHeaderListSize,
1404 HSettingType::MaxTableCapacity,
1405 HSettingType::BlockedStreams,
1406 ] {
1407 let zero_rtt_value = settings.get(*st);
1408 let new_value = new_settings.get(*st);
1409 if zero_rtt_value == new_value {
1410 continue;
1411 }
1412 if zero_rtt_value > new_value {
1413 qerror!(
1414 "[{self}] The new({new_value}) and the old value({zero_rtt_value}) of setting {st:?} do not match"
1415 );
1416 return Err(Error::HttpSettings);
1417 }
1418
1419 match st {
1420 HSettingType::MaxTableCapacity => {
1421 if zero_rtt_value != 0 {
1422 return Err(Error::QpackError(neqo_qpack::Error::DecoderStream));
1423 }
1424 qpack_changed = true;
1425 }
1426 HSettingType::BlockedStreams => qpack_changed = true,
1427 HSettingType::MaxHeaderListSize
1428 | HSettingType::EnableWebTransport
1429 | HSettingType::EnableH3Datagram => (),
1430 }
1431 }
1432 if qpack_changed {
1433 qdebug!("[{self}] Settings after zero rtt differ");
1434 self.set_qpack_settings(&(new_settings))?;
1435 }
1436 self.settings_state = Http3RemoteSettingsState::Received(new_settings);
1437 Ok(())
1438 }
1439 Http3RemoteSettingsState::Received { .. } => Err(Error::HttpFrameUnexpected),
1440 }
1441 }
1442
1443 /// Adds a new send and receive stream.
1444 pub fn add_streams(
1445 &mut self,
1446 stream_id: StreamId,
1447 send_stream: Box<dyn SendStream>,
1448 recv_stream: Box<dyn RecvStream>,
1449 ) {
1450 if send_stream.has_data_to_send() {
1451 self.streams_with_pending_data.insert(stream_id);
1452 }
1453 self.send_streams.insert(stream_id, send_stream);
1454 self.recv_streams.insert(stream_id, recv_stream);
1455 }
1456
1457 /// Add a new recv stream. This is used for push streams.
1458 pub fn add_recv_stream(&mut self, stream_id: StreamId, recv_stream: Box<dyn RecvStream>) {
1459 self.recv_streams.insert(stream_id, recv_stream);
1460 }
1461
1462 pub fn queue_control_frame(&mut self, frame: &HFrame) {
1463 self.control_stream_local.queue_frame(frame);
1464 }
1465
1466 pub fn queue_update_priority(&mut self, stream_id: StreamId, priority: Priority) -> Res<bool> {
1467 let stream = self
1468 .recv_streams
1469 .get_mut(&stream_id)
1470 .ok_or(Error::InvalidStreamId)?
1471 .http_stream()
1472 .ok_or(Error::InvalidStreamId)?;
1473
1474 if stream.maybe_update_priority(priority)? {
1475 self.control_stream_local.queue_update_priority(stream_id);
1476 Ok(true)
1477 } else {
1478 Ok(false)
1479 }
1480 }
1481
1482 fn recv_stream_is_critical(&self, stream_id: StreamId) -> bool {
1483 self.recv_streams.get(&stream_id).is_some_and(|r| {
1484 matches!(
1485 r.stream_type(),
1486 Http3StreamType::Control | Http3StreamType::Encoder | Http3StreamType::Decoder
1487 )
1488 })
1489 }
1490
1491 fn send_stream_is_critical(&self, stream_id: StreamId) -> bool {
1492 self.qpack_encoder
1493 .borrow()
1494 .local_stream_id()
1495 .iter()
1496 .chain(self.qpack_decoder.borrow().local_stream_id().iter())
1497 .chain(self.control_stream_local.stream_id().iter())
1498 .any(|id| stream_id == *id)
1499 }
1500
1501 fn close_send(&mut self, stream_id: StreamId, close_type: CloseType, conn: &mut Connection) {
1502 if let Some(mut s) = self.remove_send_stream(stream_id, conn) {
1503 s.handle_stop_sending(close_type);
1504 }
1505 }
1506
1507 fn close_recv(
1508 &mut self,
1509 stream_id: StreamId,
1510 close_type: CloseType,
1511 conn: &mut Connection,
1512 ) -> Res<()> {
1513 if let Some(mut s) = self.remove_recv_stream(stream_id, conn) {
1514 s.reset(close_type)?;
1515 }
1516 Ok(())
1517 }
1518
1519 fn remove_extended_connect(
1520 &mut self,
1521 wt: &Rc<RefCell<WebTransportSession>>,
1522 conn: &mut Connection,
1523 ) {
1524 let (recv, send) = wt.borrow_mut().take_sub_streams();
1525
1526 for id in recv {
1527 qtrace!("Remove the extended connect sub receiver stream {id}");
1528 // Use CloseType::ResetRemote so that an event will be sent. CloseType::LocalError would
1529 // have the same effect.
1530 if let Some(mut s) = self.recv_streams.remove(&id) {
1531 drop(s.reset(CloseType::ResetRemote(Error::HttpRequestCancelled.code())));
1532 }
1533 drop(conn.stream_stop_sending(id, Error::HttpRequestCancelled.code()));
1534 }
1535 for id in send {
1536 qtrace!("Remove the extended connect sub send stream {id}");
1537 if let Some(mut s) = self.send_streams.remove(&id) {
1538 s.handle_stop_sending(CloseType::ResetRemote(Error::HttpRequestCancelled.code()));
1539 }
1540 drop(conn.stream_reset_send(id, Error::HttpRequestCancelled.code()));
1541 }
1542 }
1543
1544 fn remove_recv_stream(
1545 &mut self,
1546 stream_id: StreamId,
1547 conn: &mut Connection,
1548 ) -> Option<Box<dyn RecvStream>> {
1549 let stream = self.recv_streams.remove(&stream_id);
1550 if let Some(s) = &stream {
1551 if s.stream_type() == Http3StreamType::ExtendedConnect {
1552 self.send_streams.remove(&stream_id)?;
1553 if let Some(wt) = s.webtransport() {
1554 self.remove_extended_connect(&wt, conn);
1555 }
1556 }
1557 }
1558 stream
1559 }
1560
1561 fn remove_send_stream(
1562 &mut self,
1563 stream_id: StreamId,
1564 conn: &mut Connection,
1565 ) -> Option<Box<dyn SendStream>> {
1566 let stream = self.send_streams.remove(&stream_id);
1567 if let Some(s) = &stream {
1568 if s.stream_type() == Http3StreamType::ExtendedConnect {
1569 if let Some(wt) = self.recv_streams.remove(&stream_id)?.webtransport() {
1570 self.remove_extended_connect(&wt, conn);
1571 }
1572 }
1573 }
1574 stream
1575 }
1576
1577 pub const fn webtransport_enabled(&self) -> bool {
1578 self.webtransport.enabled()
1579 }
1580
1581 #[must_use]
1582 pub const fn state(&self) -> &Http3State {
1583 &self.state
1584 }
1585
1586 pub fn set_state(&mut self, state: Http3State) {
1587 self.state = state;
1588 }
1589
1590 #[must_use]
1591 pub fn state_mut(&mut self) -> &mut Http3State {
1592 &mut self.state
1593 }
1594
1595 #[must_use]
1596 pub const fn qpack_encoder(&self) -> &Rc<RefCell<QPackEncoder>> {
1597 &self.qpack_encoder
1598 }
1599
1600 #[must_use]
1601 pub const fn qpack_decoder(&self) -> &Rc<RefCell<QPackDecoder>> {
1602 &self.qpack_decoder
1603 }
1604
1605 #[must_use]
1606 pub fn send_streams(&self) -> &HashMap<StreamId, Box<dyn SendStream>> {
1607 &self.send_streams
1608 }
1609
1610 #[must_use]
1611 pub fn send_streams_mut(&mut self) -> &mut HashMap<StreamId, Box<dyn SendStream>> {
1612 &mut self.send_streams
1613 }
1614
1615 #[must_use]
1616 pub fn recv_streams(&self) -> &HashMap<StreamId, Box<dyn RecvStream>> {
1617 &self.recv_streams
1618 }
1619
1620 #[must_use]
1621 pub fn recv_streams_mut(&mut self) -> &mut HashMap<StreamId, Box<dyn RecvStream>> {
1622 &mut self.recv_streams
1623 }
1624 }