| 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 |
#![expect(clippy::unwrap_used, reason = "This is example code.")] |
| 8 |
|
| 9 |
//! An HTTP 3 client implementation. |
| 10 |
|
| 11 |
use std::{ |
| 12 |
cell::RefCell, |
| 13 |
collections::{HashMap, VecDeque}, |
| 14 |
fmt::Display, |
| 15 |
fs::File, |
| 16 |
io::{BufWriter, Write as _}, |
| 17 |
net::SocketAddr, |
| 18 |
path::PathBuf, |
| 19 |
rc::Rc, |
| 20 |
time::Instant, |
| 21 |
}; |
| 22 |
|
| 23 |
use neqo_common::{event::Provider, hex, qdebug, qerror, qinfo, qwarn, Datagram, Header}; |
| 24 |
use neqo_crypto::{AuthenticationStatus, ResumptionToken}; |
| 25 |
use neqo_http3::{Error, Http3Client, Http3ClientEvent, Http3Parameters, Http3State, Priority}; |
| 26 |
use neqo_transport::{ |
| 27 |
AppError, CloseReason, Connection, EmptyConnectionIdGenerator, Error as TransportError, Output, |
| 28 |
RandomConnectionIdGenerator, StreamId, |
| 29 |
}; |
| 30 |
use url::Url; |
| 31 |
|
| 32 |
use super::{get_output_file, qlog_new, Args, CloseState, Res}; |
| 33 |
use crate::{send_data::SendData, STREAM_IO_BUFFER_SIZE}; |
| 34 |
|
| 35 |
pub struct Handler<'a> { |
| 36 |
#[expect(clippy::struct_field_names, reason = "This name is more descriptive.")] |
| 37 |
url_handler: UrlHandler<'a>, |
| 38 |
token: Option<ResumptionToken>, |
| 39 |
output_read_data: bool, |
| 40 |
read_buffer: Vec<u8>, |
| 41 |
} |
| 42 |
|
| 43 |
impl<'a> Handler<'a> { |
| 44 |
pub(crate) fn new(url_queue: VecDeque<Url>, args: &'a Args) -> Self { |
| 45 |
let url_handler = UrlHandler { |
| 46 |
url_queue, |
| 47 |
handled_urls: Vec::new(), |
| 48 |
stream_handlers: HashMap::new(), |
| 49 |
all_paths: Vec::new(), |
| 50 |
args, |
| 51 |
}; |
| 52 |
|
| 53 |
Self { |
| 54 |
url_handler, |
| 55 |
token: None, |
| 56 |
output_read_data: args.output_read_data, |
| 57 |
read_buffer: vec![0; STREAM_IO_BUFFER_SIZE], |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
pub fn create_client( |
| 63 |
args: &Args, |
| 64 |
local_addr: SocketAddr, |
| 65 |
remote_addr: SocketAddr, |
| 66 |
hostname: &str, |
| 67 |
resumption_token: Option<ResumptionToken>, |
| 68 |
) -> Res<Http3Client> { |
| 69 |
let cid_generator: Rc<RefCell<dyn neqo_transport::ConnectionIdGenerator>> = if args.cid_len == 0 |
| 70 |
{ |
| 71 |
Rc::new(RefCell::new(EmptyConnectionIdGenerator::default())) |
| 72 |
} else { |
| 73 |
Rc::new(RefCell::new(RandomConnectionIdGenerator::new( |
| 74 |
args.cid_len.into(), |
| 75 |
))) |
| 76 |
}; |
| 77 |
let mut transport = Connection::new_client( |
| 78 |
hostname, |
| 79 |
&[&args.shared.alpn], |
| 80 |
cid_generator, |
| 81 |
local_addr, |
| 82 |
remote_addr, |
| 83 |
args.shared.quic_parameters.get(args.shared.alpn.as_str()), |
| 84 |
Instant::now(), |
| 85 |
)?; |
| 86 |
let ciphers = args.get_ciphers(); |
| 87 |
if !ciphers.is_empty() { |
| 88 |
transport.set_ciphers(&ciphers)?; |
| 89 |
} |
| 90 |
let mut client = Http3Client::new_with_conn( |
| 91 |
transport, |
| 92 |
Http3Parameters::default() |
| 93 |
.max_table_size_encoder(args.shared.max_table_size_encoder) |
| 94 |
.max_table_size_decoder(args.shared.max_table_size_decoder) |
| 95 |
.max_blocked_streams(args.shared.max_blocked_streams) |
| 96 |
.max_concurrent_push_streams(args.max_concurrent_push_streams), |
| 97 |
); |
| 98 |
|
| 99 |
let qlog = qlog_new(args, hostname, client.connection_id())?; |
| 100 |
client.set_qlog(qlog); |
| 101 |
if let Some(ech) = &args.ech { |
| 102 |
client.enable_ech(ech).expect("enable ECH"); |
| 103 |
} |
| 104 |
if let Some(token) = resumption_token { |
| 105 |
client |
| 106 |
.enable_resumption(Instant::now(), token) |
| 107 |
.expect("enable resumption"); |
| 108 |
} |
| 109 |
|
| 110 |
Ok(client) |
| 111 |
} |
| 112 |
|
| 113 |
impl TryFrom<Http3State> for CloseState { |
| 114 |
type Error = CloseReason; |
| 115 |
|
| 116 |
fn try_from(value: Http3State) -> Result<Self, Self::Error> { |
| 117 |
let (state, error) = match value { |
| 118 |
Http3State::Closing(error) => (Self::Closing, error), |
| 119 |
Http3State::Closed(error) => (Self::Closed, error), |
| 120 |
_ => return Ok(Self::NotClosing), |
| 121 |
}; |
| 122 |
|
| 123 |
if error.is_error() { |
| 124 |
Err(error) |
| 125 |
} else { |
| 126 |
Ok(state) |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
impl super::Client for Http3Client { |
| 132 |
fn is_closed(&self) -> Result<CloseState, CloseReason> { |
| 133 |
self.state().try_into() |
| 134 |
} |
| 135 |
|
| 136 |
fn process_output(&mut self, now: Instant) -> Output { |
| 137 |
self.process_output(now) |
| 138 |
} |
| 139 |
|
| 140 |
fn process_multiple_input<'a>( |
| 141 |
&mut self, |
| 142 |
dgrams: impl IntoIterator<Item = Datagram<&'a mut [u8]>>, |
| 143 |
now: Instant, |
| 144 |
) { |
| 145 |
self.process_multiple_input(dgrams, now); |
| 146 |
} |
| 147 |
|
| 148 |
fn close<S>(&mut self, now: Instant, app_error: AppError, msg: S) |
| 149 |
where |
| 150 |
S: AsRef<str> + Display, |
| 151 |
{ |
| 152 |
self.close(now, app_error, msg); |
| 153 |
} |
| 154 |
|
| 155 |
fn stats(&self) -> neqo_transport::Stats { |
| 156 |
self.transport_stats() |
| 157 |
} |
| 158 |
|
| 159 |
fn has_events(&self) -> bool { |
| 160 |
Provider::has_events(self) |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
impl Handler<'_> { |
| 165 |
fn reinit(&mut self) { |
| 166 |
for url in self.url_handler.handled_urls.drain(..) { |
| 167 |
self.url_handler.url_queue.push_front(url); |
| 168 |
} |
| 169 |
self.url_handler.stream_handlers.clear(); |
| 170 |
self.url_handler.all_paths.clear(); |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
impl super::Handler for Handler<'_> { |
| 175 |
type Client = Http3Client; |
| 176 |
|
| 177 |
fn handle(&mut self, client: &mut Http3Client) -> Res<bool> { |
| 178 |
while let Some(event) = client.next_event() { |
| 179 |
match event { |
| 180 |
Http3ClientEvent::AuthenticationNeeded => { |
| 181 |
client.authenticated(AuthenticationStatus::Ok, Instant::now()); |
| 182 |
} |
| 183 |
Http3ClientEvent::HeaderReady { |
| 184 |
stream_id, |
| 185 |
headers, |
| 186 |
fin, |
| 187 |
.. |
| 188 |
} => { |
| 189 |
if self.url_handler.stream_handler(stream_id).is_some() { |
| 190 |
qdebug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); |
| 191 |
} else { |
| 192 |
qwarn!("Data on unexpected stream: {stream_id}"); |
| 193 |
} |
| 194 |
if fin { |
| 195 |
self.url_handler.on_stream_fin(client, stream_id); |
| 196 |
} |
| 197 |
} |
| 198 |
Http3ClientEvent::DataReadable { stream_id } => { |
| 199 |
let mut stream_done = false; |
| 200 |
match self.url_handler.stream_handler(stream_id) { |
| 201 |
None => { |
| 202 |
qwarn!("Data on unexpected stream: {stream_id}"); |
| 203 |
} |
| 204 |
Some(handler) => loop { |
| 205 |
let (sz, fin) = client.read_data( |
| 206 |
Instant::now(), |
| 207 |
stream_id, |
| 208 |
&mut self.read_buffer, |
| 209 |
)?; |
| 210 |
|
| 211 |
handler.process_data_readable( |
| 212 |
stream_id, |
| 213 |
fin, |
| 214 |
&self.read_buffer[..sz], |
| 215 |
self.output_read_data, |
| 216 |
)?; |
| 217 |
|
| 218 |
if fin { |
| 219 |
stream_done = true; |
| 220 |
break; |
| 221 |
} |
| 222 |
|
| 223 |
if sz == 0 { |
| 224 |
break; |
| 225 |
} |
| 226 |
}, |
| 227 |
} |
| 228 |
|
| 229 |
if stream_done { |
| 230 |
self.url_handler.on_stream_fin(client, stream_id); |
| 231 |
} |
| 232 |
} |
| 233 |
Http3ClientEvent::DataWritable { stream_id } => { |
| 234 |
match self.url_handler.stream_handler(stream_id) { |
| 235 |
None => { |
| 236 |
qwarn!("Data on unexpected stream: {stream_id}"); |
| 237 |
} |
| 238 |
Some(handler) => { |
| 239 |
handler.process_data_writable(client, stream_id); |
| 240 |
} |
| 241 |
} |
| 242 |
} |
| 243 |
Http3ClientEvent::StateChange(Http3State::Connected) |
| 244 |
| Http3ClientEvent::RequestsCreatable => { |
| 245 |
qinfo!("{event:?}"); |
| 246 |
self.url_handler.process_urls(client); |
| 247 |
} |
| 248 |
Http3ClientEvent::ZeroRttRejected => { |
| 249 |
qinfo!("{event:?}"); |
| 250 |
// All 0-RTT data was rejected. We need to retransmit it. |
| 251 |
self.reinit(); |
| 252 |
self.url_handler.process_urls(client); |
| 253 |
} |
| 254 |
Http3ClientEvent::ResumptionToken(t) => self.token = Some(t), |
| 255 |
_ => { |
| 256 |
qwarn!("Unhandled event {event:?}"); |
| 257 |
} |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
Ok(self.url_handler.done()) |
| 262 |
} |
| 263 |
|
| 264 |
fn take_token(&mut self) -> Option<ResumptionToken> { |
| 265 |
self.token.take() |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
trait StreamHandler { |
| 270 |
fn process_data_readable( |
| 271 |
&mut self, |
| 272 |
stream_id: StreamId, |
| 273 |
fin: bool, |
| 274 |
data: &[u8], |
| 275 |
output_read_data: bool, |
| 276 |
) -> Res<()>; |
| 277 |
fn process_data_writable(&mut self, client: &mut Http3Client, stream_id: StreamId); |
| 278 |
} |
| 279 |
|
| 280 |
struct DownloadStreamHandler { |
| 281 |
out_file: Option<BufWriter<File>>, |
| 282 |
} |
| 283 |
|
| 284 |
impl StreamHandler for DownloadStreamHandler { |
| 285 |
fn process_data_readable( |
| 286 |
&mut self, |
| 287 |
stream_id: StreamId, |
| 288 |
fin: bool, |
| 289 |
data: &[u8], |
| 290 |
output_read_data: bool, |
| 291 |
) -> Res<()> { |
| 292 |
if let Some(out_file) = &mut self.out_file { |
| 293 |
if !data.is_empty() { |
| 294 |
out_file.write_all(data)?; |
| 295 |
} |
| 296 |
return Ok(()); |
| 297 |
} else if !output_read_data { |
| 298 |
qdebug!("READ[{stream_id}]: {} bytes", data.len()); |
| 299 |
} else if let Ok(txt) = std::str::from_utf8(data) { |
| 300 |
qdebug!("READ[{stream_id}]: {txt}"); |
| 301 |
} else { |
| 302 |
qdebug!("READ[{stream_id}]: 0x{}", hex(data)); |
| 303 |
} |
| 304 |
|
| 305 |
if fin { |
| 306 |
if let Some(mut out_file) = self.out_file.take() { |
| 307 |
out_file.flush()?; |
| 308 |
} else { |
| 309 |
qdebug!("<FIN[{stream_id}]>"); |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
Ok(()) |
| 314 |
} |
| 315 |
|
| 316 |
fn process_data_writable(&mut self, _client: &mut Http3Client, _stream_id: StreamId) {} |
| 317 |
} |
| 318 |
|
| 319 |
struct UploadStreamHandler { |
| 320 |
data: SendData, |
| 321 |
start: Instant, |
| 322 |
} |
| 323 |
|
| 324 |
impl StreamHandler for UploadStreamHandler { |
| 325 |
fn process_data_readable( |
| 326 |
&mut self, |
| 327 |
stream_id: StreamId, |
| 328 |
_fin: bool, |
| 329 |
data: &[u8], |
| 330 |
_output_read_data: bool, |
| 331 |
) -> Res<()> { |
| 332 |
if let Ok(txt) = std::str::from_utf8(data) { |
| 333 |
let trimmed_txt = txt.trim_end_matches(char::from(0)); |
| 334 |
let parsed: usize = trimmed_txt.parse().map_err(|_| Error::InvalidInput)?; |
| 335 |
if parsed == self.data.len() { |
| 336 |
qinfo!( |
| 337 |
"Stream ID: {stream_id:?}, Upload time: {:?}", |
| 338 |
Instant::now().duration_since(self.start) |
| 339 |
); |
| 340 |
} |
| 341 |
Ok(()) |
| 342 |
} else { |
| 343 |
qerror!("Unexpected data [{stream_id}]: 0x{}", hex(data)); |
| 344 |
Err(crate::client::Error::Http3Error(Error::InvalidInput)) |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
fn process_data_writable(&mut self, client: &mut Http3Client, stream_id: StreamId) { |
| 349 |
let done = self |
| 350 |
.data |
| 351 |
.send(|chunk| client.send_data(stream_id, chunk).unwrap()); |
| 352 |
if done { |
| 353 |
client.stream_close_send(stream_id).unwrap(); |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
struct UrlHandler<'a> { |
| 359 |
url_queue: VecDeque<Url>, |
| 360 |
handled_urls: Vec<Url>, |
| 361 |
stream_handlers: HashMap<StreamId, Box<dyn StreamHandler>>, |
| 362 |
all_paths: Vec<PathBuf>, |
| 363 |
args: &'a Args, |
| 364 |
} |
| 365 |
|
| 366 |
impl UrlHandler<'_> { |
| 367 |
fn stream_handler(&mut self, stream_id: StreamId) -> Option<&mut Box<dyn StreamHandler>> { |
| 368 |
self.stream_handlers.get_mut(&stream_id) |
| 369 |
} |
| 370 |
|
| 371 |
fn process_urls(&mut self, client: &mut Http3Client) { |
| 372 |
loop { |
| 373 |
if self.url_queue.is_empty() { |
| 374 |
break; |
| 375 |
} |
| 376 |
if self.stream_handlers.len() >= self.args.concurrency { |
| 377 |
break; |
| 378 |
} |
| 379 |
if !self.next_url(client) { |
| 380 |
break; |
| 381 |
} |
| 382 |
} |
| 383 |
} |
| 384 |
|
| 385 |
fn next_url(&mut self, client: &mut Http3Client) -> bool { |
| 386 |
let url = self |
| 387 |
.url_queue |
| 388 |
.pop_front() |
| 389 |
.expect("download_next called with empty queue"); |
| 390 |
match client.fetch( |
| 391 |
Instant::now(), |
| 392 |
&self.args.method, |
| 393 |
&url, |
| 394 |
&to_headers(&self.args.header), |
| 395 |
Priority::default(), |
| 396 |
) { |
| 397 |
Ok(client_stream_id) => { |
| 398 |
qdebug!("Successfully created stream id {client_stream_id} for {url}"); |
| 399 |
|
| 400 |
let handler: Box<dyn StreamHandler> = match self.args.method.as_str() { |
| 401 |
"GET" => { |
| 402 |
let out_file = get_output_file( |
| 403 |
&url, |
| 404 |
self.args.output_dir.as_ref(), |
| 405 |
&mut self.all_paths, |
| 406 |
); |
| 407 |
client.stream_close_send(client_stream_id).unwrap(); |
| 408 |
Box::new(DownloadStreamHandler { out_file }) |
| 409 |
} |
| 410 |
"POST" => Box::new(UploadStreamHandler { |
| 411 |
data: SendData::zeroes(self.args.upload_size), |
| 412 |
start: Instant::now(), |
| 413 |
}), |
| 414 |
_ => unimplemented!(), |
| 415 |
}; |
| 416 |
|
| 417 |
self.stream_handlers.insert(client_stream_id, handler); |
| 418 |
self.handled_urls.push(url); |
| 419 |
true |
| 420 |
} |
| 421 |
Err( |
| 422 |
Error::TransportError(TransportError::StreamLimitError) |
| 423 |
| Error::StreamLimitError |
| 424 |
| Error::Unavailable, |
| 425 |
) => { |
| 426 |
self.url_queue.push_front(url); |
| 427 |
false |
| 428 |
} |
| 429 |
Err(e) => { |
| 430 |
panic!("Can't create stream {e}"); |
| 431 |
} |
| 432 |
} |
| 433 |
} |
| 434 |
|
| 435 |
fn done(&self) -> bool { |
| 436 |
self.stream_handlers.is_empty() && self.url_queue.is_empty() |
| 437 |
} |
| 438 |
|
| 439 |
fn on_stream_fin(&mut self, client: &mut Http3Client, stream_id: StreamId) { |
| 440 |
self.stream_handlers.remove(&stream_id); |
| 441 |
self.process_urls(client); |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
fn to_headers(values: &[impl AsRef<str>]) -> Vec<Header> { |
| 446 |
values |
| 447 |
.iter() |
| 448 |
.scan(None, |state, value| { |
| 449 |
if let Some(name) = state.take() { |
| 450 |
*state = None; |
| 451 |
Some(Header::new(name, value.as_ref())) |
| 452 |
} else { |
| 453 |
*state = Some(value.as_ref().to_string()); |
| 454 |
None |
| 455 |
} |
| 456 |
}) |
| 457 |
.collect() |
| 458 |
} |