| 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 |
#![allow( |
| 8 |
clippy::module_name_repetitions, |
| 9 |
reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>" |
| 10 |
)] |
| 11 |
#![expect( |
| 12 |
clippy::unwrap_used, |
| 13 |
clippy::future_not_send, |
| 14 |
clippy::missing_errors_doc, |
| 15 |
clippy::missing_panics_doc, |
| 16 |
reason = "This is example code." |
| 17 |
)] |
| 18 |
|
| 19 |
use std::{ |
| 20 |
cell::RefCell, |
| 21 |
fmt::{self, Display}, |
| 22 |
fs, io, |
| 23 |
net::{SocketAddr, ToSocketAddrs as _}, |
| 24 |
path::PathBuf, |
| 25 |
pin::Pin, |
| 26 |
process::exit, |
| 27 |
rc::Rc, |
| 28 |
time::{Duration, Instant}, |
| 29 |
}; |
| 30 |
|
| 31 |
use clap::Parser; |
| 32 |
use futures::{ |
| 33 |
future::{select, select_all, Either}, |
| 34 |
FutureExt as _, |
| 35 |
}; |
| 36 |
use neqo_common::{qdebug, qerror, qinfo, qwarn, Datagram}; |
| 37 |
use neqo_crypto::{ |
| 38 |
constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256}, |
| 39 |
init_db, AntiReplay, Cipher, |
| 40 |
}; |
| 41 |
use neqo_transport::{Output, RandomConnectionIdGenerator, Version}; |
| 42 |
use neqo_udp::RecvBuf; |
| 43 |
use tokio::time::Sleep; |
| 44 |
|
| 45 |
use crate::SharedArgs; |
| 46 |
|
| 47 |
const ANTI_REPLAY_WINDOW: Duration = Duration::from_secs(10); |
| 48 |
|
| 49 |
mod http09; |
| 50 |
mod http3; |
| 51 |
|
| 52 |
#[derive(Debug)] |
| 53 |
pub enum Error { |
| 54 |
ArgumentError(&'static str), |
| 55 |
Http3Error(neqo_http3::Error), |
| 56 |
IoError(io::Error), |
| 57 |
QlogError, |
| 58 |
TransportError(neqo_transport::Error), |
| 59 |
CryptoError(neqo_crypto::Error), |
| 60 |
} |
| 61 |
|
| 62 |
impl From<neqo_crypto::Error> for Error { |
| 63 |
fn from(err: neqo_crypto::Error) -> Self { |
| 64 |
Self::CryptoError(err) |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
impl From<io::Error> for Error { |
| 69 |
fn from(err: io::Error) -> Self { |
| 70 |
Self::IoError(err) |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
impl From<neqo_http3::Error> for Error { |
| 75 |
fn from(err: neqo_http3::Error) -> Self { |
| 76 |
Self::Http3Error(err) |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
impl From<qlog::Error> for Error { |
| 81 |
fn from(_err: qlog::Error) -> Self { |
| 82 |
Self::QlogError |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
impl From<neqo_transport::Error> for Error { |
| 87 |
fn from(err: neqo_transport::Error) -> Self { |
| 88 |
Self::TransportError(err) |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
impl Display for Error { |
| 93 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 94 |
write!(f, "Error: {self:?}")?; |
| 95 |
Ok(()) |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
impl std::error::Error for Error {} |
| 100 |
|
| 101 |
type Res<T> = Result<T, Error>; |
| 102 |
|
| 103 |
#[derive(Debug, Parser)] |
| 104 |
#[command(author, version, about, long_about = None)] |
| 105 |
pub struct Args { |
| 106 |
#[command(flatten)] |
| 107 |
shared: SharedArgs, |
| 108 |
|
| 109 |
/// List of IP:port to listen on |
| 110 |
#[arg(default_value = "[::]:4433")] |
| 111 |
hosts: Vec<String>, |
| 112 |
|
| 113 |
#[arg(short = 'd', long, default_value = "./test-fixture/db")] |
| 114 |
/// NSS database directory. |
| 115 |
db: PathBuf, |
| 116 |
|
| 117 |
#[arg(short = 'k', long, default_value = "key")] |
| 118 |
/// Name of key from NSS database. |
| 119 |
key: String, |
| 120 |
|
| 121 |
#[arg(name = "retry", long)] |
| 122 |
/// Force a retry |
| 123 |
retry: bool, |
| 124 |
|
| 125 |
#[arg(name = "ech", long)] |
| 126 |
/// Enable encrypted client hello (ECH). |
| 127 |
/// This generates a new set of ECH keys when it is invoked. |
| 128 |
/// The resulting configuration is printed to stdout in hexadecimal format. |
| 129 |
ech: bool, |
| 130 |
} |
| 131 |
|
| 132 |
#[cfg(any(test, feature = "bench"))] |
| 133 |
impl Default for Args { |
| 134 |
fn default() -> Self { |
| 135 |
use std::str::FromStr as _; |
| 136 |
Self { |
| 137 |
shared: SharedArgs::default(), |
| 138 |
hosts: vec!["[::]:12345".to_string()], |
| 139 |
db: PathBuf::from_str("../test-fixture/db").unwrap(), |
| 140 |
key: "key".to_string(), |
| 141 |
retry: false, |
| 142 |
ech: false, |
| 143 |
} |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
impl Args { |
| 148 |
fn get_ciphers(&self) -> Vec<Cipher> { |
| 149 |
self.shared |
| 150 |
.ciphers |
| 151 |
.iter() |
| 152 |
.filter_map(|c| match c.as_str() { |
| 153 |
"TLS_AES_128_GCM_SHA256" => Some(TLS_AES_128_GCM_SHA256), |
| 154 |
"TLS_AES_256_GCM_SHA384" => Some(TLS_AES_256_GCM_SHA384), |
| 155 |
"TLS_CHACHA20_POLY1305_SHA256" => Some(TLS_CHACHA20_POLY1305_SHA256), |
| 156 |
_ => None, |
| 157 |
}) |
| 158 |
.collect::<Vec<_>>() |
| 159 |
} |
| 160 |
|
| 161 |
fn listen_addresses(&self) -> Vec<SocketAddr> { |
| 162 |
self.hosts |
| 163 |
.iter() |
| 164 |
.filter_map(|host| host.to_socket_addrs().ok()) |
| 165 |
.flatten() |
| 166 |
.chain(self.shared.quic_parameters.preferred_address_v4()) |
| 167 |
.chain(self.shared.quic_parameters.preferred_address_v6()) |
| 168 |
.collect() |
| 169 |
} |
| 170 |
|
| 171 |
fn now(&self) -> Instant { |
| 172 |
if self.shared.qns_test.is_some() { |
| 173 |
// When NSS starts its anti-replay it blocks any acceptance of 0-RTT for a |
| 174 |
// single period. This ensures that an attacker that is able to force a |
| 175 |
// server to reboot is unable to use that to flush the anti-replay buffers |
| 176 |
// and have something replayed. |
| 177 |
// |
| 178 |
// However, this is a massive inconvenience for us when we are testing. |
| 179 |
// As we can't initialize `AntiReplay` in the past (see `neqo_common::time` |
| 180 |
// for why), fast forward time here so that the connections get times from |
| 181 |
// in the future. |
| 182 |
// |
| 183 |
// This is NOT SAFE. Don't do this. |
| 184 |
Instant::now() + ANTI_REPLAY_WINDOW |
| 185 |
} else { |
| 186 |
Instant::now() |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
#[cfg(any(test, feature = "bench"))] |
| 191 |
pub fn set_qlog_dir(&mut self, dir: PathBuf) { |
| 192 |
self.shared.qlog_dir = Some(dir); |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
fn qns_read_response(filename: &str) -> Result<Vec<u8>, io::Error> { |
| 197 |
let path: PathBuf = ["/www", filename.trim_matches(|p| p == '/')] |
| 198 |
.iter() |
| 199 |
.collect(); |
| 200 |
fs::read(path) |
| 201 |
} |
| 202 |
|
| 203 |
pub trait HttpServer: Display { |
| 204 |
fn process(&mut self, dgram: Option<Datagram<&mut [u8]>>, now: Instant) -> Output; |
| 205 |
fn process_events(&mut self, now: Instant); |
| 206 |
fn has_events(&self) -> bool; |
| 207 |
} |
| 208 |
|
| 209 |
pub struct ServerRunner { |
| 210 |
now: Box<dyn Fn() -> Instant>, |
| 211 |
server: Box<dyn HttpServer>, |
| 212 |
timeout: Option<Pin<Box<Sleep>>>, |
| 213 |
sockets: Vec<(SocketAddr, crate::udp::Socket)>, |
| 214 |
recv_buf: RecvBuf, |
| 215 |
} |
| 216 |
|
| 217 |
impl ServerRunner { |
| 218 |
#[must_use] |
| 219 |
pub fn new( |
| 220 |
now: Box<dyn Fn() -> Instant>, |
| 221 |
server: Box<dyn HttpServer>, |
| 222 |
sockets: Vec<(SocketAddr, crate::udp::Socket)>, |
| 223 |
) -> Self { |
| 224 |
Self { |
| 225 |
now, |
| 226 |
server, |
| 227 |
timeout: None, |
| 228 |
sockets, |
| 229 |
recv_buf: RecvBuf::new(), |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
/// Tries to find a socket, but then just falls back to sending from the first. |
| 234 |
fn find_socket( |
| 235 |
sockets: &mut [(SocketAddr, crate::udp::Socket)], |
| 236 |
addr: SocketAddr, |
| 237 |
) -> &mut crate::udp::Socket { |
| 238 |
let ((_host, first_socket), rest) = sockets.split_first_mut().unwrap(); |
| 239 |
rest.iter_mut() |
| 240 |
.map(|(_host, socket)| socket) |
| 241 |
.find(|socket| socket.local_addr().is_ok_and(|a| a == addr)) |
| 242 |
.unwrap_or(first_socket) |
| 243 |
} |
| 244 |
|
| 245 |
// Free function (i.e. not taking `&mut self: ServerRunner`) to be callable by |
| 246 |
// `ServerRunner::read_and_process` while holding a reference to |
| 247 |
// `ServerRunner::recv_buf`. |
| 248 |
async fn process_inner( |
| 249 |
server: &mut Box<dyn HttpServer>, |
| 250 |
timeout: &mut Option<Pin<Box<Sleep>>>, |
| 251 |
sockets: &mut [(SocketAddr, crate::udp::Socket)], |
| 252 |
now: &dyn Fn() -> Instant, |
| 253 |
mut input_dgram: Option<Datagram<&mut [u8]>>, |
| 254 |
) -> Result<(), io::Error> { |
| 255 |
loop { |
| 256 |
match server.process(input_dgram.take(), now()) { |
| 257 |
Output::Datagram(dgram) => { |
| 258 |
let socket = Self::find_socket(sockets, dgram.source()); |
| 259 |
loop { |
| 260 |
// Optimistically attempt sending datagram. In case the |
| 261 |
// OS buffer is full, wait till socket is writable then |
| 262 |
// try again. |
| 263 |
match socket.send(&dgram) { |
| 264 |
Ok(()) => break, |
| 265 |
Err(e) if e.kind() == io::ErrorKind::WouldBlock => { |
| 266 |
socket.writable().await?; |
| 267 |
// Now try again. |
| 268 |
} |
| 269 |
e @ Err(_) => return e, |
| 270 |
} |
| 271 |
} |
| 272 |
} |
| 273 |
Output::Callback(new_timeout) => { |
| 274 |
qdebug!("Setting timeout of {new_timeout:?}"); |
| 275 |
*timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); |
| 276 |
break; |
| 277 |
} |
| 278 |
Output::None => break, |
| 279 |
} |
| 280 |
} |
| 281 |
Ok(()) |
| 282 |
} |
| 283 |
|
| 284 |
async fn read_and_process(&mut self, sockets_index: usize) -> Result<(), io::Error> { |
| 285 |
loop { |
| 286 |
let (host, socket) = &mut self.sockets[sockets_index]; |
| 287 |
let Some(input_dgrams) = socket.recv(*host, &mut self.recv_buf)? else { |
| 288 |
break; |
| 289 |
}; |
| 290 |
|
| 291 |
for input_dgram in input_dgrams { |
| 292 |
Self::process_inner( |
| 293 |
&mut self.server, |
| 294 |
&mut self.timeout, |
| 295 |
&mut self.sockets, |
| 296 |
&self.now, |
| 297 |
Some(input_dgram), |
| 298 |
) |
| 299 |
.await?; |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
Ok(()) |
| 304 |
} |
| 305 |
|
| 306 |
async fn process(&mut self) -> Result<(), io::Error> { |
| 307 |
Self::process_inner( |
| 308 |
&mut self.server, |
| 309 |
&mut self.timeout, |
| 310 |
&mut self.sockets, |
| 311 |
&self.now, |
| 312 |
None, |
| 313 |
) |
| 314 |
.await |
| 315 |
} |
| 316 |
|
| 317 |
// Wait for any of the sockets to be readable or the timeout to fire. |
| 318 |
async fn ready(&mut self) -> Result<Ready, io::Error> { |
| 319 |
let sockets_ready = select_all( |
| 320 |
self.sockets |
| 321 |
.iter() |
| 322 |
.map(|(_host, socket)| Box::pin(socket.readable())), |
| 323 |
) |
| 324 |
.map(|(res, inx, _)| match res { |
| 325 |
Ok(()) => Ok(Ready::Socket(inx)), |
| 326 |
Err(e) => Err(e), |
| 327 |
}); |
| 328 |
let timeout_ready = self |
| 329 |
.timeout |
| 330 |
.as_mut() |
| 331 |
.map_or_else(|| Either::Right(futures::future::pending()), Either::Left) |
| 332 |
.map(|()| Ok(Ready::Timeout)); |
| 333 |
select(sockets_ready, timeout_ready).await.factor_first().0 |
| 334 |
} |
| 335 |
|
| 336 |
pub async fn run(mut self) -> Res<()> { |
| 337 |
loop { |
| 338 |
self.server.process_events((self.now)()); |
| 339 |
self.process().await?; |
| 340 |
|
| 341 |
if self.server.has_events() { |
| 342 |
continue; |
| 343 |
} |
| 344 |
|
| 345 |
match self.ready().await? { |
| 346 |
Ready::Socket(sockets_index) => { |
| 347 |
self.read_and_process(sockets_index).await?; |
| 348 |
} |
| 349 |
Ready::Timeout => { |
| 350 |
self.timeout = None; |
| 351 |
self.process().await?; |
| 352 |
} |
| 353 |
} |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
enum Ready { |
| 359 |
Socket(usize), |
| 360 |
Timeout, |
| 361 |
} |
| 362 |
|
| 363 |
pub async fn server(mut args: Args) -> Res<()> { |
| 364 |
neqo_common::log::init( |
| 365 |
args.shared |
| 366 |
.verbose |
| 367 |
.as_ref() |
| 368 |
.map(clap_verbosity_flag::Verbosity::log_level_filter), |
| 369 |
); |
| 370 |
assert!(!args.key.is_empty(), "Need at least one key"); |
| 371 |
|
| 372 |
init_db(args.db.clone())?; |
| 373 |
|
| 374 |
if let Some(testcase) = args.shared.qns_test.as_ref() { |
| 375 |
if args.shared.quic_parameters.quic_version.is_empty() { |
| 376 |
// Quic Interop Runner expects the server to support `Version1` |
| 377 |
// only. Exceptions are testcases `versionnegotiation` (not yet |
| 378 |
// implemented) and `v2`. |
| 379 |
if testcase != "v2" { |
| 380 |
args.shared.quic_parameters.quic_version = vec![Version::Version1]; |
| 381 |
} |
| 382 |
} else { |
| 383 |
qwarn!("Both -V and --qns-test were set. Ignoring testcase specific versions"); |
| 384 |
} |
| 385 |
|
| 386 |
// These are the default for all tests except http3. |
| 387 |
args.shared.alpn = String::from("hq-interop"); |
| 388 |
// TODO: More options to deduplicate with client? |
| 389 |
match testcase.as_str() { |
| 390 |
"http3" => { |
| 391 |
args.shared.alpn = String::from("h3"); |
| 392 |
} |
| 393 |
"zerortt" => args.shared.quic_parameters.max_streams_bidi = 100, |
| 394 |
"handshake" | "transfer" | "resumption" | "multiconnect" | "v2" | "ecn" => {} |
| 395 |
"connectionmigration" => { |
| 396 |
if args.shared.quic_parameters.preferred_address().is_none() { |
| 397 |
qerror!("No preferred addresses set for connectionmigration test"); |
| 398 |
exit(127); |
| 399 |
} |
| 400 |
} |
| 401 |
"chacha20" => { |
| 402 |
args.shared.ciphers.clear(); |
| 403 |
args.shared |
| 404 |
.ciphers |
| 405 |
.extend_from_slice(&[String::from("TLS_CHACHA20_POLY1305_SHA256")]); |
| 406 |
} |
| 407 |
"retry" => args.retry = true, |
| 408 |
_ => exit(127), |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
let hosts = args.listen_addresses(); |
| 413 |
if hosts.is_empty() { |
| 414 |
qerror!("No valid hosts defined"); |
| 415 |
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No hosts").into()); |
| 416 |
} |
| 417 |
let sockets = hosts |
| 418 |
.into_iter() |
| 419 |
.map(|host| { |
| 420 |
let socket = crate::udp::Socket::bind(host)?; |
| 421 |
qinfo!( |
| 422 |
"Server waiting for connection on: {:?}", |
| 423 |
socket.local_addr() |
| 424 |
); |
| 425 |
|
| 426 |
Ok((host, socket)) |
| 427 |
}) |
| 428 |
.collect::<Result<_, io::Error>>()?; |
| 429 |
|
| 430 |
// Note: this is the exception to the case where we use `Args::now`. |
| 431 |
let anti_replay = AntiReplay::new(Instant::now(), ANTI_REPLAY_WINDOW, 7, 14) |
| 432 |
.expect("unable to setup anti-replay"); |
| 433 |
let cid_mgr = Rc::new(RefCell::new(RandomConnectionIdGenerator::new(10))); |
| 434 |
|
| 435 |
let server: Box<dyn HttpServer> = if args.shared.alpn == "h3" { |
| 436 |
Box::new(http3::HttpServer::new(&args, anti_replay, cid_mgr)) |
| 437 |
} else { |
| 438 |
Box::new( |
| 439 |
http09::HttpServer::new(&args, anti_replay, cid_mgr).expect("We cannot make a server!"), |
| 440 |
) |
| 441 |
}; |
| 442 |
|
| 443 |
ServerRunner::new(Box::new(move || args.now()), server, sockets) |
| 444 |
.run() |
| 445 |
.await |
| 446 |
} |