| 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, |
| 10 |
fmt::{self, Display, Formatter}, |
| 11 |
mem, |
| 12 |
rc::Rc, |
| 13 |
}; |
| 14 |
|
| 15 |
use neqo_common::{qtrace, Encoder, Header, MessageType, Role}; |
| 16 |
use neqo_qpack::{QPackDecoder, QPackEncoder}; |
| 17 |
use neqo_transport::{Connection, DatagramTracking, StreamId}; |
| 18 |
|
| 19 |
use super::{ExtendedConnectEvents, ExtendedConnectType, SessionCloseReason}; |
| 20 |
use crate::{ |
| 21 |
frames::{FrameReader, StreamReaderRecvStreamWrapper, WebTransportFrame}, |
| 22 |
recv_message::{RecvMessage, RecvMessageInfo}, |
| 23 |
send_message::SendMessage, |
| 24 |
CloseType, Error, HFrame, Http3StreamInfo, Http3StreamType, HttpRecvStream, |
| 25 |
HttpRecvStreamEvents, Priority, PriorityHandler, ReceiveOutput, RecvStream, RecvStreamEvents, |
| 26 |
Res, SendStream, SendStreamEvents, Stream, |
| 27 |
}; |
| 28 |
|
| 29 |
#[derive(Debug, PartialEq)] |
| 30 |
enum SessionState { |
| 31 |
Negotiating, |
| 32 |
Active, |
| 33 |
FinPending, |
| 34 |
Done, |
| 35 |
} |
| 36 |
|
| 37 |
impl SessionState { |
| 38 |
pub const fn closing_state(&self) -> bool { |
| 39 |
matches!(self, Self::FinPending | Self::Done) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
#[derive(Debug)] |
| 44 |
pub struct WebTransportSession { |
| 45 |
control_stream_recv: Box<dyn RecvStream>, |
| 46 |
control_stream_send: Box<dyn SendStream>, |
| 47 |
stream_event_listener: Rc<RefCell<WebTransportSessionListener>>, |
| 48 |
session_id: StreamId, |
| 49 |
state: SessionState, |
| 50 |
frame_reader: FrameReader, |
| 51 |
events: Box<dyn ExtendedConnectEvents>, |
| 52 |
send_streams: BTreeSet<StreamId>, |
| 53 |
recv_streams: BTreeSet<StreamId>, |
| 54 |
role: Role, |
| 55 |
} |
| 56 |
|
| 57 |
impl Display for WebTransportSession { |
| 58 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 59 |
write!(f, "WebTransportSession session={}", self.session_id) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
impl WebTransportSession { |
| 64 |
#[must_use] |
| 65 |
pub fn new( |
| 66 |
session_id: StreamId, |
| 67 |
events: Box<dyn ExtendedConnectEvents>, |
| 68 |
role: Role, |
| 69 |
qpack_encoder: Rc<RefCell<QPackEncoder>>, |
| 70 |
qpack_decoder: Rc<RefCell<QPackDecoder>>, |
| 71 |
) -> Self { |
| 72 |
let stream_event_listener = Rc::new(RefCell::new(WebTransportSessionListener::default())); |
| 73 |
Self { |
| 74 |
control_stream_recv: Box::new(RecvMessage::new( |
| 75 |
&RecvMessageInfo { |
| 76 |
message_type: MessageType::Response, |
| 77 |
stream_type: Http3StreamType::ExtendedConnect, |
| 78 |
stream_id: session_id, |
| 79 |
first_frame_type: None, |
| 80 |
}, |
| 81 |
qpack_decoder, |
| 82 |
Box::new(Rc::clone(&stream_event_listener)), |
| 83 |
None, |
| 84 |
PriorityHandler::new(false, Priority::default()), |
| 85 |
)), |
| 86 |
control_stream_send: Box::new(SendMessage::new( |
| 87 |
MessageType::Request, |
| 88 |
Http3StreamType::ExtendedConnect, |
| 89 |
session_id, |
| 90 |
qpack_encoder, |
| 91 |
Box::new(Rc::clone(&stream_event_listener)), |
| 92 |
)), |
| 93 |
stream_event_listener, |
| 94 |
session_id, |
| 95 |
state: SessionState::Negotiating, |
| 96 |
frame_reader: FrameReader::new(), |
| 97 |
events, |
| 98 |
send_streams: BTreeSet::new(), |
| 99 |
recv_streams: BTreeSet::new(), |
| 100 |
role, |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
/// # Panics |
| 105 |
/// |
| 106 |
/// This function is only called with `RecvStream` and `SendStream` that also implement |
| 107 |
/// the http specific functions and `http_stream()` will never return `None`. |
| 108 |
pub fn new_with_http_streams( |
| 109 |
session_id: StreamId, |
| 110 |
events: Box<dyn ExtendedConnectEvents>, |
| 111 |
role: Role, |
| 112 |
mut control_stream_recv: Box<dyn RecvStream>, |
| 113 |
mut control_stream_send: Box<dyn SendStream>, |
| 114 |
) -> Res<Self> { |
| 115 |
let stream_event_listener = Rc::new(RefCell::new(WebTransportSessionListener::default())); |
| 116 |
control_stream_recv |
| 117 |
.http_stream() |
| 118 |
.ok_or(Error::Internal)? |
| 119 |
.set_new_listener(Box::new(Rc::clone(&stream_event_listener))); |
| 120 |
control_stream_send |
| 121 |
.http_stream() |
| 122 |
.ok_or(Error::Internal)? |
| 123 |
.set_new_listener(Box::new(Rc::clone(&stream_event_listener))); |
| 124 |
Ok(Self { |
| 125 |
control_stream_recv, |
| 126 |
control_stream_send, |
| 127 |
stream_event_listener, |
| 128 |
session_id, |
| 129 |
state: SessionState::Active, |
| 130 |
frame_reader: FrameReader::new(), |
| 131 |
events, |
| 132 |
send_streams: BTreeSet::new(), |
| 133 |
recv_streams: BTreeSet::new(), |
| 134 |
role, |
| 135 |
}) |
| 136 |
} |
| 137 |
|
| 138 |
/// # Errors |
| 139 |
/// |
| 140 |
/// The function can only fail if supplied headers are not valid http headers. |
| 141 |
/// |
| 142 |
/// # Panics |
| 143 |
/// |
| 144 |
/// `control_stream_send` implements the http specific functions and `http_stream()` |
| 145 |
/// will never return `None`. |
| 146 |
pub fn send_request(&mut self, headers: &[Header], conn: &mut Connection) -> Res<()> { |
| 147 |
self.control_stream_send |
| 148 |
.http_stream() |
| 149 |
.ok_or(Error::Internal)? |
| 150 |
.send_headers(headers, conn) |
| 151 |
} |
| 152 |
|
| 153 |
fn receive(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { |
| 154 |
qtrace!("[{self}] receive control data"); |
| 155 |
let (out, _) = self.control_stream_recv.receive(conn)?; |
| 156 |
debug_assert!(out == ReceiveOutput::NoOutput); |
| 157 |
self.maybe_check_headers()?; |
| 158 |
self.read_control_stream(conn)?; |
| 159 |
Ok((ReceiveOutput::NoOutput, self.state == SessionState::Done)) |
| 160 |
} |
| 161 |
|
| 162 |
fn header_unblocked(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { |
| 163 |
let (out, _) = self |
| 164 |
.control_stream_recv |
| 165 |
.http_stream() |
| 166 |
.ok_or(Error::Internal)? |
| 167 |
.header_unblocked(conn)?; |
| 168 |
debug_assert!(out == ReceiveOutput::NoOutput); |
| 169 |
self.maybe_check_headers()?; |
| 170 |
self.read_control_stream(conn)?; |
| 171 |
Ok((ReceiveOutput::NoOutput, self.state == SessionState::Done)) |
| 172 |
} |
| 173 |
|
| 174 |
fn maybe_update_priority(&mut self, priority: Priority) -> Res<bool> { |
| 175 |
self.control_stream_recv |
| 176 |
.http_stream() |
| 177 |
.ok_or(Error::Internal)? |
| 178 |
.maybe_update_priority(priority) |
| 179 |
} |
| 180 |
|
| 181 |
fn priority_update_frame(&mut self) -> Option<HFrame> { |
| 182 |
self.control_stream_recv |
| 183 |
.http_stream()? |
| 184 |
.priority_update_frame() |
| 185 |
} |
| 186 |
|
| 187 |
fn priority_update_sent(&mut self) -> Res<()> { |
| 188 |
self.control_stream_recv |
| 189 |
.http_stream() |
| 190 |
.ok_or(Error::Internal)? |
| 191 |
.priority_update_sent() |
| 192 |
} |
| 193 |
|
| 194 |
fn send(&mut self, conn: &mut Connection) -> Res<()> { |
| 195 |
self.control_stream_send.send(conn)?; |
| 196 |
if self.control_stream_send.done() { |
| 197 |
self.state = SessionState::Done; |
| 198 |
} |
| 199 |
Ok(()) |
| 200 |
} |
| 201 |
|
| 202 |
fn has_data_to_send(&self) -> bool { |
| 203 |
self.control_stream_send.has_data_to_send() |
| 204 |
} |
| 205 |
|
| 206 |
fn done(&self) -> bool { |
| 207 |
self.state == SessionState::Done |
| 208 |
} |
| 209 |
|
| 210 |
fn close(&mut self, close_type: CloseType) { |
| 211 |
if self.state.closing_state() { |
| 212 |
return; |
| 213 |
} |
| 214 |
qtrace!("ExtendedConnect close the session"); |
| 215 |
self.state = SessionState::Done; |
| 216 |
if !close_type.locally_initiated() { |
| 217 |
self.events.session_end( |
| 218 |
ExtendedConnectType::WebTransport, |
| 219 |
self.session_id, |
| 220 |
SessionCloseReason::from(close_type), |
| 221 |
None, |
| 222 |
); |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
/// # Panics |
| 227 |
/// |
| 228 |
/// This cannot panic because headers are checked before this function called. |
| 229 |
pub fn maybe_check_headers(&mut self) -> Res<()> { |
| 230 |
if SessionState::Negotiating != self.state { |
| 231 |
return Ok(()); |
| 232 |
} |
| 233 |
|
| 234 |
if let Some((headers, interim, fin)) = self.stream_event_listener.borrow_mut().get_headers() |
| 235 |
{ |
| 236 |
qtrace!("ExtendedConnect response headers {headers:?}, fin={fin}"); |
| 237 |
|
| 238 |
if interim { |
| 239 |
if fin { |
| 240 |
self.events.session_end( |
| 241 |
ExtendedConnectType::WebTransport, |
| 242 |
self.session_id, |
| 243 |
SessionCloseReason::Clean { |
| 244 |
error: 0, |
| 245 |
message: String::new(), |
| 246 |
}, |
| 247 |
Some(headers), |
| 248 |
); |
| 249 |
self.state = SessionState::Done; |
| 250 |
} |
| 251 |
} else { |
| 252 |
let status = headers |
| 253 |
.iter() |
| 254 |
.find_map(|h| { |
| 255 |
if h.name() == ":status" { |
| 256 |
h.value().parse::<u16>().ok() |
| 257 |
} else { |
| 258 |
None |
| 259 |
} |
| 260 |
}) |
| 261 |
.ok_or(Error::Internal)?; |
| 262 |
|
| 263 |
self.state = if (200..300).contains(&status) { |
| 264 |
if fin { |
| 265 |
self.events.session_end( |
| 266 |
ExtendedConnectType::WebTransport, |
| 267 |
self.session_id, |
| 268 |
SessionCloseReason::Clean { |
| 269 |
error: 0, |
| 270 |
message: String::new(), |
| 271 |
}, |
| 272 |
Some(headers), |
| 273 |
); |
| 274 |
SessionState::Done |
| 275 |
} else { |
| 276 |
self.events.session_start( |
| 277 |
ExtendedConnectType::WebTransport, |
| 278 |
self.session_id, |
| 279 |
status, |
| 280 |
headers, |
| 281 |
); |
| 282 |
SessionState::Active |
| 283 |
} |
| 284 |
} else { |
| 285 |
self.events.session_end( |
| 286 |
ExtendedConnectType::WebTransport, |
| 287 |
self.session_id, |
| 288 |
SessionCloseReason::Status(status), |
| 289 |
Some(headers), |
| 290 |
); |
| 291 |
SessionState::Done |
| 292 |
}; |
| 293 |
} |
| 294 |
} |
| 295 |
Ok(()) |
| 296 |
} |
| 297 |
|
| 298 |
pub fn add_stream(&mut self, stream_id: StreamId) -> Res<()> { |
| 299 |
if self.state == SessionState::Active { |
| 300 |
if stream_id.is_bidi() { |
| 301 |
self.send_streams.insert(stream_id); |
| 302 |
self.recv_streams.insert(stream_id); |
| 303 |
} else if stream_id.is_self_initiated(self.role) { |
| 304 |
self.send_streams.insert(stream_id); |
| 305 |
} else { |
| 306 |
self.recv_streams.insert(stream_id); |
| 307 |
} |
| 308 |
|
| 309 |
if !stream_id.is_self_initiated(self.role) { |
| 310 |
self.events |
| 311 |
.extended_connect_new_stream(Http3StreamInfo::new( |
| 312 |
stream_id, |
| 313 |
ExtendedConnectType::WebTransport.get_stream_type(self.session_id), |
| 314 |
))?; |
| 315 |
} |
| 316 |
} |
| 317 |
Ok(()) |
| 318 |
} |
| 319 |
|
| 320 |
pub fn remove_recv_stream(&mut self, stream_id: StreamId) { |
| 321 |
self.recv_streams.remove(&stream_id); |
| 322 |
} |
| 323 |
|
| 324 |
pub fn remove_send_stream(&mut self, stream_id: StreamId) { |
| 325 |
self.send_streams.remove(&stream_id); |
| 326 |
} |
| 327 |
|
| 328 |
#[must_use] |
| 329 |
pub const fn is_active(&self) -> bool { |
| 330 |
matches!(self.state, SessionState::Active) |
| 331 |
} |
| 332 |
|
| 333 |
pub fn take_sub_streams(&mut self) -> (BTreeSet<StreamId>, BTreeSet<StreamId>) { |
| 334 |
( |
| 335 |
mem::take(&mut self.recv_streams), |
| 336 |
mem::take(&mut self.send_streams), |
| 337 |
) |
| 338 |
} |
| 339 |
|
| 340 |
/// # Errors |
| 341 |
/// |
| 342 |
/// It may return an error if the frame is not correctly decoded. |
| 343 |
pub fn read_control_stream(&mut self, conn: &mut Connection) -> Res<()> { |
| 344 |
let (f, fin) = self |
| 345 |
.frame_reader |
| 346 |
.receive::<WebTransportFrame>(&mut StreamReaderRecvStreamWrapper::new( |
| 347 |
conn, |
| 348 |
&mut self.control_stream_recv, |
| 349 |
)) |
| 350 |
.map_err(|_| Error::HttpGeneralProtocolStream)?; |
| 351 |
qtrace!("[{self}] Received frame: {f:?} fin={fin}"); |
| 352 |
if let Some(WebTransportFrame::CloseSession { error, message }) = f { |
| 353 |
self.events.session_end( |
| 354 |
ExtendedConnectType::WebTransport, |
| 355 |
self.session_id, |
| 356 |
SessionCloseReason::Clean { error, message }, |
| 357 |
None, |
| 358 |
); |
| 359 |
self.state = if fin { |
| 360 |
SessionState::Done |
| 361 |
} else { |
| 362 |
SessionState::FinPending |
| 363 |
}; |
| 364 |
} else if fin { |
| 365 |
self.events.session_end( |
| 366 |
ExtendedConnectType::WebTransport, |
| 367 |
self.session_id, |
| 368 |
SessionCloseReason::Clean { |
| 369 |
error: 0, |
| 370 |
message: String::new(), |
| 371 |
}, |
| 372 |
None, |
| 373 |
); |
| 374 |
self.state = SessionState::Done; |
| 375 |
} |
| 376 |
Ok(()) |
| 377 |
} |
| 378 |
|
| 379 |
/// # Errors |
| 380 |
/// |
| 381 |
/// Return an error if the stream was closed on the transport layer, but that information is not |
| 382 |
/// yet consumed on the http/3 layer. |
| 383 |
pub fn close_session(&mut self, conn: &mut Connection, error: u32, message: &str) -> Res<()> { |
| 384 |
self.state = SessionState::Done; |
| 385 |
let close_frame = WebTransportFrame::CloseSession { |
| 386 |
error, |
| 387 |
message: message.to_string(), |
| 388 |
}; |
| 389 |
let mut encoder = Encoder::default(); |
| 390 |
close_frame.encode(&mut encoder); |
| 391 |
self.control_stream_send |
| 392 |
.send_data_atomic(conn, encoder.as_ref())?; |
| 393 |
self.control_stream_send.close(conn)?; |
| 394 |
self.state = if self.control_stream_send.done() { |
| 395 |
SessionState::Done |
| 396 |
} else { |
| 397 |
SessionState::FinPending |
| 398 |
}; |
| 399 |
Ok(()) |
| 400 |
} |
| 401 |
|
| 402 |
fn send_data(&mut self, conn: &mut Connection, buf: &[u8]) -> Res<usize> { |
| 403 |
self.control_stream_send.send_data(conn, buf) |
| 404 |
} |
| 405 |
|
| 406 |
/// # Errors |
| 407 |
/// |
| 408 |
/// Returns an error if the datagram exceeds the remote datagram size limit. |
| 409 |
pub fn send_datagram( |
| 410 |
&self, |
| 411 |
conn: &mut Connection, |
| 412 |
buf: &[u8], |
| 413 |
id: impl Into<DatagramTracking>, |
| 414 |
) -> Res<()> { |
| 415 |
qtrace!("[{self}] send_datagram state={:?}", self.state); |
| 416 |
if self.state == SessionState::Active { |
| 417 |
let mut dgram_data = Encoder::default(); |
| 418 |
dgram_data.encode_varint(self.session_id.as_u64() / 4); |
| 419 |
dgram_data.encode(buf); |
| 420 |
conn.send_datagram(dgram_data.into(), id)?; |
| 421 |
} else { |
| 422 |
debug_assert!(false); |
| 423 |
return Err(Error::Unavailable); |
| 424 |
} |
| 425 |
Ok(()) |
| 426 |
} |
| 427 |
|
| 428 |
pub fn datagram(&self, datagram: Vec<u8>) { |
| 429 |
if self.state == SessionState::Active { |
| 430 |
self.events.new_datagram(self.session_id, datagram); |
| 431 |
} |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
impl Stream for Rc<RefCell<WebTransportSession>> { |
| 436 |
fn stream_type(&self) -> Http3StreamType { |
| 437 |
Http3StreamType::ExtendedConnect |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
impl RecvStream for Rc<RefCell<WebTransportSession>> { |
| 442 |
fn receive(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { |
| 443 |
self.borrow_mut().receive(conn) |
| 444 |
} |
| 445 |
|
| 446 |
fn reset(&mut self, close_type: CloseType) -> Res<()> { |
| 447 |
self.borrow_mut().close(close_type); |
| 448 |
Ok(()) |
| 449 |
} |
| 450 |
|
| 451 |
fn http_stream(&mut self) -> Option<&mut dyn HttpRecvStream> { |
| 452 |
Some(self) |
| 453 |
} |
| 454 |
|
| 455 |
fn webtransport(&self) -> Option<Rc<RefCell<WebTransportSession>>> { |
| 456 |
Some(Self::clone(self)) |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
impl HttpRecvStream for Rc<RefCell<WebTransportSession>> { |
| 461 |
fn header_unblocked(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { |
| 462 |
self.borrow_mut().header_unblocked(conn) |
| 463 |
} |
| 464 |
|
| 465 |
fn maybe_update_priority(&mut self, priority: Priority) -> Res<bool> { |
| 466 |
self.borrow_mut().maybe_update_priority(priority) |
| 467 |
} |
| 468 |
|
| 469 |
fn priority_update_frame(&mut self) -> Option<HFrame> { |
| 470 |
self.borrow_mut().priority_update_frame() |
| 471 |
} |
| 472 |
|
| 473 |
fn priority_update_sent(&mut self) -> Res<()> { |
| 474 |
self.borrow_mut().priority_update_sent() |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
impl SendStream for Rc<RefCell<WebTransportSession>> { |
| 479 |
fn send(&mut self, conn: &mut Connection) -> Res<()> { |
| 480 |
self.borrow_mut().send(conn) |
| 481 |
} |
| 482 |
|
| 483 |
fn send_data(&mut self, conn: &mut Connection, buf: &[u8]) -> Res<usize> { |
| 484 |
self.borrow_mut().send_data(conn, buf) |
| 485 |
} |
| 486 |
|
| 487 |
fn has_data_to_send(&self) -> bool { |
| 488 |
self.borrow_mut().has_data_to_send() |
| 489 |
} |
| 490 |
|
| 491 |
fn stream_writable(&self) {} |
| 492 |
|
| 493 |
fn done(&self) -> bool { |
| 494 |
self.borrow_mut().done() |
| 495 |
} |
| 496 |
|
| 497 |
fn close(&mut self, conn: &mut Connection) -> Res<()> { |
| 498 |
self.borrow_mut().close_session(conn, 0, "") |
| 499 |
} |
| 500 |
|
| 501 |
fn close_with_message(&mut self, conn: &mut Connection, error: u32, message: &str) -> Res<()> { |
| 502 |
self.borrow_mut().close_session(conn, error, message) |
| 503 |
} |
| 504 |
|
| 505 |
fn handle_stop_sending(&mut self, close_type: CloseType) { |
| 506 |
self.borrow_mut().close(close_type); |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
#[derive(Debug, Default)] |
| 511 |
struct WebTransportSessionListener { |
| 512 |
headers: Option<(Vec<Header>, bool, bool)>, |
| 513 |
} |
| 514 |
|
| 515 |
impl WebTransportSessionListener { |
| 516 |
fn set_headers(&mut self, headers: Vec<Header>, interim: bool, fin: bool) { |
| 517 |
self.headers = Some((headers, interim, fin)); |
| 518 |
} |
| 519 |
|
| 520 |
pub fn get_headers(&mut self) -> Option<(Vec<Header>, bool, bool)> { |
| 521 |
mem::take(&mut self.headers) |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
impl RecvStreamEvents for Rc<RefCell<WebTransportSessionListener>> {} |
| 526 |
|
| 527 |
impl HttpRecvStreamEvents for Rc<RefCell<WebTransportSessionListener>> { |
| 528 |
fn header_ready( |
| 529 |
&self, |
| 530 |
_stream_info: Http3StreamInfo, |
| 531 |
headers: Vec<Header>, |
| 532 |
interim: bool, |
| 533 |
fin: bool, |
| 534 |
) { |
| 535 |
if !interim || fin { |
| 536 |
self.borrow_mut().set_headers(headers, interim, fin); |
| 537 |
} |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
impl SendStreamEvents for Rc<RefCell<WebTransportSessionListener>> {} |