| 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 |
fmt::{self, Display, Formatter}, |
| 9 |
rc::Rc, |
| 10 |
time::Instant, |
| 11 |
}; |
| 12 |
|
| 13 |
use neqo_common::{event::Provider as _, qdebug, qinfo, qtrace, Header, MessageType, Role}; |
| 14 |
use neqo_transport::{ |
| 15 |
AppError, Connection, ConnectionEvent, DatagramTracking, StreamId, StreamType, |
| 16 |
}; |
| 17 |
|
| 18 |
use crate::{ |
| 19 |
connection::{Http3Connection, Http3State, WebTransportSessionAcceptAction}, |
| 20 |
frames::HFrame, |
| 21 |
recv_message::{RecvMessage, RecvMessageInfo}, |
| 22 |
send_message::SendMessage, |
| 23 |
server_connection_events::{Http3ServerConnEvent, Http3ServerConnEvents}, |
| 24 |
Error, Http3Parameters, Http3StreamType, NewStreamType, Priority, PriorityHandler, |
| 25 |
ReceiveOutput, Res, |
| 26 |
}; |
| 27 |
|
| 28 |
#[derive(Debug)] |
| 29 |
pub struct Http3ServerHandler { |
| 30 |
base_handler: Http3Connection, |
| 31 |
events: Http3ServerConnEvents, |
| 32 |
needs_processing: bool, |
| 33 |
} |
| 34 |
|
| 35 |
impl Display for Http3ServerHandler { |
| 36 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 37 |
write!(f, "Http3 server connection") |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
impl Http3ServerHandler { |
| 42 |
pub(crate) fn new(http3_parameters: Http3Parameters) -> Self { |
| 43 |
Self { |
| 44 |
base_handler: Http3Connection::new(http3_parameters, Role::Server), |
| 45 |
events: Http3ServerConnEvents::default(), |
| 46 |
needs_processing: false, |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
#[must_use] |
| 51 |
pub fn state(&self) -> Http3State { |
| 52 |
self.base_handler.state().clone() |
| 53 |
} |
| 54 |
|
| 55 |
/// Supply a response for a request. |
| 56 |
/// |
| 57 |
/// # Errors |
| 58 |
/// |
| 59 |
/// `InvalidStreamId` if the stream does not exist, |
| 60 |
/// `AlreadyClosed` if the stream has already been closed. |
| 61 |
/// `TransportStreamDoesNotExist` if the transport stream does not exist (this may happen if |
| 62 |
/// `process_output` has not been called when needed, and HTTP3 layer has not picked up the |
| 63 |
/// info that the stream has been closed.) `InvalidInput` if an empty buffer has been |
| 64 |
/// supplied. |
| 65 |
pub(crate) fn send_data( |
| 66 |
&mut self, |
| 67 |
stream_id: StreamId, |
| 68 |
data: &[u8], |
| 69 |
conn: &mut Connection, |
| 70 |
) -> Res<usize> { |
| 71 |
let n = self |
| 72 |
.base_handler |
| 73 |
.send_streams_mut() |
| 74 |
.get_mut(&stream_id) |
| 75 |
.ok_or(Error::InvalidStreamId)? |
| 76 |
.send_data(conn, data)?; |
| 77 |
if n > 0 { |
| 78 |
self.base_handler.stream_has_pending_data(stream_id); |
| 79 |
} |
| 80 |
self.needs_processing = true; |
| 81 |
Ok(n) |
| 82 |
} |
| 83 |
|
| 84 |
/// Supply response heeaders for a request. |
| 85 |
pub(crate) fn send_headers( |
| 86 |
&mut self, |
| 87 |
stream_id: StreamId, |
| 88 |
headers: &[Header], |
| 89 |
conn: &mut Connection, |
| 90 |
) -> Res<()> { |
| 91 |
self.base_handler |
| 92 |
.send_streams_mut() |
| 93 |
.get_mut(&stream_id) |
| 94 |
.ok_or(Error::InvalidStreamId)? |
| 95 |
.http_stream() |
| 96 |
.ok_or(Error::InvalidStreamId)? |
| 97 |
.send_headers(headers, conn)?; |
| 98 |
self.base_handler.stream_has_pending_data(stream_id); |
| 99 |
self.needs_processing = true; |
| 100 |
Ok(()) |
| 101 |
} |
| 102 |
|
| 103 |
/// This is called when application is done sending a request. |
| 104 |
/// |
| 105 |
/// # Errors |
| 106 |
/// |
| 107 |
/// An error will be returned if stream does not exist. |
| 108 |
pub fn stream_close_send(&mut self, stream_id: StreamId, conn: &mut Connection) -> Res<()> { |
| 109 |
qdebug!("[{self}] Close sending side stream={stream_id}"); |
| 110 |
self.base_handler.stream_close_send(conn, stream_id)?; |
| 111 |
self.needs_processing = true; |
| 112 |
Ok(()) |
| 113 |
} |
| 114 |
|
| 115 |
/// An application may reset a stream(request). |
| 116 |
/// Both sides, sending and receiving side, will be closed. |
| 117 |
/// |
| 118 |
/// # Errors |
| 119 |
/// |
| 120 |
/// An error will be return if a stream does not exist. |
| 121 |
pub fn cancel_fetch( |
| 122 |
&mut self, |
| 123 |
stream_id: StreamId, |
| 124 |
error: AppError, |
| 125 |
conn: &mut Connection, |
| 126 |
) -> Res<()> { |
| 127 |
qinfo!("[{self}] cancel_fetch {stream_id} error={error}"); |
| 128 |
self.needs_processing = true; |
| 129 |
self.base_handler.cancel_fetch(stream_id, error, conn) |
| 130 |
} |
| 131 |
|
| 132 |
pub fn stream_stop_sending( |
| 133 |
&mut self, |
| 134 |
stream_id: StreamId, |
| 135 |
error: AppError, |
| 136 |
conn: &mut Connection, |
| 137 |
) -> Res<()> { |
| 138 |
qinfo!("[{self}] stream_stop_sending {stream_id} error={error}"); |
| 139 |
self.needs_processing = true; |
| 140 |
self.base_handler |
| 141 |
.stream_stop_sending(conn, stream_id, error) |
| 142 |
} |
| 143 |
|
| 144 |
pub fn stream_reset_send( |
| 145 |
&mut self, |
| 146 |
stream_id: StreamId, |
| 147 |
error: AppError, |
| 148 |
conn: &mut Connection, |
| 149 |
) -> Res<()> { |
| 150 |
qinfo!("[{self}] stream_reset_send {stream_id} error={error}"); |
| 151 |
self.needs_processing = true; |
| 152 |
self.base_handler.stream_reset_send(conn, stream_id, error) |
| 153 |
} |
| 154 |
|
| 155 |
/// Accept a `WebTransport` Session request |
| 156 |
pub(crate) fn webtransport_session_accept( |
| 157 |
&mut self, |
| 158 |
conn: &mut Connection, |
| 159 |
stream_id: StreamId, |
| 160 |
accept: &WebTransportSessionAcceptAction, |
| 161 |
) -> Res<()> { |
| 162 |
self.needs_processing = true; |
| 163 |
self.base_handler.webtransport_session_accept( |
| 164 |
conn, |
| 165 |
stream_id, |
| 166 |
Box::new(self.events.clone()), |
| 167 |
accept, |
| 168 |
) |
| 169 |
} |
| 170 |
|
| 171 |
/// Close `WebTransport` cleanly |
| 172 |
/// |
| 173 |
/// # Errors |
| 174 |
/// |
| 175 |
/// `InvalidStreamId` if the stream does not exist, |
| 176 |
/// `TransportStreamDoesNotExist` if the transport stream does not exist (this may happen if |
| 177 |
/// `process_output` has not been called when needed, and HTTP3 layer has not picked up the |
| 178 |
/// info that the stream has been closed.) `InvalidInput` if an empty buffer has been |
| 179 |
/// supplied. |
| 180 |
pub fn webtransport_close_session( |
| 181 |
&mut self, |
| 182 |
conn: &mut Connection, |
| 183 |
session_id: StreamId, |
| 184 |
error: u32, |
| 185 |
message: &str, |
| 186 |
) -> Res<()> { |
| 187 |
self.needs_processing = true; |
| 188 |
self.base_handler |
| 189 |
.webtransport_close_session(conn, session_id, error, message) |
| 190 |
} |
| 191 |
|
| 192 |
pub fn webtransport_create_stream( |
| 193 |
&mut self, |
| 194 |
conn: &mut Connection, |
| 195 |
session_id: StreamId, |
| 196 |
stream_type: StreamType, |
| 197 |
) -> Res<StreamId> { |
| 198 |
self.needs_processing = true; |
| 199 |
self.base_handler.webtransport_create_stream_local( |
| 200 |
conn, |
| 201 |
session_id, |
| 202 |
stream_type, |
| 203 |
Box::new(self.events.clone()), |
| 204 |
Box::new(self.events.clone()), |
| 205 |
) |
| 206 |
} |
| 207 |
|
| 208 |
pub fn webtransport_send_datagram( |
| 209 |
&mut self, |
| 210 |
conn: &mut Connection, |
| 211 |
session_id: StreamId, |
| 212 |
buf: &[u8], |
| 213 |
id: impl Into<DatagramTracking>, |
| 214 |
) -> Res<()> { |
| 215 |
self.needs_processing = true; |
| 216 |
self.base_handler |
| 217 |
.webtransport_send_datagram(session_id, conn, buf, id) |
| 218 |
} |
| 219 |
|
| 220 |
/// Process HTTTP3 layer. |
| 221 |
pub fn process_http3(&mut self, conn: &mut Connection, now: Instant) { |
| 222 |
qtrace!("[{self}] Process http3 internal"); |
| 223 |
if matches!(self.base_handler.state(), Http3State::Closed(..)) { |
| 224 |
return; |
| 225 |
} |
| 226 |
|
| 227 |
let res = self.check_connection_events(conn, now); |
| 228 |
if !self.check_result(conn, now, &res) && self.base_handler.state().active() { |
| 229 |
let res = self.base_handler.process_sending(conn); |
| 230 |
self.check_result(conn, now, &res); |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
/// Take the next available event. |
| 235 |
pub(crate) fn next_event(&self) -> Option<Http3ServerConnEvent> { |
| 236 |
self.events.next_event() |
| 237 |
} |
| 238 |
|
| 239 |
/// Whether this connection has events to process or data to send. |
| 240 |
pub(crate) fn should_be_processed(&mut self) -> bool { |
| 241 |
if self.needs_processing { |
| 242 |
self.needs_processing = false; |
| 243 |
return true; |
| 244 |
} |
| 245 |
self.base_handler.has_data_to_send() || self.events.has_events() |
| 246 |
} |
| 247 |
|
| 248 |
// This function takes the provided result and check for an error. |
| 249 |
// An error results in closing the connection. |
| 250 |
fn check_result<ERR>(&mut self, conn: &mut Connection, now: Instant, res: &Res<ERR>) -> bool { |
| 251 |
match &res { |
| 252 |
Err(e) => { |
| 253 |
self.close(conn, now, e); |
| 254 |
true |
| 255 |
} |
| 256 |
_ => false, |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
fn close(&mut self, conn: &mut Connection, now: Instant, err: &Error) { |
| 261 |
qinfo!("[{self}] Connection error: {err}"); |
| 262 |
conn.close(now, err.code(), format!("{err}")); |
| 263 |
self.base_handler.close(err.code()); |
| 264 |
self.events |
| 265 |
.connection_state_change(self.base_handler.state().clone()); |
| 266 |
} |
| 267 |
|
| 268 |
// If this return an error the connection must be closed. |
| 269 |
fn check_connection_events(&mut self, conn: &mut Connection, now: Instant) -> Res<()> { |
| 270 |
qtrace!("[{self}] Check connection events"); |
| 271 |
while let Some(e) = conn.next_event() { |
| 272 |
qdebug!("[{self}] check_connection_events - event {e:?}"); |
| 273 |
match e { |
| 274 |
ConnectionEvent::NewStream { stream_id } => { |
| 275 |
self.base_handler.add_new_stream(stream_id); |
| 276 |
} |
| 277 |
ConnectionEvent::RecvStreamReadable { stream_id } => { |
| 278 |
self.handle_stream_readable(conn, stream_id)?; |
| 279 |
} |
| 280 |
ConnectionEvent::RecvStreamReset { |
| 281 |
stream_id, |
| 282 |
app_error, |
| 283 |
} => { |
| 284 |
self.base_handler |
| 285 |
.handle_stream_reset(stream_id, app_error, conn)?; |
| 286 |
} |
| 287 |
ConnectionEvent::SendStreamStopSending { |
| 288 |
stream_id, |
| 289 |
app_error, |
| 290 |
} => self |
| 291 |
.base_handler |
| 292 |
.handle_stream_stop_sending(stream_id, app_error, conn)?, |
| 293 |
ConnectionEvent::StateChange(state) => { |
| 294 |
if self.base_handler.handle_state_change(conn, &state)? { |
| 295 |
if self.base_handler.state() == &Http3State::Connected { |
| 296 |
let settings = self.base_handler.save_settings(); |
| 297 |
conn.send_ticket(now, &settings)?; |
| 298 |
} |
| 299 |
self.events |
| 300 |
.connection_state_change(self.base_handler.state().clone()); |
| 301 |
} |
| 302 |
} |
| 303 |
ConnectionEvent::SendStreamWritable { stream_id } => { |
| 304 |
if let Some(s) = self.base_handler.send_streams_mut().get_mut(&stream_id) { |
| 305 |
s.stream_writable(); |
| 306 |
} |
| 307 |
} |
| 308 |
ConnectionEvent::Datagram(dgram) => self.base_handler.handle_datagram(&dgram), |
| 309 |
ConnectionEvent::AuthenticationNeeded |
| 310 |
| ConnectionEvent::EchFallbackAuthenticationNeeded { .. } |
| 311 |
| ConnectionEvent::ZeroRttRejected |
| 312 |
| ConnectionEvent::ResumptionToken(..) => return Err(Error::HttpInternal(4)), |
| 313 |
ConnectionEvent::SendStreamComplete { .. } |
| 314 |
| ConnectionEvent::SendStreamCreatable { .. } |
| 315 |
| ConnectionEvent::OutgoingDatagramOutcome { .. } |
| 316 |
| ConnectionEvent::IncomingDatagramDropped => {} |
| 317 |
} |
| 318 |
} |
| 319 |
Ok(()) |
| 320 |
} |
| 321 |
|
| 322 |
fn handle_stream_readable(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { |
| 323 |
match self.base_handler.handle_stream_readable(conn, stream_id)? { |
| 324 |
ReceiveOutput::NewStream(NewStreamType::Push(_)) => Err(Error::HttpStreamCreation), |
| 325 |
ReceiveOutput::NewStream(NewStreamType::Http(first_frame_type)) => { |
| 326 |
self.base_handler.add_streams( |
| 327 |
stream_id, |
| 328 |
Box::new(SendMessage::new( |
| 329 |
MessageType::Response, |
| 330 |
Http3StreamType::Http, |
| 331 |
stream_id, |
| 332 |
Rc::clone(self.base_handler.qpack_encoder()), |
| 333 |
Box::new(self.events.clone()), |
| 334 |
)), |
| 335 |
Box::new(RecvMessage::new( |
| 336 |
&RecvMessageInfo { |
| 337 |
message_type: MessageType::Request, |
| 338 |
stream_type: Http3StreamType::Http, |
| 339 |
stream_id, |
| 340 |
first_frame_type: Some(first_frame_type), |
| 341 |
}, |
| 342 |
Rc::clone(self.base_handler.qpack_decoder()), |
| 343 |
Box::new(self.events.clone()), |
| 344 |
None, |
| 345 |
PriorityHandler::new(false, Priority::default()), |
| 346 |
)), |
| 347 |
); |
| 348 |
let res = self.base_handler.handle_stream_readable(conn, stream_id)?; |
| 349 |
assert_eq!(ReceiveOutput::NoOutput, res); |
| 350 |
Ok(()) |
| 351 |
} |
| 352 |
ReceiveOutput::NewStream(NewStreamType::WebTransportStream(session_id)) => { |
| 353 |
self.base_handler.webtransport_create_stream_remote( |
| 354 |
StreamId::from(session_id), |
| 355 |
stream_id, |
| 356 |
Box::new(self.events.clone()), |
| 357 |
Box::new(self.events.clone()), |
| 358 |
)?; |
| 359 |
let res = self.base_handler.handle_stream_readable(conn, stream_id)?; |
| 360 |
assert_eq!(ReceiveOutput::NoOutput, res); |
| 361 |
Ok(()) |
| 362 |
} |
| 363 |
ReceiveOutput::ControlFrames(control_frames) => { |
| 364 |
for f in control_frames { |
| 365 |
match f { |
| 366 |
HFrame::MaxPushId { .. } => { |
| 367 |
// TODO implement push |
| 368 |
Ok(()) |
| 369 |
} |
| 370 |
HFrame::Goaway { .. } | HFrame::CancelPush { .. } => { |
| 371 |
Err(Error::HttpFrameUnexpected) |
| 372 |
} |
| 373 |
HFrame::PriorityUpdatePush { element_id, priority } => { |
| 374 |
// TODO: check if the element_id references a promised push stream or |
| 375 |
// is greater than the maximum Push ID. |
| 376 |
self.events.priority_update(StreamId::from(element_id), priority); |
| 377 |
Ok(()) |
| 378 |
} |
| 379 |
HFrame::PriorityUpdateRequest { element_id, priority } => { |
| 380 |
// check that the element_id references a request stream |
| 381 |
// within the client-sided bidirectional stream limit |
| 382 |
let element_stream_id = StreamId::new(element_id); |
| 383 |
if !element_stream_id.is_bidi() |
| 384 |
|| !element_stream_id.is_client_initiated() |
| 385 |
|| !conn.is_stream_id_allowed(element_stream_id) |
| 386 |
{ |
| 387 |
return Err(Error::HttpId) |
| 388 |
} |
| 389 |
|
| 390 |
self.events.priority_update(element_stream_id, priority); |
| 391 |
Ok(()) |
| 392 |
} |
| 393 |
_ => unreachable!( |
| 394 |
"we should only put MaxPushId, Goaway and PriorityUpdates into control_frames" |
| 395 |
), |
| 396 |
}?; |
| 397 |
} |
| 398 |
Ok(()) |
| 399 |
} |
| 400 |
_ => Ok(()), |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
/// Response data are read directly into a buffer supplied as a parameter of this function to |
| 405 |
/// avoid copying data. |
| 406 |
/// |
| 407 |
/// # Errors |
| 408 |
/// |
| 409 |
/// It returns an error if a stream does not exist or an error happen while reading a stream, |
| 410 |
/// e.g. early close, protocol error, etc. |
| 411 |
pub fn read_data( |
| 412 |
&mut self, |
| 413 |
conn: &mut Connection, |
| 414 |
now: Instant, |
| 415 |
stream_id: StreamId, |
| 416 |
buf: &mut [u8], |
| 417 |
) -> Res<(usize, bool)> { |
| 418 |
qdebug!("[{self}] read_data from stream {stream_id}"); |
| 419 |
let res = self.base_handler.read_data(conn, stream_id, buf); |
| 420 |
if let Err(e) = &res { |
| 421 |
if e.connection_error() { |
| 422 |
self.close(conn, now, e); |
| 423 |
} |
| 424 |
} |
| 425 |
res |
| 426 |
} |
| 427 |
} |