| 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 0.9](https://www.w3.org/Protocols/HTTP/AsImplemented.html) 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, qdebug, qinfo, qwarn, Datagram}; |
| 24 |
use neqo_crypto::{AuthenticationStatus, ResumptionToken}; |
| 25 |
use neqo_transport::{ |
| 26 |
CloseReason, Connection, ConnectionEvent, ConnectionIdGenerator, EmptyConnectionIdGenerator, |
| 27 |
Error, Output, RandomConnectionIdGenerator, State, StreamId, StreamType, |
| 28 |
}; |
| 29 |
use url::Url; |
| 30 |
|
| 31 |
use super::{get_output_file, qlog_new, Args, CloseState, Res}; |
| 32 |
use crate::STREAM_IO_BUFFER_SIZE; |
| 33 |
|
| 34 |
pub struct Handler<'a> { |
| 35 |
streams: HashMap<StreamId, Option<BufWriter<File>>>, |
| 36 |
url_queue: VecDeque<Url>, |
| 37 |
handled_urls: Vec<Url>, |
| 38 |
all_paths: Vec<PathBuf>, |
| 39 |
args: &'a Args, |
| 40 |
token: Option<ResumptionToken>, |
| 41 |
needs_key_update: bool, |
| 42 |
read_buffer: Vec<u8>, |
| 43 |
} |
| 44 |
|
| 45 |
impl Handler<'_> { |
| 46 |
fn reinit(&mut self) { |
| 47 |
for url in self.handled_urls.drain(..) { |
| 48 |
self.url_queue.push_front(url); |
| 49 |
} |
| 50 |
self.streams.clear(); |
| 51 |
self.all_paths.clear(); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
impl super::Handler for Handler<'_> { |
| 56 |
type Client = Connection; |
| 57 |
|
| 58 |
fn handle(&mut self, client: &mut Self::Client) -> Res<bool> { |
| 59 |
while let Some(event) = client.next_event() { |
| 60 |
if self.needs_key_update { |
| 61 |
match client.initiate_key_update() { |
| 62 |
Ok(()) => { |
| 63 |
qdebug!("Keys updated"); |
| 64 |
self.needs_key_update = false; |
| 65 |
self.download_urls(client); |
| 66 |
} |
| 67 |
Err(Error::KeyUpdateBlocked) => (), |
| 68 |
Err(e) => return Err(e.into()), |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
match event { |
| 73 |
ConnectionEvent::AuthenticationNeeded => { |
| 74 |
client.authenticated(AuthenticationStatus::Ok, Instant::now()); |
| 75 |
} |
| 76 |
ConnectionEvent::RecvStreamReadable { stream_id } => { |
| 77 |
self.read(client, stream_id)?; |
| 78 |
} |
| 79 |
ConnectionEvent::SendStreamWritable { stream_id } => { |
| 80 |
qdebug!("stream {stream_id} writable"); |
| 81 |
} |
| 82 |
ConnectionEvent::SendStreamComplete { stream_id } => { |
| 83 |
qdebug!("stream {stream_id} complete"); |
| 84 |
} |
| 85 |
ConnectionEvent::SendStreamCreatable { stream_type } => { |
| 86 |
qdebug!("stream {stream_type:?} creatable"); |
| 87 |
if stream_type == StreamType::BiDi { |
| 88 |
self.download_urls(client); |
| 89 |
} |
| 90 |
} |
| 91 |
ConnectionEvent::StateChange( |
| 92 |
State::WaitInitial | State::Handshaking | State::Connected, |
| 93 |
) => { |
| 94 |
qdebug!("{event:?}"); |
| 95 |
self.download_urls(client); |
| 96 |
} |
| 97 |
ConnectionEvent::ZeroRttRejected => { |
| 98 |
qdebug!("{event:?}"); |
| 99 |
// All 0-RTT data was rejected. We need to retransmit it. |
| 100 |
self.reinit(); |
| 101 |
self.download_urls(client); |
| 102 |
} |
| 103 |
ConnectionEvent::ResumptionToken(token) => { |
| 104 |
self.token = Some(token); |
| 105 |
} |
| 106 |
_ => { |
| 107 |
qwarn!("Unhandled event {event:?}"); |
| 108 |
} |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
if !self.streams.is_empty() || !self.url_queue.is_empty() { |
| 113 |
return Ok(false); |
| 114 |
} |
| 115 |
|
| 116 |
if self.args.resume && self.token.is_none() { |
| 117 |
self.token = client.take_resumption_token(Instant::now()); |
| 118 |
} |
| 119 |
|
| 120 |
Ok(true) |
| 121 |
} |
| 122 |
|
| 123 |
fn take_token(&mut self) -> Option<ResumptionToken> { |
| 124 |
self.token.take() |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
pub fn create_client( |
| 129 |
args: &Args, |
| 130 |
local_addr: SocketAddr, |
| 131 |
remote_addr: SocketAddr, |
| 132 |
hostname: &str, |
| 133 |
resumption_token: Option<ResumptionToken>, |
| 134 |
) -> Res<Connection> { |
| 135 |
let alpn = match args.shared.alpn.as_str() { |
| 136 |
"hq-29" | "hq-30" | "hq-31" | "hq-32" => args.shared.alpn.as_str(), |
| 137 |
_ => "hq-interop", |
| 138 |
}; |
| 139 |
let cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>> = if args.cid_len == 0 { |
| 140 |
Rc::new(RefCell::new(EmptyConnectionIdGenerator::default())) |
| 141 |
} else { |
| 142 |
Rc::new(RefCell::new(RandomConnectionIdGenerator::new( |
| 143 |
args.cid_len.into(), |
| 144 |
))) |
| 145 |
}; |
| 146 |
let mut client = Connection::new_client( |
| 147 |
hostname, |
| 148 |
&[alpn], |
| 149 |
cid_generator, |
| 150 |
local_addr, |
| 151 |
remote_addr, |
| 152 |
args.shared.quic_parameters.get(alpn), |
| 153 |
Instant::now(), |
| 154 |
)?; |
| 155 |
|
| 156 |
if let Some(tok) = resumption_token { |
| 157 |
client.enable_resumption(Instant::now(), tok)?; |
| 158 |
} |
| 159 |
|
| 160 |
let ciphers = args.get_ciphers(); |
| 161 |
if !ciphers.is_empty() { |
| 162 |
client.set_ciphers(&ciphers)?; |
| 163 |
} |
| 164 |
|
| 165 |
client.set_qlog(qlog_new( |
| 166 |
args, |
| 167 |
hostname, |
| 168 |
client.odcid().ok_or(Error::InternalError)?, |
| 169 |
)?); |
| 170 |
|
| 171 |
Ok(client) |
| 172 |
} |
| 173 |
|
| 174 |
impl TryFrom<&State> for CloseState { |
| 175 |
type Error = CloseReason; |
| 176 |
|
| 177 |
fn try_from(value: &State) -> Result<Self, Self::Error> { |
| 178 |
let (state, error) = match value { |
| 179 |
State::Closing { error, .. } | State::Draining { error, .. } => (Self::Closing, error), |
| 180 |
State::Closed(error) => (Self::Closed, error), |
| 181 |
_ => return Ok(Self::NotClosing), |
| 182 |
}; |
| 183 |
|
| 184 |
if error.is_error() { |
| 185 |
Err(error.clone()) |
| 186 |
} else { |
| 187 |
Ok(state) |
| 188 |
} |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
impl super::Client for Connection { |
| 193 |
fn process_output(&mut self, now: Instant) -> Output { |
| 194 |
self.process_output(now) |
| 195 |
} |
| 196 |
|
| 197 |
fn process_multiple_input<'a>( |
| 198 |
&mut self, |
| 199 |
dgrams: impl IntoIterator<Item = Datagram<&'a mut [u8]>>, |
| 200 |
now: Instant, |
| 201 |
) { |
| 202 |
self.process_multiple_input(dgrams, now); |
| 203 |
} |
| 204 |
|
| 205 |
fn close<S>(&mut self, now: Instant, app_error: neqo_transport::AppError, msg: S) |
| 206 |
where |
| 207 |
S: AsRef<str> + Display, |
| 208 |
{ |
| 209 |
if !self.state().closed() { |
| 210 |
self.close(now, app_error, msg); |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
fn is_closed(&self) -> Result<CloseState, CloseReason> { |
| 215 |
self.state().try_into() |
| 216 |
} |
| 217 |
|
| 218 |
fn stats(&self) -> neqo_transport::Stats { |
| 219 |
self.stats() |
| 220 |
} |
| 221 |
|
| 222 |
fn has_events(&self) -> bool { |
| 223 |
Provider::has_events(self) |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
impl<'b> Handler<'b> { |
| 228 |
pub fn new(url_queue: VecDeque<Url>, args: &'b Args) -> Self { |
| 229 |
Self { |
| 230 |
streams: HashMap::new(), |
| 231 |
url_queue, |
| 232 |
handled_urls: Vec::new(), |
| 233 |
all_paths: Vec::new(), |
| 234 |
args, |
| 235 |
token: None, |
| 236 |
needs_key_update: args.key_update, |
| 237 |
read_buffer: vec![0; STREAM_IO_BUFFER_SIZE], |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
fn download_urls(&mut self, client: &mut Connection) { |
| 242 |
loop { |
| 243 |
if self.url_queue.is_empty() { |
| 244 |
break; |
| 245 |
} |
| 246 |
if self.streams.len() >= self.args.concurrency { |
| 247 |
break; |
| 248 |
} |
| 249 |
if !self.download_next(client) { |
| 250 |
break; |
| 251 |
} |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
fn download_next(&mut self, client: &mut Connection) -> bool { |
| 256 |
if self.needs_key_update { |
| 257 |
qdebug!("Deferring requests until after first key update"); |
| 258 |
return false; |
| 259 |
} |
| 260 |
let url = self |
| 261 |
.url_queue |
| 262 |
.pop_front() |
| 263 |
.expect("download_next called with empty queue"); |
| 264 |
match client.stream_create(StreamType::BiDi) { |
| 265 |
Ok(client_stream_id) => { |
| 266 |
qinfo!("Created stream {client_stream_id} for {url}"); |
| 267 |
let req = format!("GET {}\r\n", url.path()); |
| 268 |
_ = client |
| 269 |
.stream_send(client_stream_id, req.as_bytes()) |
| 270 |
.unwrap(); |
| 271 |
client.stream_close_send(client_stream_id).unwrap(); |
| 272 |
let out_file = |
| 273 |
get_output_file(&url, self.args.output_dir.as_ref(), &mut self.all_paths); |
| 274 |
self.streams.insert(client_stream_id, out_file); |
| 275 |
self.handled_urls.push(url); |
| 276 |
true |
| 277 |
} |
| 278 |
Err(e @ (Error::StreamLimitError | Error::ConnectionState)) => { |
| 279 |
qwarn!("Cannot create stream {e:?}"); |
| 280 |
self.url_queue.push_front(url); |
| 281 |
false |
| 282 |
} |
| 283 |
Err(e) => { |
| 284 |
panic!("Error creating stream {e:?}"); |
| 285 |
} |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
/// Read and maybe print received data from a stream. |
| 290 |
// Returns bool: was fin received? |
| 291 |
fn read_from_stream( |
| 292 |
client: &mut Connection, |
| 293 |
stream_id: StreamId, |
| 294 |
read_buffer: &mut [u8], |
| 295 |
output_read_data: bool, |
| 296 |
maybe_out_file: &mut Option<BufWriter<File>>, |
| 297 |
) -> Res<bool> { |
| 298 |
loop { |
| 299 |
let (sz, fin) = client.stream_recv(stream_id, read_buffer)?; |
| 300 |
if sz == 0 { |
| 301 |
return Ok(fin); |
| 302 |
} |
| 303 |
let read_buffer = &read_buffer[0..sz]; |
| 304 |
|
| 305 |
if let Some(out_file) = maybe_out_file { |
| 306 |
out_file.write_all(read_buffer)?; |
| 307 |
} else if !output_read_data { |
| 308 |
qdebug!("READ[{stream_id}]: {} bytes", read_buffer.len()); |
| 309 |
} else { |
| 310 |
qdebug!( |
| 311 |
"READ[{stream_id}]: {}", |
| 312 |
std::str::from_utf8(read_buffer).map_err(|_| Error::InvalidInput)? |
| 313 |
); |
| 314 |
} |
| 315 |
if fin { |
| 316 |
return Ok(true); |
| 317 |
} |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
fn read(&mut self, client: &mut Connection, stream_id: StreamId) -> Res<()> { |
| 322 |
match self.streams.get_mut(&stream_id) { |
| 323 |
None => { |
| 324 |
qwarn!("Data on unexpected stream: {stream_id}"); |
| 325 |
return Ok(()); |
| 326 |
} |
| 327 |
Some(maybe_out_file) => { |
| 328 |
let fin_recvd = Self::read_from_stream( |
| 329 |
client, |
| 330 |
stream_id, |
| 331 |
&mut self.read_buffer, |
| 332 |
self.args.output_read_data, |
| 333 |
maybe_out_file, |
| 334 |
)?; |
| 335 |
|
| 336 |
if fin_recvd { |
| 337 |
if let Some(mut out_file) = maybe_out_file.take() { |
| 338 |
out_file.flush()?; |
| 339 |
} else { |
| 340 |
qinfo!("<FIN[{stream_id}]>"); |
| 341 |
} |
| 342 |
self.streams.remove(&stream_id); |
| 343 |
self.download_urls(client); |
| 344 |
} |
| 345 |
} |
| 346 |
} |
| 347 |
Ok(()) |
| 348 |
} |
| 349 |
} |