| 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 |
use std::{ |
| 10 |
collections::{HashMap, VecDeque}, |
| 11 |
fmt::{self, Display}, |
| 12 |
fs::{create_dir_all, File, OpenOptions}, |
| 13 |
io::{self, BufWriter}, |
| 14 |
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs as _}, |
| 15 |
path::PathBuf, |
| 16 |
pin::Pin, |
| 17 |
process::exit, |
| 18 |
time::Instant, |
| 19 |
}; |
| 20 |
|
| 21 |
use clap::Parser; |
| 22 |
use futures::{ |
| 23 |
future::{select, Either}, |
| 24 |
FutureExt as _, TryFutureExt as _, |
| 25 |
}; |
| 26 |
use neqo_common::{qdebug, qerror, qinfo, qlog::NeqoQlog, qwarn, Datagram, Role}; |
| 27 |
use neqo_crypto::{ |
| 28 |
constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256}, |
| 29 |
init, Cipher, ResumptionToken, |
| 30 |
}; |
| 31 |
use neqo_http3::Output; |
| 32 |
use neqo_transport::{AppError, CloseReason, ConnectionId, Version}; |
| 33 |
use neqo_udp::RecvBuf; |
| 34 |
use tokio::time::Sleep; |
| 35 |
use url::{Host, Origin, Url}; |
| 36 |
|
| 37 |
use crate::SharedArgs; |
| 38 |
|
| 39 |
mod http09; |
| 40 |
mod http3; |
| 41 |
|
| 42 |
const BUFWRITER_BUFFER_SIZE: usize = 64 * 1024; |
| 43 |
|
| 44 |
#[derive(Debug)] |
| 45 |
pub enum Error { |
| 46 |
ArgumentError(&'static str), |
| 47 |
Http3Error(neqo_http3::Error), |
| 48 |
IoError(io::Error), |
| 49 |
QlogError(qlog::Error), |
| 50 |
TransportError(neqo_transport::Error), |
| 51 |
ApplicationError(AppError), |
| 52 |
CryptoError(neqo_crypto::Error), |
| 53 |
} |
| 54 |
|
| 55 |
impl From<neqo_crypto::Error> for Error { |
| 56 |
fn from(err: neqo_crypto::Error) -> Self { |
| 57 |
Self::CryptoError(err) |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
impl From<io::Error> for Error { |
| 62 |
fn from(err: io::Error) -> Self { |
| 63 |
Self::IoError(err) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
impl From<neqo_http3::Error> for Error { |
| 68 |
fn from(err: neqo_http3::Error) -> Self { |
| 69 |
Self::Http3Error(err) |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
impl From<qlog::Error> for Error { |
| 74 |
fn from(err: qlog::Error) -> Self { |
| 75 |
Self::QlogError(err) |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
impl From<neqo_transport::Error> for Error { |
| 80 |
fn from(err: neqo_transport::Error) -> Self { |
| 81 |
Self::TransportError(err) |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
impl From<CloseReason> for Error { |
| 86 |
fn from(err: CloseReason) -> Self { |
| 87 |
match err { |
| 88 |
CloseReason::Transport(e) => Self::TransportError(e), |
| 89 |
CloseReason::Application(e) => Self::ApplicationError(e), |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
impl Display for Error { |
| 95 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 96 |
write!(f, "Error: {self:?}")?; |
| 97 |
Ok(()) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
impl std::error::Error for Error {} |
| 102 |
|
| 103 |
type Res<T> = Result<T, Error>; |
| 104 |
|
| 105 |
#[derive(Debug, Parser)] |
| 106 |
#[command(author, version, about, long_about = None)] |
| 107 |
#[expect( |
| 108 |
clippy::struct_excessive_bools, |
| 109 |
reason = "Not a good use of that lint." |
| 110 |
)] |
| 111 |
pub struct Args { |
| 112 |
#[command(flatten)] |
| 113 |
shared: SharedArgs, |
| 114 |
|
| 115 |
urls: Vec<Url>, |
| 116 |
|
| 117 |
#[arg(short = 'm', default_value = "GET")] |
| 118 |
method: String, |
| 119 |
|
| 120 |
#[arg(short = 'H', long, number_of_values = 2)] |
| 121 |
header: Vec<String>, |
| 122 |
|
| 123 |
#[arg(name = "max-push", short = 'p', long, default_value = "10")] |
| 124 |
max_concurrent_push_streams: u64, |
| 125 |
|
| 126 |
#[arg(name = "download-in-series", long)] |
| 127 |
/// Download resources in series using separate connections. |
| 128 |
download_in_series: bool, |
| 129 |
|
| 130 |
#[arg(name = "concurrency", long, default_value = "100")] |
| 131 |
/// The maximum number of requests to have outstanding at one time. |
| 132 |
concurrency: usize, |
| 133 |
|
| 134 |
#[arg(name = "output-read-data", long)] |
| 135 |
/// Output received data to stdout |
| 136 |
output_read_data: bool, |
| 137 |
|
| 138 |
#[arg(name = "output-dir", long)] |
| 139 |
/// Save contents of fetched URLs to a directory |
| 140 |
output_dir: Option<PathBuf>, |
| 141 |
|
| 142 |
#[arg(short = 'r', long, hide = true)] |
| 143 |
/// Client attempts to resume by making multiple connections to servers. |
| 144 |
/// Requires that 2 or more URLs are listed for each server. |
| 145 |
/// Use this for 0-RTT: the stack always attempts 0-RTT on resumption. |
| 146 |
resume: bool, |
| 147 |
|
| 148 |
#[arg(name = "key-update", long, hide = true)] |
| 149 |
/// Attempt to initiate a key update immediately after confirming the connection. |
| 150 |
key_update: bool, |
| 151 |
|
| 152 |
#[arg(name = "ech", long, value_parser = |s: &str| hex::decode(s))] |
| 153 |
/// Enable encrypted client hello (ECH). |
| 154 |
/// This takes an encoded ECH configuration in hexadecimal format. |
| 155 |
ech: Option<Vec<u8>>, |
| 156 |
|
| 157 |
#[arg(name = "ipv4-only", short = '4', long)] |
| 158 |
/// Connect only over IPv4 |
| 159 |
ipv4_only: bool, |
| 160 |
|
| 161 |
#[arg(name = "ipv6-only", short = '6', long)] |
| 162 |
/// Connect only over IPv6 |
| 163 |
ipv6_only: bool, |
| 164 |
|
| 165 |
/// The test that this client will run. Currently, we only support "upload". |
| 166 |
#[arg(name = "test", long)] |
| 167 |
test: Option<String>, |
| 168 |
|
| 169 |
/// The request size that will be used for upload test. |
| 170 |
#[arg(name = "upload-size", long, default_value = "100")] |
| 171 |
upload_size: usize, |
| 172 |
|
| 173 |
/// Print connection stats after close. |
| 174 |
#[arg(name = "stats", long)] |
| 175 |
stats: bool, |
| 176 |
|
| 177 |
/// The length of the local connection ID. |
| 178 |
#[arg(name = "cid-length", short = 'l', long, default_value = "0", |
| 179 |
value_parser = clap::value_parser!(u8).range(..=20))] |
| 180 |
cid_len: u8, |
| 181 |
} |
| 182 |
|
| 183 |
impl Args { |
| 184 |
#[must_use] |
| 185 |
#[cfg(any(test, feature = "bench"))] |
| 186 |
#[expect(clippy::missing_panics_doc, reason = "This is example code.")] |
| 187 |
pub fn new(requests: &[usize], upload: bool) -> Self { |
| 188 |
use std::str::FromStr as _; |
| 189 |
Self { |
| 190 |
shared: SharedArgs::default(), |
| 191 |
urls: requests |
| 192 |
.iter() |
| 193 |
.map(|r| Url::from_str(&format!("http://[::1]:12345/{r}")).unwrap()) |
| 194 |
.collect(), |
| 195 |
method: if upload { "POST".into() } else { "GET".into() }, |
| 196 |
header: vec![], |
| 197 |
max_concurrent_push_streams: 10, |
| 198 |
download_in_series: false, |
| 199 |
concurrency: 100, |
| 200 |
output_read_data: false, |
| 201 |
output_dir: Some("/dev/null".into()), |
| 202 |
resume: false, |
| 203 |
key_update: false, |
| 204 |
ech: None, |
| 205 |
ipv4_only: false, |
| 206 |
ipv6_only: false, |
| 207 |
test: None, |
| 208 |
upload_size: if upload { requests[0] } else { 100 }, |
| 209 |
stats: false, |
| 210 |
cid_len: 0, |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
fn get_ciphers(&self) -> Vec<Cipher> { |
| 215 |
self.shared |
| 216 |
.ciphers |
| 217 |
.iter() |
| 218 |
.filter_map(|c| match c.as_str() { |
| 219 |
"TLS_AES_128_GCM_SHA256" => Some(TLS_AES_128_GCM_SHA256), |
| 220 |
"TLS_AES_256_GCM_SHA384" => Some(TLS_AES_256_GCM_SHA384), |
| 221 |
"TLS_CHACHA20_POLY1305_SHA256" => Some(TLS_CHACHA20_POLY1305_SHA256), |
| 222 |
_ => None, |
| 223 |
}) |
| 224 |
.collect::<Vec<_>>() |
| 225 |
} |
| 226 |
|
| 227 |
fn update_for_tests(&mut self) { |
| 228 |
let Some(testcase) = self.shared.qns_test.as_ref() else { |
| 229 |
return; |
| 230 |
}; |
| 231 |
|
| 232 |
if self.key_update { |
| 233 |
qerror!("internal option key_update set by user"); |
| 234 |
exit(127) |
| 235 |
} |
| 236 |
|
| 237 |
if self.resume { |
| 238 |
qerror!("internal option resume set by user"); |
| 239 |
exit(127) |
| 240 |
} |
| 241 |
|
| 242 |
// Only use v1 for most QNS tests. |
| 243 |
self.shared.quic_parameters.quic_version = vec![Version::Version1]; |
| 244 |
// This is the default for all tests except http3. |
| 245 |
self.shared.alpn = String::from("hq-interop"); |
| 246 |
// Wireshark can't reassemble sliced CRYPTO frames, which causes tests to fail. |
| 247 |
// So let's turn that off by default, and only enable for some known-good QNS tests. |
| 248 |
self.shared.quic_parameters.no_sni_slicing = true; |
| 249 |
match testcase.as_str() { |
| 250 |
"http3" => { |
| 251 |
self.shared.quic_parameters.no_sni_slicing = false; |
| 252 |
self.shared.alpn = String::from("h3"); |
| 253 |
if let Some(testcase) = &self.test { |
| 254 |
if testcase.as_str() != "upload" { |
| 255 |
qerror!("Unsupported test case: {testcase}"); |
| 256 |
exit(127) |
| 257 |
} |
| 258 |
|
| 259 |
self.method = String::from("POST"); |
| 260 |
} |
| 261 |
} |
| 262 |
"handshake" | "transfer" | "retry" | "ecn" => {} |
| 263 |
"resumption" => { |
| 264 |
if self.urls.len() < 2 { |
| 265 |
qerror!("Warning: resumption test won't work without >1 URL"); |
| 266 |
exit(127); |
| 267 |
} |
| 268 |
self.resume = true; |
| 269 |
} |
| 270 |
"zerortt" => { |
| 271 |
if self.urls.len() < 2 { |
| 272 |
qerror!("Warning: zerortt test won't work without >1 URL"); |
| 273 |
exit(127); |
| 274 |
} |
| 275 |
self.shared.quic_parameters.no_sni_slicing = false; |
| 276 |
self.resume = true; |
| 277 |
// PMTUD probes inflate what we sent in 1-RTT, causing QNS to fail the test. |
| 278 |
self.shared.quic_parameters.no_pmtud = true; |
| 279 |
// If we pace, we might get the initial server flight before sending sufficient |
| 280 |
// 0-RTT data to pass the QNS check. So let's burst. |
| 281 |
self.shared.quic_parameters.no_pacing = true; |
| 282 |
} |
| 283 |
"multiconnect" => { |
| 284 |
self.download_in_series = true; |
| 285 |
} |
| 286 |
"chacha20" => { |
| 287 |
self.shared.ciphers.clear(); |
| 288 |
self.shared |
| 289 |
.ciphers |
| 290 |
.extend_from_slice(&[String::from("TLS_CHACHA20_POLY1305_SHA256")]); |
| 291 |
} |
| 292 |
"keyupdate" => { |
| 293 |
self.key_update = true; |
| 294 |
} |
| 295 |
"v2" => { |
| 296 |
self.shared.quic_parameters.no_sni_slicing = false; |
| 297 |
// Use default version set for this test (which allows compatible vneg.) |
| 298 |
self.shared.quic_parameters.quic_version.clear(); |
| 299 |
} |
| 300 |
_ => exit(127), |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
#[cfg(any(test, feature = "bench"))] |
| 305 |
pub fn set_qlog_dir(&mut self, dir: PathBuf) { |
| 306 |
self.shared.qlog_dir = Some(dir); |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
fn get_output_file( |
| 311 |
url: &Url, |
| 312 |
output_dir: Option<&PathBuf>, |
| 313 |
all_paths: &mut Vec<PathBuf>, |
| 314 |
) -> Option<BufWriter<File>> { |
| 315 |
if let Some(dir) = output_dir { |
| 316 |
let mut out_path = dir.clone(); |
| 317 |
|
| 318 |
let url_path = if url.path() == "/" { |
| 319 |
// If no path is given... call it "root"? |
| 320 |
"root" |
| 321 |
} else { |
| 322 |
// Omit leading slash |
| 323 |
&url.path()[1..] |
| 324 |
}; |
| 325 |
out_path.push(url_path); |
| 326 |
|
| 327 |
if all_paths.contains(&out_path) { |
| 328 |
qerror!("duplicate path {}", out_path.display()); |
| 329 |
return None; |
| 330 |
} |
| 331 |
|
| 332 |
qinfo!("Saving {url} to {out_path:?}"); |
| 333 |
|
| 334 |
if let Some(parent) = out_path.parent() { |
| 335 |
create_dir_all(parent).ok()?; |
| 336 |
} |
| 337 |
|
| 338 |
let f = OpenOptions::new() |
| 339 |
.write(true) |
| 340 |
.create(true) |
| 341 |
.truncate(true) |
| 342 |
.open(&out_path) |
| 343 |
.ok()?; |
| 344 |
|
| 345 |
all_paths.push(out_path); |
| 346 |
Some(BufWriter::with_capacity(BUFWRITER_BUFFER_SIZE, f)) |
| 347 |
} else { |
| 348 |
None |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
enum Ready { |
| 353 |
Socket, |
| 354 |
Timeout, |
| 355 |
} |
| 356 |
|
| 357 |
// Wait for the socket to be readable or the timeout to fire. |
| 358 |
async fn ready( |
| 359 |
socket: &crate::udp::Socket, |
| 360 |
mut timeout: Option<&mut Pin<Box<Sleep>>>, |
| 361 |
) -> Result<Ready, io::Error> { |
| 362 |
let socket_ready = Box::pin(socket.readable()).map_ok(|()| Ready::Socket); |
| 363 |
let timeout_ready = timeout |
| 364 |
.as_mut() |
| 365 |
.map_or_else(|| Either::Right(futures::future::pending()), Either::Left) |
| 366 |
.map(|()| Ok(Ready::Timeout)); |
| 367 |
select(socket_ready, timeout_ready).await.factor_first().0 |
| 368 |
} |
| 369 |
|
| 370 |
/// Handles a given task on the provided [`Client`]. |
| 371 |
trait Handler { |
| 372 |
type Client: Client; |
| 373 |
|
| 374 |
fn handle(&mut self, client: &mut Self::Client) -> Res<bool>; |
| 375 |
fn take_token(&mut self) -> Option<ResumptionToken>; |
| 376 |
} |
| 377 |
|
| 378 |
enum CloseState { |
| 379 |
NotClosing, |
| 380 |
Closing, |
| 381 |
Closed, |
| 382 |
} |
| 383 |
|
| 384 |
/// Network client, e.g. [`neqo_transport::Connection`] or [`neqo_http3::Http3Client`]. |
| 385 |
trait Client { |
| 386 |
fn process_output(&mut self, now: Instant) -> Output; |
| 387 |
fn process_multiple_input<'a>( |
| 388 |
&mut self, |
| 389 |
dgrams: impl IntoIterator<Item = Datagram<&'a mut [u8]>>, |
| 390 |
now: Instant, |
| 391 |
); |
| 392 |
fn has_events(&self) -> bool; |
| 393 |
fn close<S>(&mut self, now: Instant, app_error: AppError, msg: S) |
| 394 |
where |
| 395 |
S: AsRef<str> + Display; |
| 396 |
fn is_closed(&self) -> Result<CloseState, CloseReason>; |
| 397 |
fn stats(&self) -> neqo_transport::Stats; |
| 398 |
} |
| 399 |
|
| 400 |
struct Runner<'a, H: Handler> { |
| 401 |
local_addr: SocketAddr, |
| 402 |
socket: &'a mut crate::udp::Socket, |
| 403 |
client: H::Client, |
| 404 |
handler: H, |
| 405 |
timeout: Option<Pin<Box<Sleep>>>, |
| 406 |
args: &'a Args, |
| 407 |
recv_buf: RecvBuf, |
| 408 |
} |
| 409 |
|
| 410 |
impl<'a, H: Handler> Runner<'a, H> { |
| 411 |
fn new( |
| 412 |
local_addr: SocketAddr, |
| 413 |
socket: &'a mut crate::udp::Socket, |
| 414 |
client: H::Client, |
| 415 |
handler: H, |
| 416 |
args: &'a Args, |
| 417 |
) -> Self { |
| 418 |
Self { |
| 419 |
local_addr, |
| 420 |
socket, |
| 421 |
client, |
| 422 |
handler, |
| 423 |
args, |
| 424 |
timeout: None, |
| 425 |
recv_buf: RecvBuf::new(), |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
async fn run(mut self) -> Res<Option<ResumptionToken>> { |
| 430 |
loop { |
| 431 |
let handler_done = self.handler.handle(&mut self.client)?; |
| 432 |
self.process_output().await?; |
| 433 |
if self.client.has_events() { |
| 434 |
continue; |
| 435 |
} |
| 436 |
|
| 437 |
match (handler_done, self.client.is_closed()?) { |
| 438 |
// more work; or no more work, already closing connection |
| 439 |
(true, CloseState::Closing) | (false, _) => {} |
| 440 |
// no more work, closing connection |
| 441 |
(true, CloseState::NotClosing) => { |
| 442 |
self.client.close(Instant::now(), 0, "kthxbye!"); |
| 443 |
continue; |
| 444 |
} |
| 445 |
// no more work, connection closed, terminating |
| 446 |
(true, CloseState::Closed) => break, |
| 447 |
} |
| 448 |
|
| 449 |
match ready(self.socket, self.timeout.as_mut()).await? { |
| 450 |
Ready::Socket => self.process_multiple_input().await?, |
| 451 |
Ready::Timeout => { |
| 452 |
self.timeout = None; |
| 453 |
} |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
if self.args.stats { |
| 458 |
qinfo!("{:?}", self.client.stats()); |
| 459 |
} |
| 460 |
|
| 461 |
Ok(self.handler.take_token()) |
| 462 |
} |
| 463 |
|
| 464 |
async fn process_output(&mut self) -> Result<(), io::Error> { |
| 465 |
loop { |
| 466 |
match self.client.process_output(Instant::now()) { |
| 467 |
Output::Datagram(dgram) => loop { |
| 468 |
// Optimistically attempt sending datagram. In case the OS |
| 469 |
// buffer is full, wait till socket is writable then try |
| 470 |
// again. |
| 471 |
match self.socket.send(&dgram) { |
| 472 |
Ok(()) => break, |
| 473 |
Err(e) if e.kind() == io::ErrorKind::WouldBlock => { |
| 474 |
self.socket.writable().await?; |
| 475 |
// Now try again. |
| 476 |
} |
| 477 |
e @ Err(_) => return e, |
| 478 |
} |
| 479 |
}, |
| 480 |
Output::Callback(new_timeout) => { |
| 481 |
qdebug!("Setting timeout of {new_timeout:?}"); |
| 482 |
self.timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); |
| 483 |
break; |
| 484 |
} |
| 485 |
Output::None => { |
| 486 |
qdebug!("Output::None"); |
| 487 |
break; |
| 488 |
} |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
Ok(()) |
| 493 |
} |
| 494 |
|
| 495 |
async fn process_multiple_input(&mut self) -> Res<()> { |
| 496 |
loop { |
| 497 |
let Some(dgrams) = self.socket.recv(self.local_addr, &mut self.recv_buf)? else { |
| 498 |
break; |
| 499 |
}; |
| 500 |
self.client.process_multiple_input(dgrams, Instant::now()); |
| 501 |
self.process_output().await?; |
| 502 |
} |
| 503 |
|
| 504 |
Ok(()) |
| 505 |
} |
| 506 |
} |
| 507 |
|
| 508 |
fn qlog_new(args: &Args, hostname: &str, cid: &ConnectionId) -> Res<NeqoQlog> { |
| 509 |
let Some(qlog_dir) = args.shared.qlog_dir.clone() else { |
| 510 |
return Ok(NeqoQlog::disabled()); |
| 511 |
}; |
| 512 |
|
| 513 |
// hostname might be an IPv6 address, e.g. `[::1]`. `:` is an invalid |
| 514 |
// Windows file name character. |
| 515 |
#[cfg(windows)] |
| 516 |
let hostname: String = hostname |
| 517 |
.chars() |
| 518 |
.map(|c| if c == ':' { '_' } else { c }) |
| 519 |
.collect(); |
| 520 |
|
| 521 |
NeqoQlog::enabled_with_file( |
| 522 |
qlog_dir, |
| 523 |
Role::Client, |
| 524 |
Some("Neqo client qlog".to_string()), |
| 525 |
Some("Neqo client qlog".to_string()), |
| 526 |
format!("client-{hostname}-{cid}"), |
| 527 |
) |
| 528 |
.map_err(Error::QlogError) |
| 529 |
} |
| 530 |
|
| 531 |
const fn local_addr_for(remote_addr: &SocketAddr, local_port: u16) -> SocketAddr { |
| 532 |
match remote_addr { |
| 533 |
SocketAddr::V4(..) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), local_port), |
| 534 |
SocketAddr::V6(..) => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), local_port), |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
fn urls_by_origin(urls: &[Url]) -> impl Iterator<Item = ((Host, u16), VecDeque<Url>)> { |
| 539 |
urls.iter() |
| 540 |
.fold(HashMap::<Origin, VecDeque<Url>>::new(), |mut urls, url| { |
| 541 |
urls.entry(url.origin()).or_default().push_back(url.clone()); |
| 542 |
urls |
| 543 |
}) |
| 544 |
.into_iter() |
| 545 |
.filter_map(|(origin, urls)| match origin { |
| 546 |
Origin::Tuple(_scheme, h, p) => Some(((h, p), urls)), |
| 547 |
Origin::Opaque(x) => { |
| 548 |
qwarn!("Opaque origin {x:?}"); |
| 549 |
None |
| 550 |
} |
| 551 |
}) |
| 552 |
} |
| 553 |
|
| 554 |
#[expect( |
| 555 |
clippy::future_not_send, |
| 556 |
clippy::missing_panics_doc, |
| 557 |
clippy::missing_errors_doc, |
| 558 |
reason = "This is example code." |
| 559 |
)] |
| 560 |
pub async fn client(mut args: Args) -> Res<()> { |
| 561 |
neqo_common::log::init( |
| 562 |
args.shared |
| 563 |
.verbose |
| 564 |
.as_ref() |
| 565 |
.map(clap_verbosity_flag::Verbosity::log_level_filter), |
| 566 |
); |
| 567 |
init()?; |
| 568 |
|
| 569 |
args.update_for_tests(); |
| 570 |
|
| 571 |
init()?; |
| 572 |
|
| 573 |
for ((host, port), mut urls) in urls_by_origin(&args.urls) { |
| 574 |
if args.resume && urls.len() < 2 { |
| 575 |
qerror!("Resumption to {host} cannot work without at least 2 URLs"); |
| 576 |
exit(127); |
| 577 |
} |
| 578 |
|
| 579 |
let remote_addr = format!("{host}:{port}").to_socket_addrs()?.find(|addr| { |
| 580 |
!matches!( |
| 581 |
(addr, args.ipv4_only, args.ipv6_only), |
| 582 |
(SocketAddr::V4(..), false, true) | (SocketAddr::V6(..), true, false) |
| 583 |
) |
| 584 |
}); |
| 585 |
let Some(remote_addr) = remote_addr else { |
| 586 |
qerror!("No compatible address found for: {host}"); |
| 587 |
exit(1); |
| 588 |
}; |
| 589 |
let mut socket = crate::udp::Socket::bind(local_addr_for(&remote_addr, 0))?; |
| 590 |
let real_local = socket.local_addr().unwrap(); |
| 591 |
qinfo!( |
| 592 |
"{} Client connecting: {real_local:?} -> {remote_addr:?}", |
| 593 |
args.shared.alpn |
| 594 |
); |
| 595 |
|
| 596 |
let hostname = format!("{host}"); |
| 597 |
let mut token: Option<ResumptionToken> = None; |
| 598 |
let mut first = true; |
| 599 |
while !urls.is_empty() { |
| 600 |
let to_request = if (args.resume && first) || args.download_in_series { |
| 601 |
urls.pop_front().into_iter().collect() |
| 602 |
} else { |
| 603 |
std::mem::take(&mut urls) |
| 604 |
}; |
| 605 |
|
| 606 |
first = false; |
| 607 |
|
| 608 |
token = if args.shared.alpn == "h3" { |
| 609 |
let client = http3::create_client(&args, real_local, remote_addr, &hostname, token) |
| 610 |
.expect("failed to create client"); |
| 611 |
|
| 612 |
let handler = http3::Handler::new(to_request, &args); |
| 613 |
|
| 614 |
Runner::new(real_local, &mut socket, client, handler, &args) |
| 615 |
.run() |
| 616 |
.await? |
| 617 |
} else { |
| 618 |
let client = |
| 619 |
http09::create_client(&args, real_local, remote_addr, &hostname, token) |
| 620 |
.expect("failed to create client"); |
| 621 |
|
| 622 |
let handler = http09::Handler::new(to_request, &args); |
| 623 |
|
| 624 |
Runner::new(real_local, &mut socket, client, handler, &args) |
| 625 |
.run() |
| 626 |
.await? |
| 627 |
}; |
| 628 |
} |
| 629 |
} |
| 630 |
|
| 631 |
Ok(()) |
| 632 |
} |