From 161d22d94a6b6e19b7c5bcf2d0979fa5a2465188 Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 10:18:54 +0200 Subject: [PATCH 1/9] fix: Replace `neqo_common::log` with `log` crate Fixes #1963 --- Cargo.lock | 6 +- neqo-bin/Cargo.toml | 1 + neqo-bin/src/client/http09.rs | 31 +-- neqo-bin/src/client/http3.rs | 31 +-- neqo-bin/src/client/mod.rs | 39 ++- neqo-bin/src/lib.rs | 31 ++- neqo-bin/src/server/http09.rs | 23 +- neqo-bin/src/server/http3.rs | 9 +- neqo-bin/src/server/mod.rs | 17 +- neqo-common/Cargo.toml | 1 - neqo-common/src/lib.rs | 1 - neqo-common/src/log.rs | 115 -------- neqo-common/src/qlog.rs | 6 +- neqo-common/tests/log.rs | 58 ---- neqo-crypto/src/agent.rs | 31 ++- neqo-crypto/src/agentio.rs | 15 +- neqo-crypto/src/cert.rs | 4 +- neqo-crypto/src/ech.rs | 4 +- neqo-crypto/src/lib.rs | 4 +- neqo-crypto/src/secrets.rs | 4 +- neqo-crypto/src/selfencrypt.rs | 15 +- neqo-crypto/tests/handshake.rs | 6 +- neqo-http3/src/buffered_send_stream.rs | 6 +- neqo-http3/src/connection.rs | 114 ++++---- neqo-http3/src/connection_client.rs | 54 ++-- neqo-http3/src/connection_server.rs | 24 +- neqo-http3/src/control_stream_local.rs | 5 +- neqo-http3/src/control_stream_remote.rs | 6 +- .../extended_connect/webtransport_session.rs | 13 +- neqo-http3/src/features/mod.rs | 4 +- neqo-http3/src/frames/reader.rs | 11 +- neqo-http3/src/push_controller.rs | 30 +-- neqo-http3/src/recv_message.rs | 29 +- neqo-http3/src/send_message.rs | 21 +- neqo-http3/src/server.rs | 9 +- neqo-http3/src/server_events.rs | 21 +- neqo-http3/src/stream_type_reader.rs | 10 +- neqo-http3/tests/httpconn.rs | 13 +- neqo-qpack/src/decoder.rs | 11 +- neqo-qpack/src/decoder_instructions.rs | 6 +- neqo-qpack/src/encoder.rs | 27 +- neqo-qpack/src/encoder_instructions.rs | 12 +- neqo-qpack/src/header_block.rs | 54 ++-- neqo-qpack/src/reader.rs | 6 +- neqo-qpack/src/table.rs | 31 +-- neqo-transport/src/ackrate.rs | 10 +- neqo-transport/src/addr_valid.rs | 29 +- neqo-transport/src/cc/classic_cc.rs | 42 ++- neqo-transport/src/cc/cubic.rs | 4 +- neqo-transport/src/cid.rs | 7 +- neqo-transport/src/connection/dump.rs | 8 +- neqo-transport/src/connection/idle.rs | 4 +- neqo-transport/src/connection/mod.rs | 249 ++++++++---------- neqo-transport/src/connection/saved.rs | 7 +- neqo-transport/src/connection/tests/cc.rs | 15 +- .../src/connection/tests/handshake.rs | 47 ++-- neqo-transport/src/connection/tests/idle.rs | 9 +- neqo-transport/src/connection/tests/keys.rs | 11 +- .../src/connection/tests/migration.rs | 9 +- neqo-transport/src/connection/tests/mod.rs | 29 +- .../src/connection/tests/recovery.rs | 20 +- neqo-transport/src/connection/tests/stream.rs | 15 +- .../src/connection/tests/zerortt.rs | 5 +- neqo-transport/src/crypto.rs | 109 ++++---- neqo-transport/src/ecn.rs | 19 +- neqo-transport/src/fc.rs | 7 +- neqo-transport/src/frame.rs | 11 +- neqo-transport/src/lib.rs | 4 +- neqo-transport/src/pace.rs | 10 +- neqo-transport/src/packet/mod.rs | 17 +- neqo-transport/src/packet/retry.rs | 4 +- neqo-transport/src/path.rs | 49 ++-- neqo-transport/src/pmtud.rs | 29 +- neqo-transport/src/qlog.rs | 7 +- neqo-transport/src/recovery/mod.rs | 42 ++- neqo-transport/src/recv_stream.rs | 30 ++- neqo-transport/src/rtt.rs | 7 +- neqo-transport/src/send_stream.rs | 78 +++--- neqo-transport/src/sender.rs | 5 +- neqo-transport/src/server.rs | 55 ++-- neqo-transport/src/shuffle.rs | 5 +- neqo-transport/src/stats.rs | 8 +- neqo-transport/src/streams.rs | 9 +- neqo-transport/src/tparams.rs | 35 +-- neqo-transport/src/tracking.rs | 21 +- neqo-transport/src/version.rs | 7 +- neqo-transport/tests/common/mod.rs | 3 +- neqo-transport/tests/retry.rs | 9 +- neqo-transport/tests/server.rs | 5 +- neqo-udp/src/lib.rs | 14 +- test-fixture/src/header_protection.rs | 5 +- test-fixture/src/lib.rs | 5 +- test-fixture/src/sim/connection.rs | 15 +- test-fixture/src/sim/drop.rs | 5 +- test-fixture/src/sim/mod.rs | 29 +- test-fixture/src/sim/taildrop.rs | 13 +- 96 files changed, 994 insertions(+), 1166 deletions(-) delete mode 100644 neqo-common/src/log.rs delete mode 100644 neqo-common/tests/log.rs diff --git a/Cargo.lock b/Cargo.lock index 914f9b7ffe..95020625f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -364,9 +364,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.10.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" dependencies = [ "log", ] @@ -802,6 +802,7 @@ dependencies = [ "clap", "clap-verbosity-flag", "criterion", + "env_logger", "futures", "hex", "log", @@ -824,7 +825,6 @@ version = "0.11.0" dependencies = [ "criterion", "enum-map", - "env_logger", "hex", "log", "neqo-crypto", diff --git a/neqo-bin/Cargo.toml b/neqo-bin/Cargo.toml index ce8accbf0a..565ddb086b 100644 --- a/neqo-bin/Cargo.toml +++ b/neqo-bin/Cargo.toml @@ -29,6 +29,7 @@ workspace = true # Not used in Firefox, so we can be liberal with dependency versions clap = { version = "4.4", default-features = false, features = ["std", "help", "usage", "error-context", "suggestions", "derive"] } clap-verbosity-flag = { version = "3.0", default-features = false, features = ["log"] } +env_logger = { version = "0.10", default-features = false } futures = { version = "0.3", default-features = false, features = ["alloc"] } hex = { version = "0.4", default-features = false, features = ["std"] } log = { workspace = true } diff --git a/neqo-bin/src/client/http09.rs b/neqo-bin/src/client/http09.rs index f7f62bf57a..7038ed9cc4 100644 --- a/neqo-bin/src/client/http09.rs +++ b/neqo-bin/src/client/http09.rs @@ -17,7 +17,8 @@ use std::{ time::Instant, }; -use neqo_common::{event::Provider, qdebug, qinfo, qwarn, Datagram}; +use log::{debug, info, warn}; +use neqo_common::{event::Provider, Datagram}; use neqo_crypto::{AuthenticationStatus, ResumptionToken}; use neqo_transport::{ CloseReason, Connection, ConnectionEvent, ConnectionIdGenerator, EmptyConnectionIdGenerator, @@ -57,7 +58,7 @@ impl super::Handler for Handler<'_> { if self.needs_key_update { match client.initiate_key_update() { Ok(()) => { - qdebug!("Keys updated"); + debug!("Keys updated"); self.needs_key_update = false; self.download_urls(client); } @@ -74,13 +75,13 @@ impl super::Handler for Handler<'_> { self.read(client, stream_id)?; } ConnectionEvent::SendStreamWritable { stream_id } => { - qdebug!("stream {stream_id} writable"); + debug!("stream {stream_id} writable"); } ConnectionEvent::SendStreamComplete { stream_id } => { - qdebug!("stream {stream_id} complete"); + debug!("stream {stream_id} complete"); } ConnectionEvent::SendStreamCreatable { stream_type } => { - qdebug!("stream {stream_type:?} creatable"); + debug!("stream {stream_type:?} creatable"); if stream_type == StreamType::BiDi { self.download_urls(client); } @@ -88,11 +89,11 @@ impl super::Handler for Handler<'_> { ConnectionEvent::StateChange( State::WaitInitial | State::Handshaking | State::Connected, ) => { - qdebug!("{event:?}"); + debug!("{event:?}"); self.download_urls(client); } ConnectionEvent::ZeroRttRejected => { - qdebug!("{event:?}"); + debug!("{event:?}"); // All 0-RTT data was rejected. We need to retransmit it. self.reinit(); self.download_urls(client); @@ -101,7 +102,7 @@ impl super::Handler for Handler<'_> { self.token = Some(token); } _ => { - qwarn!("Unhandled event {event:?}"); + warn!("Unhandled event {event:?}"); } } } @@ -247,7 +248,7 @@ impl<'b> Handler<'b> { fn download_next(&mut self, client: &mut Connection) -> bool { if self.needs_key_update { - qdebug!("Deferring requests until after first key update"); + debug!("Deferring requests until after first key update"); return false; } let url = self @@ -256,7 +257,7 @@ impl<'b> Handler<'b> { .expect("download_next called with empty queue"); match client.stream_create(StreamType::BiDi) { Ok(client_stream_id) => { - qinfo!("Created stream {client_stream_id} for {url}"); + info!("Created stream {client_stream_id} for {url}"); let req = format!("GET {}\r\n", url.path()); _ = client .stream_send(client_stream_id, req.as_bytes()) @@ -269,7 +270,7 @@ impl<'b> Handler<'b> { true } Err(e @ (Error::StreamLimitError | Error::ConnectionState)) => { - qwarn!("Cannot create stream {e:?}"); + warn!("Cannot create stream {e:?}"); self.url_queue.push_front(url); false } @@ -298,9 +299,9 @@ impl<'b> Handler<'b> { if let Some(out_file) = maybe_out_file { out_file.write_all(read_buffer)?; } else if !output_read_data { - qdebug!("READ[{stream_id}]: {} bytes", read_buffer.len()); + debug!("READ[{stream_id}]: {} bytes", read_buffer.len()); } else { - qdebug!( + debug!( "READ[{}]: {}", stream_id, std::str::from_utf8(read_buffer).unwrap() @@ -315,7 +316,7 @@ impl<'b> Handler<'b> { fn read(&mut self, client: &mut Connection, stream_id: StreamId) -> Res<()> { match self.streams.get_mut(&stream_id) { None => { - qwarn!("Data on unexpected stream: {stream_id}"); + warn!("Data on unexpected stream: {stream_id}"); return Ok(()); } Some(maybe_out_file) => { @@ -331,7 +332,7 @@ impl<'b> Handler<'b> { if let Some(mut out_file) = maybe_out_file.take() { out_file.flush()?; } else { - qinfo!(""); + info!(""); } self.streams.remove(&stream_id); self.download_urls(client); diff --git a/neqo-bin/src/client/http3.rs b/neqo-bin/src/client/http3.rs index 3a5a777cb6..d991a67533 100644 --- a/neqo-bin/src/client/http3.rs +++ b/neqo-bin/src/client/http3.rs @@ -18,7 +18,8 @@ use std::{ time::Instant, }; -use neqo_common::{event::Provider, hex, qdebug, qinfo, qwarn, Datagram, Header}; +use log::{debug, info, warn}; +use neqo_common::{event::Provider, hex, Datagram, Header}; use neqo_crypto::{AuthenticationStatus, ResumptionToken}; use neqo_http3::{Error, Http3Client, Http3ClientEvent, Http3Parameters, Http3State, Priority}; use neqo_transport::{ @@ -187,7 +188,7 @@ impl super::Handler for Handler<'_> { if let Some(handler) = self.url_handler.stream_handler(stream_id) { handler.process_header_ready(stream_id, fin, headers); } else { - qwarn!("Data on unexpected stream: {stream_id}"); + warn!("Data on unexpected stream: {stream_id}"); } if fin { self.url_handler.on_stream_fin(client, stream_id); @@ -197,7 +198,7 @@ impl super::Handler for Handler<'_> { let mut stream_done = false; match self.url_handler.stream_handler(stream_id) { None => { - qwarn!("Data on unexpected stream: {stream_id}"); + warn!("Data on unexpected stream: {stream_id}"); } Some(handler) => loop { let (sz, fin) = client @@ -229,7 +230,7 @@ impl super::Handler for Handler<'_> { Http3ClientEvent::DataWritable { stream_id } => { match self.url_handler.stream_handler(stream_id) { None => { - qwarn!("Data on unexpected stream: {stream_id}"); + warn!("Data on unexpected stream: {stream_id}"); } Some(handler) => { handler.process_data_writable(client, stream_id); @@ -238,18 +239,18 @@ impl super::Handler for Handler<'_> { } Http3ClientEvent::StateChange(Http3State::Connected) | Http3ClientEvent::RequestsCreatable => { - qinfo!("{event:?}"); + info!("{event:?}"); self.url_handler.process_urls(client); } Http3ClientEvent::ZeroRttRejected => { - qinfo!("{event:?}"); + info!("{event:?}"); // All 0-RTT data was rejected. We need to retransmit it. self.reinit(); self.url_handler.process_urls(client); } Http3ClientEvent::ResumptionToken(t) => self.token = Some(t), _ => { - qwarn!("Unhandled event {event:?}"); + warn!("Unhandled event {event:?}"); } } } @@ -281,7 +282,7 @@ struct DownloadStreamHandler { impl StreamHandler for DownloadStreamHandler { fn process_header_ready(&mut self, stream_id: StreamId, fin: bool, headers: Vec
) { if self.out_file.is_none() { - qdebug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); + debug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); } } @@ -298,18 +299,18 @@ impl StreamHandler for DownloadStreamHandler { } return Ok(true); } else if !output_read_data { - qdebug!("READ[{stream_id}]: {} bytes", data.len()); + debug!("READ[{stream_id}]: {} bytes", data.len()); } else if let Ok(txt) = std::str::from_utf8(data) { - qdebug!("READ[{stream_id}]: {txt}"); + debug!("READ[{stream_id}]: {txt}"); } else { - qdebug!("READ[{}]: 0x{}", stream_id, hex(data)); + debug!("READ[{}]: 0x{}", stream_id, hex(data)); } if fin { if let Some(mut out_file) = self.out_file.take() { out_file.flush()?; } else { - qdebug!(""); + debug!(""); } } @@ -326,7 +327,7 @@ struct UploadStreamHandler { impl StreamHandler for UploadStreamHandler { fn process_header_ready(&mut self, stream_id: StreamId, fin: bool, headers: Vec
) { - qdebug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); + debug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); } fn process_data_readable( @@ -341,7 +342,7 @@ impl StreamHandler for UploadStreamHandler { let parsed: usize = trimmed_txt.parse().unwrap(); if parsed == self.data.len() { let upload_time = Instant::now().duration_since(self.start); - qinfo!("Stream ID: {stream_id:?}, Upload time: {upload_time:?}"); + info!("Stream ID: {stream_id:?}, Upload time: {upload_time:?}"); } } else { panic!("Unexpected data [{}]: 0x{}", stream_id, hex(data)); @@ -399,7 +400,7 @@ impl UrlHandler<'_> { Priority::default(), ) { Ok(client_stream_id) => { - qdebug!("Successfully created stream id {client_stream_id} for {url}"); + debug!("Successfully created stream id {client_stream_id} for {url}"); let handler: Box = match self.args.method.as_str() { "GET" => { diff --git a/neqo-bin/src/client/mod.rs b/neqo-bin/src/client/mod.rs index 24102cd283..d057afe1af 100644 --- a/neqo-bin/src/client/mod.rs +++ b/neqo-bin/src/client/mod.rs @@ -23,7 +23,8 @@ use futures::{ future::{select, Either}, FutureExt, TryFutureExt, }; -use neqo_common::{qdebug, qerror, qinfo, qlog::NeqoQlog, qwarn, Datagram, Role}; +use log::{debug, error, info, warn}; +use neqo_common::{qlog::NeqoQlog, Datagram, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256}, init, Cipher, ResumptionToken, @@ -33,7 +34,7 @@ use neqo_transport::{AppError, CloseReason, ConnectionId, Version}; use tokio::time::Sleep; use url::{Host, Origin, Url}; -use crate::SharedArgs; +use crate::{log_init, SharedArgs}; mod http09; mod http3; @@ -226,12 +227,12 @@ impl Args { }; if self.key_update { - qerror!("internal option key_update set by user"); + error!("internal option key_update set by user"); exit(127) } if self.resume { - qerror!("internal option resume set by user"); + error!("internal option resume set by user"); exit(127) } @@ -244,7 +245,7 @@ impl Args { self.shared.alpn = String::from("h3"); if let Some(testcase) = &self.test { if testcase.as_str() != "upload" { - qerror!("Unsupported test case: {testcase}"); + error!("Unsupported test case: {testcase}"); exit(127) } @@ -254,14 +255,14 @@ impl Args { "handshake" | "transfer" | "retry" | "ecn" => {} "resumption" => { if self.urls.len() < 2 { - qerror!("Warning: resumption test won't work without >1 URL"); + error!("Warning: resumption test won't work without >1 URL"); exit(127); } self.resume = true; } "zerortt" => { if self.urls.len() < 2 { - qerror!("Warning: zerortt test won't work without >1 URL"); + error!("Warning: zerortt test won't work without >1 URL"); exit(127); } self.resume = true; @@ -315,11 +316,11 @@ fn get_output_file( out_path.push(url_path); if all_paths.contains(&out_path) { - qerror!("duplicate path {}", out_path.display()); + error!("duplicate path {}", out_path.display()); return None; } - qinfo!("Saving {url} to {out_path:?}"); + info!("Saving {url} to {out_path:?}"); if let Some(parent) = out_path.parent() { create_dir_all(parent).ok()?; @@ -448,7 +449,7 @@ impl<'a, H: Handler> Runner<'a, H> { } if self.args.stats { - qinfo!("{:?}", self.client.stats()); + info!("{:?}", self.client.stats()); } Ok(self.handler.take_token()) @@ -462,12 +463,12 @@ impl<'a, H: Handler> Runner<'a, H> { self.socket.send(&dgram)?; } Output::Callback(new_timeout) => { - qdebug!("Setting timeout of {:?}", new_timeout); + debug!("Setting timeout of {:?}", new_timeout); self.timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); break; } Output::None => { - qdebug!("Output::None"); + debug!("Output::None"); break; } } @@ -532,14 +533,14 @@ fn urls_by_origin(urls: &[Url]) -> impl Iterator Some(((h, p), urls)), Origin::Opaque(x) => { - qwarn!("Opaque origin {x:?}"); + warn!("Opaque origin {x:?}"); None } }) } pub async fn client(mut args: Args) -> Res<()> { - neqo_common::log::init( + log_init( args.shared .verbose .as_ref() @@ -553,7 +554,7 @@ pub async fn client(mut args: Args) -> Res<()> { for ((host, port), mut urls) in urls_by_origin(&args.urls) { if args.resume && urls.len() < 2 { - qerror!("Resumption to {host} cannot work without at least 2 URLs."); + error!("Resumption to {host} cannot work without at least 2 URLs."); exit(127); } @@ -564,16 +565,14 @@ pub async fn client(mut args: Args) -> Res<()> { ) }); let Some(remote_addr) = remote_addr else { - qerror!("No compatible address found for: {host}"); + error!("No compatible address found for: {host}"); exit(1); }; let mut socket = crate::udp::Socket::bind(local_addr_for(&remote_addr, 0))?; let real_local = socket.local_addr().unwrap(); - qinfo!( + info!( "{} Client connecting: {:?} -> {:?}", - args.shared.alpn, - real_local, - remote_addr, + args.shared.alpn, real_local, remote_addr, ); let hostname = format!("{host}"); diff --git a/neqo-bin/src/lib.rs b/neqo-bin/src/lib.rs index 1a9f981780..66af6ab33a 100644 --- a/neqo-bin/src/lib.rs +++ b/neqo-bin/src/lib.rs @@ -9,9 +9,11 @@ use std::{ fmt::{self, Display}, + io::Write, net::{SocketAddr, ToSocketAddrs}, path::PathBuf, - time::Duration, + sync::OnceLock, + time::{Duration, Instant}, }; use clap::Parser; @@ -244,6 +246,33 @@ impl QuicParameters { } } +fn since_start() -> Duration { + static START_TIME: OnceLock = OnceLock::new(); + START_TIME.get_or_init(Instant::now).elapsed() +} +pub fn log_init(level_filter: Option) { + let mut builder = env_logger::Builder::from_default_env(); + if let Some(filter) = level_filter { + builder.filter_level(filter); + } + builder.format(|buf, record| { + let elapsed = since_start(); + writeln!( + buf, + "{}s{:3}ms {} {}", + elapsed.as_secs(), + elapsed.as_millis() % 1000, + record.level(), + record.args() + ) + }); + if let Err(e) = builder.try_init() { + eprintln!("Logging initialization error {e:?}"); + } else { + log::debug!("Logging initialized"); + } +} + fn from_str(s: &str) -> Result { let v = u32::from_str_radix(s, 16) .map_err(|_| Error::Argument("versions need to be specified in hex"))?; diff --git a/neqo-bin/src/server/http09.rs b/neqo-bin/src/server/http09.rs index e183a1b045..a1465c50d4 100644 --- a/neqo-bin/src/server/http09.rs +++ b/neqo-bin/src/server/http09.rs @@ -6,7 +6,8 @@ use std::{borrow::Cow, cell::RefCell, collections::HashMap, fmt::Display, rc::Rc, time::Instant}; -use neqo_common::{event::Provider, hex, qdebug, qerror, qinfo, qwarn, Datagram}; +use log::{debug, error, info, warn}; +use neqo_common::{event::Provider, hex, Datagram}; use neqo_crypto::{generate_ech_keys, random, AllowZeroRtt, AntiReplay}; use neqo_http3::Error; use neqo_transport::{ @@ -60,7 +61,7 @@ impl HttpServer { .enable_ech(random::<1>()[0], "public.example", &sk, &pk) .expect("enable ECH"); let cfg = server.ech_config(); - qinfo!("ECHConfigList: {}", hex(cfg)); + info!("ECHConfigList: {}", hex(cfg)); } let is_qns_test = args.shared.qns_test.is_some(); @@ -82,17 +83,17 @@ impl HttpServer { let url_dbg = String::from_utf8(partial.clone()) .unwrap_or_else(|_| format!("", hex(&partial))); if partial.len() < 4096 { - qdebug!("Saving partial URL: {}", url_dbg); + debug!("Saving partial URL: {}", url_dbg); self.read_state.insert(stream_id, partial); } else { - qdebug!("Giving up on partial URL {}", url_dbg); + debug!("Giving up on partial URL {}", url_dbg); conn.borrow_mut().stream_stop_sending(stream_id, 0).unwrap(); } } fn stream_readable(&mut self, stream_id: StreamId, conn: &ConnectionRef) { if !stream_id.is_client_initiated() || !stream_id.is_bidi() { - qdebug!("Stream {} not client-initiated bidi, ignoring", stream_id); + debug!("Stream {} not client-initiated bidi, ignoring", stream_id); return; } let (sz, fin) = conn @@ -102,7 +103,7 @@ impl HttpServer { if sz == 0 { if !fin { - qdebug!("size 0 but !fin"); + debug!("size 0 but !fin"); } return; } @@ -129,12 +130,12 @@ impl HttpServer { let resp: SendData = { let path = path.as_str(); - qdebug!("Path = '{path}'"); + debug!("Path = '{path}'"); if self.is_qns_test { match qns_read_response(path) { Ok(data) => data.into(), Err(e) => { - qerror!("Failed to read {path}: {e}"); + error!("Failed to read {path}: {e}"); b"404".to_vec().into() } } @@ -148,7 +149,7 @@ impl HttpServer { match stream_state.data_to_send { None => stream_state.data_to_send = Some(resp), Some(_) => { - qdebug!("Data already set, doing nothing"); + debug!("Data already set, doing nothing"); } } if stream_state.writable { @@ -167,7 +168,7 @@ impl HttpServer { fn stream_writable(&mut self, stream_id: StreamId, conn: &ConnectionRef) { let Some(stream_state) = self.write_state.get_mut(&stream_id) else { - qwarn!("Unknown stream {stream_id}, ignoring event"); + warn!("Unknown stream {stream_id}, ignoring event"); return; }; @@ -220,7 +221,7 @@ impl super::HttpServer for HttpServer { ConnectionEvent::StateChange(_) | ConnectionEvent::SendStreamCreatable { .. } | ConnectionEvent::SendStreamComplete { .. } => (), - e => qwarn!("unhandled event {e:?}"), + e => warn!("unhandled event {e:?}"), } } } diff --git a/neqo-bin/src/server/http3.rs b/neqo-bin/src/server/http3.rs index bf5a3592e3..54bfa18083 100644 --- a/neqo-bin/src/server/http3.rs +++ b/neqo-bin/src/server/http3.rs @@ -12,7 +12,8 @@ use std::{ time::Instant, }; -use neqo_common::{header::HeadersExt, hex, qdebug, qerror, qinfo, Datagram, Header}; +use log::{debug, error, info}; +use neqo_common::{header::HeadersExt, hex, Datagram, Header}; use neqo_crypto::{generate_ech_keys, random, AntiReplay}; use neqo_http3::{ Http3OrWebTransportStream, Http3Parameters, Http3Server, Http3ServerEvent, StreamId, @@ -62,7 +63,7 @@ impl HttpServer { .enable_ech(random::<1>()[0], "public.example", &sk, &pk) .unwrap(); let cfg = server.ech_config(); - qinfo!("ECHConfigList: {}", hex(cfg)); + info!("ECHConfigList: {}", hex(cfg)); } Self { server, @@ -92,7 +93,7 @@ impl super::HttpServer for HttpServer { headers, fin, } => { - qdebug!("Headers (request={stream} fin={fin}): {headers:?}"); + debug!("Headers (request={stream} fin={fin}): {headers:?}"); if headers.contains_header(":method", "POST") { self.posts.insert(stream, 0); @@ -110,7 +111,7 @@ impl super::HttpServer for HttpServer { match qns_read_response(path.value()) { Ok(data) => SendData::from(data), Err(e) => { - qerror!("Failed to read {}: {e}", path.value()); + error!("Failed to read {}: {e}", path.value()); stream .send_headers(&[Header::new(":status", "404")]) .unwrap(); diff --git a/neqo-bin/src/server/mod.rs b/neqo-bin/src/server/mod.rs index 1b6384df0d..d618de23f0 100644 --- a/neqo-bin/src/server/mod.rs +++ b/neqo-bin/src/server/mod.rs @@ -23,7 +23,8 @@ use futures::{ future::{select, select_all, Either}, FutureExt, }; -use neqo_common::{qdebug, qerror, qinfo, qwarn, Datagram}; +use log::{debug, error, info, warn}; +use neqo_common::Datagram; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256}, init_db, AntiReplay, Cipher, @@ -31,7 +32,7 @@ use neqo_crypto::{ use neqo_transport::{Output, RandomConnectionIdGenerator, Version}; use tokio::time::Sleep; -use crate::SharedArgs; +use crate::{log_init, SharedArgs}; const ANTI_REPLAY_WINDOW: Duration = Duration::from_secs(10); @@ -251,7 +252,7 @@ impl ServerRunner { socket.send(&dgram)?; } Output::Callback(new_timeout) => { - qdebug!("Setting timeout of {:?}", new_timeout); + debug!("Setting timeout of {:?}", new_timeout); *timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); break; } @@ -341,7 +342,7 @@ enum Ready { } pub async fn server(mut args: Args) -> Res<()> { - neqo_common::log::init( + log_init( args.shared .verbose .as_ref() @@ -360,7 +361,7 @@ pub async fn server(mut args: Args) -> Res<()> { args.shared.quic_parameters.quic_version = vec![Version::Version1]; } } else { - qwarn!("Both -V and --qns-test were set. Ignoring testcase specific versions."); + warn!("Both -V and --qns-test were set. Ignoring testcase specific versions."); } // These are the default for all tests except http3. @@ -374,7 +375,7 @@ pub async fn server(mut args: Args) -> Res<()> { "handshake" | "transfer" | "resumption" | "multiconnect" | "v2" | "ecn" => {} "connectionmigration" => { if args.shared.quic_parameters.preferred_address().is_none() { - qerror!("No preferred addresses set for connectionmigration test"); + error!("No preferred addresses set for connectionmigration test"); exit(127); } } @@ -391,7 +392,7 @@ pub async fn server(mut args: Args) -> Res<()> { let hosts = args.listen_addresses(); if hosts.is_empty() { - qerror!("No valid hosts defined"); + error!("No valid hosts defined"); Err(io::Error::new(io::ErrorKind::InvalidInput, "No hosts"))?; } let sockets = hosts @@ -399,7 +400,7 @@ pub async fn server(mut args: Args) -> Res<()> { .map(|host| { let socket = crate::udp::Socket::bind(host)?; let local_addr = socket.local_addr()?; - qinfo!("Server waiting for connection on: {local_addr:?}"); + info!("Server waiting for connection on: {local_addr:?}"); Ok((host, socket)) }) diff --git a/neqo-common/Cargo.toml b/neqo-common/Cargo.toml index 4022befd9b..fa9fae130c 100644 --- a/neqo-common/Cargo.toml +++ b/neqo-common/Cargo.toml @@ -18,7 +18,6 @@ workspace = true [dependencies] # Checked against https://searchfox.org/mozilla-central/source/Cargo.lock 2024-11-11 enum-map = { workspace = true } -env_logger = { version = "0.10", default-features = false } hex = { version = "0.4", default-features = false, features = ["alloc"], optional = true } log = { workspace = true } qlog = { workspace = true } diff --git a/neqo-common/src/lib.rs b/neqo-common/src/lib.rs index 5b212f9998..14966c2ad0 100644 --- a/neqo-common/src/lib.rs +++ b/neqo-common/src/lib.rs @@ -14,7 +14,6 @@ mod fuzz; pub mod header; pub mod hrtime; mod incrdecoder; -pub mod log; pub mod qlog; pub mod tos; diff --git a/neqo-common/src/log.rs b/neqo-common/src/log.rs deleted file mode 100644 index 04028a26bd..0000000000 --- a/neqo-common/src/log.rs +++ /dev/null @@ -1,115 +0,0 @@ -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(clippy::module_name_repetitions)] - -use std::{ - io::Write, - sync::{Once, OnceLock}, - time::{Duration, Instant}, -}; - -use env_logger::Builder; - -#[macro_export] -macro_rules! do_log { - (target: $target:expr, $lvl:expr, $($arg:tt)+) => ({ - let lvl = $lvl; - if lvl <= ::log::STATIC_MAX_LEVEL && lvl <= ::log::max_level() { - ::log::logger().log( - &::log::Record::builder() - .args(format_args!($($arg)+)) - .level(lvl) - .target($target) - .module_path_static(Some(module_path!())) - .file_static(Some(file!())) - .line(Some(line!())) - .build() - ); - } - }); - ($lvl:expr, $($arg:tt)+) => ($crate::do_log!(target: module_path!(), $lvl, $($arg)+)) -} - -#[macro_export] -macro_rules! log_subject { - ($lvl:expr, $subject:expr) => {{ - if $lvl <= ::log::max_level() { - format!("{}", $subject) - } else { - String::new() - } - }}; -} - -fn since_start() -> Duration { - static START_TIME: OnceLock = OnceLock::new(); - START_TIME.get_or_init(Instant::now).elapsed() -} - -pub fn init(level_filter: Option) { - static INIT_ONCE: Once = Once::new(); - - if ::log::STATIC_MAX_LEVEL == ::log::LevelFilter::Off { - return; - } - - INIT_ONCE.call_once(|| { - let mut builder = Builder::from_env("RUST_LOG"); - if let Some(filter) = level_filter { - builder.filter_level(filter); - } - builder.format(|buf, record| { - let elapsed = since_start(); - writeln!( - buf, - "{}s{:3}ms {} {}", - elapsed.as_secs(), - elapsed.as_millis() % 1000, - record.level(), - record.args() - ) - }); - if let Err(e) = builder.try_init() { - do_log!(::log::Level::Warn, "Logging initialization error {:?}", e); - } else { - do_log!(::log::Level::Debug, "Logging initialized"); - } - }); -} - -#[macro_export] -macro_rules! log_invoke { - ($lvl:expr, $ctx:expr, $($arg:tt)*) => ( { - ::neqo_common::log::init(None); - ::neqo_common::do_log!($lvl, "[{}] {}", $ctx, format!($($arg)*)); - } ) -} -#[macro_export] -macro_rules! qerror { - ([$ctx:expr], $($arg:tt)*) => (::neqo_common::log_invoke!(::log::Level::Error, $ctx, $($arg)*);); - ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::neqo_common::do_log!(::log::Level::Error, $($arg)*); } ); -} -#[macro_export] -macro_rules! qwarn { - ([$ctx:expr], $($arg:tt)*) => (::neqo_common::log_invoke!(::log::Level::Warn, $ctx, $($arg)*);); - ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::neqo_common::do_log!(::log::Level::Warn, $($arg)*); } ); -} -#[macro_export] -macro_rules! qinfo { - ([$ctx:expr], $($arg:tt)*) => (::neqo_common::log_invoke!(::log::Level::Info, $ctx, $($arg)*);); - ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::neqo_common::do_log!(::log::Level::Info, $($arg)*); } ); -} -#[macro_export] -macro_rules! qdebug { - ([$ctx:expr], $($arg:tt)*) => (::neqo_common::log_invoke!(::log::Level::Debug, $ctx, $($arg)*);); - ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::neqo_common::do_log!(::log::Level::Debug, $($arg)*); } ); -} -#[macro_export] -macro_rules! qtrace { - ([$ctx:expr], $($arg:tt)*) => (::neqo_common::log_invoke!(::log::Level::Trace, $ctx, $($arg)*);); - ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::neqo_common::do_log!(::log::Level::Trace, $($arg)*); } ); -} diff --git a/neqo-common/src/qlog.rs b/neqo-common/src/qlog.rs index 5f7b5dca3d..d29a294d16 100644 --- a/neqo-common/src/qlog.rs +++ b/neqo-common/src/qlog.rs @@ -14,6 +14,7 @@ use std::{ time::{Instant, SystemTime}, }; +use log::error; use qlog::{ streamer::QlogStreamer, CommonFields, Configuration, TraceSeq, VantagePoint, VantagePointType, }; @@ -149,8 +150,7 @@ impl NeqoQlog { { if let Some(inner) = self.inner.borrow_mut().as_mut() { if let Err(e) = f(&mut inner.streamer) { - crate::do_log!( - ::log::Level::Error, + error!( "Qlog event generation failed with error {}; closing qlog.", e ); @@ -169,7 +169,7 @@ impl fmt::Debug for NeqoQlogShared { impl Drop for NeqoQlogShared { fn drop(&mut self) { if let Err(e) = self.streamer.finish_log() { - crate::do_log!(::log::Level::Error, "Error dropping NeqoQlog: {}", e); + error!("Error dropping NeqoQlog: {}", e); } } } diff --git a/neqo-common/tests/log.rs b/neqo-common/tests/log.rs deleted file mode 100644 index 135a667146..0000000000 --- a/neqo-common/tests/log.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use neqo_common::{qdebug, qerror, qinfo, qtrace, qwarn}; - -#[test] -fn basic() { - qerror!("error"); - qwarn!("warn"); - qinfo!("info"); - qdebug!("debug"); - qtrace!("trace"); -} - -#[test] -fn args() { - let num = 1; - let obj = std::time::Instant::now(); - qerror!("error {} {:?}", num, obj); - qwarn!("warn {} {:?}", num, obj); - qinfo!("info {} {:?}", num, obj); - qdebug!("debug {} {:?}", num, obj); - qtrace!("trace {} {:?}", num, obj); -} - -#[test] -fn context() { - let context = "context"; - qerror!([context], "error"); - qwarn!([context], "warn"); - qinfo!([context], "info"); - qdebug!([context], "debug"); - qtrace!([context], "trace"); -} - -#[test] -fn context_comma() { - let obj = vec![1, 2, 3]; - let context = "context"; - qerror!([context], "error {:?}", obj); - qwarn!([context], "warn {:?}", obj); - qinfo!([context], "info {:?}", obj); - qdebug!([context], "debug {:?}", obj); - qtrace!([context], "trace {:?}", obj); -} - -#[test] -fn context_expr() { - let context = vec![1, 2, 3]; - qerror!([format!("{:x?}", context)], "error"); - qwarn!([format!("{:x?}", context)], "warn"); - qinfo!([format!("{:x?}", context)], "info"); - qdebug!([format!("{:x?}", context)], "debug"); - qtrace!([format!("{:x?}", context)], "trace"); -} diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index b3e76ca39b..77493536bf 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -16,7 +16,8 @@ use std::{ time::Instant, }; -use neqo_common::{hex_snip_middle, hex_with_len, qdebug, qtrace, qwarn}; +use log::{debug, trace, warn}; +use neqo_common::{hex_snip_middle, hex_with_len}; pub use crate::{ agentio::{as_c_void, Record, RecordList}, @@ -107,7 +108,7 @@ fn get_alpn(fd: *mut ssl::PRFileDesc, pre: bool) -> Res> { } _ => None, }; - qtrace!([format!("{fd:p}")], "got ALPN {:?}", alpn); + trace!("[{}] got ALPN {:?}", format!("{fd:p}"), alpn); Ok(alpn) } @@ -369,7 +370,11 @@ impl SecretAgent { if st.is_none() { *st = Some(alert.description); } else { - qwarn!([format!("{fd:p}")], "duplicate alert {}", alert.description); + warn!( + "[{}] duplicate alert {}", + format!("{fd:p}"), + alert.description + ); } } } @@ -429,7 +434,7 @@ impl SecretAgent { /// If NSS can't enable or disable ciphers. pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> { if self.state != HandshakeState::New { - qwarn!([self], "Cannot enable ciphers in state {:?}", self.state); + warn!("[{}] Cannot enable ciphers in state {:?}", self, self.state); return Err(Error::InternalError); } @@ -644,7 +649,7 @@ impl SecretAgent { fn capture_error(&mut self, res: Res) -> Res { if let Err(e) = res { let e = ech::convert_ech_error(self.fd, e); - qwarn!([self], "error: {:?}", e); + warn!("[{self}] error: {:?}", e); self.state = HandshakeState::Failed(e.clone()); Err(e) } else { @@ -669,7 +674,7 @@ impl SecretAgent { let info = self.capture_error(SecretAgentInfo::new(self.fd))?; HandshakeState::Complete(info) }; - qdebug!([self], "state -> {:?}", self.state); + debug!("[{self}] state -> {:?}", self.state); Ok(()) } @@ -729,7 +734,7 @@ impl SecretAgent { if let HandshakeState::Authenticated(ref err) = self.state { let result = secstatus_to_res(unsafe { ssl::SSL_AuthCertificateComplete(self.fd, *err) }); - qdebug!([self], "SSL_AuthCertificateComplete: {:?}", result); + debug!("[{self}] SSL_AuthCertificateComplete: {:?}", result); // This should return SECSuccess, so don't use update_state(). self.capture_error(result)?; } @@ -891,9 +896,9 @@ impl Client { let len = usize::try_from(len).unwrap(); let mut v = Vec::with_capacity(len); v.extend_from_slice(null_safe_slice(token, len)); - qdebug!( - [format!("{fd:p}")], - "Got resumption token {}", + debug!( + "[{}] Got resumption token {}", + format!("{fd:p}"), hex_snip_middle(&v) ); @@ -965,7 +970,7 @@ impl Client { /// Error returned when the configuration is invalid. pub fn enable_ech(&mut self, ech_config_list: impl AsRef<[u8]>) -> Res<()> { let config = ech_config_list.as_ref(); - qdebug!([self], "Enable ECH for a server: {}", hex_with_len(config)); + debug!("[{self}] Enable ECH for a server: {}", hex_with_len(config)); self.ech_config = Vec::from(config); if config.is_empty() { unsafe { ech::SSL_EnableTls13GreaseEch(self.agent.fd, PRBool::from(true)) } @@ -1027,7 +1032,7 @@ pub trait ZeroRttChecker: std::fmt::Debug + std::marker::Unpin { pub struct AllowZeroRtt {} impl ZeroRttChecker for AllowZeroRtt { fn check(&self, _token: &[u8]) -> ZeroRttCheckResult { - qwarn!("AllowZeroRtt accepting 0-RTT"); + warn!("AllowZeroRtt accepting 0-RTT"); ZeroRttCheckResult::Accept } } @@ -1175,7 +1180,7 @@ impl Server { pk: &PublicKey, ) -> Res<()> { let cfg = ech::encode_config(config, public_name, pk)?; - qdebug!([self], "Enable ECH for a server: {}", hex_with_len(&cfg)); + debug!("[{self}] Enable ECH for a server: {}", hex_with_len(&cfg)); unsafe { ech::SSL_SetServerEchConfigs( self.agent.fd, diff --git a/neqo-crypto/src/agentio.rs b/neqo-crypto/src/agentio.rs index f2173bfd8d..4cdf42acb9 100644 --- a/neqo-crypto/src/agentio.rs +++ b/neqo-crypto/src/agentio.rs @@ -13,7 +13,8 @@ use std::{ ptr::{null, null_mut}, }; -use neqo_common::{hex, hex_with_len, qtrace}; +use log::trace; +use neqo_common::{hex, hex_with_len}; use crate::{ constants::{ContentType, Epoch}, @@ -52,7 +53,7 @@ impl Record { // Shoves this record into the socket, returns true if blocked. pub(crate) fn write(self, fd: *mut ssl::PRFileDesc) -> Res<()> { - qtrace!("write {:?}", self); + trace!("write {:?}", self); unsafe { ssl::SSL_RecordLayerData( fd, @@ -161,7 +162,7 @@ impl AgentIoInput { assert!(self.input.is_null()); self.input = input.as_ptr(); self.available = input.len(); - qtrace!("AgentIoInput wrap {:p}", self.input); + trace!("AgentIoInput wrap {:p}", self.input); AgentIoInputContext { input: self } } @@ -177,7 +178,7 @@ impl AgentIoInput { #[allow(clippy::disallowed_methods)] // We just checked if this was empty. let src = unsafe { std::slice::from_raw_parts(self.input, amount) }; - qtrace!([self], "read {}", hex(src)); + trace!("[{self}] read {}", hex(src)); let dst = unsafe { std::slice::from_raw_parts_mut(buf, amount) }; dst.copy_from_slice(src); self.input = self.input.wrapping_add(amount); @@ -186,7 +187,7 @@ impl AgentIoInput { } fn reset(&mut self) { - qtrace!([self], "reset"); + trace!("[{self}] reset"); self.input = null(); self.available = 0; } @@ -230,12 +231,12 @@ impl AgentIo { // Stage output from TLS into the output buffer. fn save_output(&mut self, buf: *const u8, count: usize) { let slice = unsafe { null_safe_slice(buf, count) }; - qtrace!([self], "save output {}", hex(slice)); + trace!("[{self}] save output {}", hex(slice)); self.output.extend_from_slice(slice); } pub fn take_output(&mut self) -> Vec { - qtrace!([self], "take output"); + trace!("[{self}] take output"); mem::take(&mut self.output) } } diff --git a/neqo-crypto/src/cert.rs b/neqo-crypto/src/cert.rs index 80609f5316..71842fa38d 100644 --- a/neqo-crypto/src/cert.rs +++ b/neqo-crypto/src/cert.rs @@ -6,7 +6,7 @@ use std::ptr::NonNull; -use neqo_common::qerror; +use log::error; use crate::{ experimental_api, null_safe_slice, @@ -46,7 +46,7 @@ fn stapled_ocsp_responses(fd: *mut PRFileDesc) -> Option>> { Some(ocsp_ptr) => { let mut ocsp_helper: Vec> = Vec::new(); let Ok(len) = isize::try_from(unsafe { ocsp_ptr.as_ref().len }) else { - qerror!([format!("{fd:p}")], "Received illegal OSCP length"); + error!("[{}] Received illegal OSCP length", format!("{fd:p}")); return None; }; for idx in 0..len { diff --git a/neqo-crypto/src/ech.rs b/neqo-crypto/src/ech.rs index 76fd362c14..1be5c3445f 100644 --- a/neqo-crypto/src/ech.rs +++ b/neqo-crypto/src/ech.rs @@ -10,7 +10,7 @@ use std::{ ptr::{addr_of_mut, null_mut}, }; -use neqo_common::qtrace; +use log::trace; use crate::{ err::{ssl::SSL_ERROR_ECH_RETRY_WITH_ECH, Error, Res}, @@ -146,7 +146,7 @@ pub fn generate_keys() -> Res<(PrivateKey, PublicKey)> { assert_eq!(secret_ptr.is_null(), public_ptr.is_null()); let sk = PrivateKey::from_ptr(secret_ptr)?; let pk = PublicKey::from_ptr(public_ptr)?; - qtrace!("Generated key pair: sk={:?} pk={:?}", sk, pk); + trace!("Generated key pair: sk={:?} pk={:?}", sk, pk); Ok((sk, pk)) } diff --git a/neqo-crypto/src/lib.rs b/neqo-crypto/src/lib.rs index 1816440d63..fed13cc20c 100644 --- a/neqo-crypto/src/lib.rs +++ b/neqo-crypto/src/lib.rs @@ -60,8 +60,8 @@ pub use self::{ }; mod min_version; +use log::error; use min_version::MINIMUM_NSS_VERSION; -use neqo_common::qerror; #[allow(non_upper_case_globals)] mod nss { @@ -94,7 +94,7 @@ static INITIALIZED: OnceLock> = OnceLock::new(); fn version_check() -> Res<()> { let min_ver = CString::new(MINIMUM_NSS_VERSION)?; if unsafe { nss::NSS_VersionCheck(min_ver.as_ptr()) } == 0 { - qerror!("Minimum NSS version of {MINIMUM_NSS_VERSION} not supported"); + error!("Minimum NSS version of {MINIMUM_NSS_VERSION} not supported"); return Err(Error::UnsupportedVersion); } Ok(()) diff --git a/neqo-crypto/src/secrets.rs b/neqo-crypto/src/secrets.rs index 3d637fb958..ac09122f77 100644 --- a/neqo-crypto/src/secrets.rs +++ b/neqo-crypto/src/secrets.rs @@ -6,7 +6,7 @@ use std::{os::raw::c_void, pin::Pin}; -use neqo_common::qdebug; +use log::debug; use crate::{ agentio::as_c_void, @@ -88,7 +88,7 @@ impl Secrets { } fn put(&mut self, dir: SecretDirection, epoch: Epoch, key: SymKey) { - qdebug!("{:?} secret available for {:?}: {:?}", dir, epoch, key); + debug!("{:?} secret available for {:?}: {:?}", dir, epoch, key); let keys = match dir { SecretDirection::Read => &mut self.r, SecretDirection::Write => &mut self.w, diff --git a/neqo-crypto/src/selfencrypt.rs b/neqo-crypto/src/selfencrypt.rs index 1618a971a9..b8661876fc 100644 --- a/neqo-crypto/src/selfencrypt.rs +++ b/neqo-crypto/src/selfencrypt.rs @@ -6,7 +6,8 @@ use std::mem; -use neqo_common::{hex, qinfo, qtrace, Encoder}; +use log::{info, trace}; +use neqo_common::{hex, Encoder}; use crate::{ constants::{Cipher, Version}, @@ -61,7 +62,7 @@ impl SelfEncrypt { self.old_key = Some(mem::replace(&mut self.key, new_key)); let (kid, _) = self.key_id.overflowing_add(1); self.key_id = kid; - qinfo!(["SelfEncrypt"], "Rotated keys to {}", self.key_id); + info!("[SelfEncrypt] Rotated keys to {}", self.key_id); Ok(()) } @@ -98,9 +99,8 @@ impl SelfEncrypt { let mut output: Vec = enc.into(); output.resize(encoded_len, 0); cipher.encrypt(0, extended_aad.as_ref(), plaintext, &mut output[offset..])?; - qtrace!( - ["SelfEncrypt"], - "seal {} {} -> {}", + trace!( + "[SelfEncrypt] seal {} {} -> {}", hex(aad), hex(plaintext), hex(&output) @@ -149,9 +149,8 @@ impl SelfEncrypt { aead.decrypt(0, extended_aad.as_ref(), &ciphertext[offset..], &mut output)?; let final_len = decrypted.len(); output.truncate(final_len); - qtrace!( - ["SelfEncrypt"], - "open {} {} -> {}", + trace!( + "[SelfEncrypt] open {} {} -> {}", hex(aad), hex(ciphertext), hex(&output) diff --git a/neqo-crypto/tests/handshake.rs b/neqo-crypto/tests/handshake.rs index 799ccba34e..3e78f430c9 100644 --- a/neqo-crypto/tests/handshake.rs +++ b/neqo-crypto/tests/handshake.rs @@ -8,7 +8,7 @@ use std::{mem, time::Instant}; -use neqo_common::qinfo; +use log::info; use neqo_crypto::{ AntiReplay, AuthenticationStatus, Client, HandshakeState, RecordList, Res, ResumptionToken, SecretAgent, Server, ZeroRttCheckResult, ZeroRttChecker, @@ -68,8 +68,8 @@ fn handshake(now: Instant, client: &mut SecretAgent, server: &mut SecretAgent) { #[allow(clippy::missing_panics_doc)] pub fn connect_at(now: Instant, client: &mut SecretAgent, server: &mut SecretAgent) { handshake(now, client, server); - qinfo!("client: {:?}", client.state()); - qinfo!("server: {:?}", server.state()); + info!("client: {:?}", client.state()); + info!("server: {:?}", server.state()); assert!(client.state().is_connected()); assert!(server.state().is_connected()); } diff --git a/neqo-http3/src/buffered_send_stream.rs b/neqo-http3/src/buffered_send_stream.rs index 4d1ef3511b..1900920369 100644 --- a/neqo-http3/src/buffered_send_stream.rs +++ b/neqo-http3/src/buffered_send_stream.rs @@ -4,7 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use neqo_common::qtrace; +use log::trace; use neqo_transport::{Connection, StreamId}; use crate::{qlog, Res}; @@ -62,14 +62,14 @@ impl BufferedStream { /// /// Returns `neqo_transport` errors. pub fn send_buffer(&mut self, conn: &mut Connection) -> Res { - let label = ::neqo_common::log_subject!(::log::Level::Debug, self); + let label = format!("{self}"); let Self::Initialized { stream_id, buf } = self else { return Ok(0); }; if buf.is_empty() { return Ok(0); } - qtrace!([label], "sending data."); + trace!("[{label}] sending data."); let sent = conn.stream_send(*stream_id, &buf[..])?; if sent == 0 { return Ok(0); diff --git a/neqo-http3/src/connection.rs b/neqo-http3/src/connection.rs index a59b6908e7..5b0c31466f 100644 --- a/neqo-http3/src/connection.rs +++ b/neqo-http3/src/connection.rs @@ -14,7 +14,8 @@ use std::{ rc::Rc, }; -use neqo_common::{qdebug, qerror, qinfo, qtrace, qwarn, Decoder, Header, MessageType, Role}; +use log::{debug, error, info, trace, warn}; +use neqo_common::{Decoder, Header, MessageType, Role}; use neqo_qpack::{decoder::QPackDecoder, encoder::QPackEncoder}; use neqo_transport::{ streams::SendOrder, AppError, CloseReason, Connection, DatagramTracking, State, StreamId, @@ -352,7 +353,7 @@ impl Http3Connection { /// This function creates and initializes, i.e. send stream type, the control and qpack /// streams. fn initialize_http3_connection(&mut self, conn: &mut Connection) -> Res<()> { - qdebug!([self], "Initialize the http3 connection."); + debug!("[{self}] Initialize the http3 connection."); self.control_stream_local.create(conn)?; self.send_settings(); @@ -361,7 +362,7 @@ impl Http3Connection { } fn send_settings(&mut self) { - qdebug!([self], "Send settings."); + debug!("[{self}] Send settings."); self.control_stream_local.queue_frame(&HFrame::Settings { settings: HSettings::from(&self.local_params), }); @@ -374,7 +375,7 @@ impl Http3Connection { } fn create_qpack_streams(&self, conn: &mut Connection) -> Res<()> { - qdebug!([self], "create_qpack_streams."); + debug!("[{self}] create_qpack_streams."); self.qpack_encoder .borrow_mut() .add_send_stream(conn.stream_create(StreamType::UniDi)?); @@ -458,7 +459,7 @@ impl Http3Connection { /// This is called when a `ConnectionEvent::NewStream` event is received. This register the /// stream with a `NewStreamHeadReader` handler. pub fn add_new_stream(&mut self, stream_id: StreamId) { - qtrace!([self], "A new stream: {}.", stream_id); + trace!("[{self}] A new stream: {}.", stream_id); self.recv_streams.insert( stream_id, Box::new(NewStreamHeadReader::new(stream_id, self.role)), @@ -468,7 +469,7 @@ impl Http3Connection { /// The function calls `receive` for a stream. It also deals with the outcome of a read by /// calling `handle_stream_manipulation_output`. fn stream_receive(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res { - qtrace!([self], "Readable stream {}.", stream_id); + trace!("[{self}] Readable stream {}.", stream_id); if let Some(recv_stream) = self.recv_streams.get_mut(&stream_id) { let res = recv_stream.receive(conn); @@ -485,7 +486,7 @@ impl Http3Connection { conn: &mut Connection, ) -> Res<()> { for stream_id in unblocked_streams { - qdebug!([self], "Stream {} is unblocked", stream_id); + debug!("[{self}] Stream {} is unblocked", stream_id); if let Some(r) = self.recv_streams.get_mut(&stream_id) { let res = r .http_stream() @@ -551,11 +552,9 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!( - [self], - "Handle a stream reset stream_id={} app_err={}", - stream_id, - app_error + info!( + "[{self}] Handle a stream reset stream_id={} app_err={}", + stream_id, app_error ); self.close_recv(stream_id, CloseType::ResetRemote(app_error), conn) @@ -567,11 +566,9 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!( - [self], - "Handle stream_stop_sending stream_id={} app_err={}", - stream_id, - app_error + info!( + "[{self}] Handle stream_stop_sending stream_id={} app_err={}", + stream_id, app_error ); if self.send_stream_is_critical(stream_id) { @@ -585,7 +582,7 @@ impl Http3Connection { /// This is called when `neqo_transport::Connection` state has been change to take proper /// actions in the HTTP3 layer. pub fn handle_state_change(&mut self, conn: &mut Connection, state: &State) -> Res { - qdebug!([self], "Handle state change {:?}", state); + debug!("[{self}] Handle state change {:?}", state); match state { State::Handshaking => { if self.role == Role::Server @@ -696,15 +693,13 @@ impl Http3Connection { } NewStreamType::Push(push_id) => { - qinfo!( - [self], - "A new push stream {} push_id:{}.", - stream_id, - push_id + info!( + "[{self}] A new push stream {} push_id:{}.", + stream_id, push_id ); } NewStreamType::Decoder => { - qdebug!([self], "A new remote qpack encoder stream {}", stream_id); + debug!("[{self}] A new remote qpack encoder stream {}", stream_id); self.check_stream_exists(Http3StreamType::Decoder)?; self.recv_streams.insert( stream_id, @@ -715,7 +710,7 @@ impl Http3Connection { ); } NewStreamType::Encoder => { - qdebug!([self], "A new remote qpack decoder stream {}", stream_id); + debug!("[{self}] A new remote qpack decoder stream {}", stream_id); self.check_stream_exists(Http3StreamType::Encoder)?; self.recv_streams.insert( stream_id, @@ -726,7 +721,7 @@ impl Http3Connection { ); } NewStreamType::Http(_) => { - qinfo!([self], "A new http stream {}.", stream_id); + info!("[{self}] A new http stream {}.", stream_id); } NewStreamType::WebTransportStream(session_id) => { let session_exists = self @@ -739,11 +734,9 @@ impl Http3Connection { } // set incoming WebTransport streams to be fair (share bandwidth) conn.stream_fairness(stream_id, true).ok(); - qinfo!( - [self], - "A new WebTransport stream {} for session {}.", - stream_id, - session_id + info!( + "[{self}] A new WebTransport stream {} for session {}.", + stream_id, session_id ); } NewStreamType::Unknown => { @@ -764,10 +757,10 @@ impl Http3Connection { /// This is called when an application closes the connection. pub fn close(&mut self, error: AppError) { - qdebug!([self], "Close connection error {:?}.", error); + debug!("[{self}] Close connection error {:?}.", error); self.state = Http3State::Closing(CloseReason::Application(error)); if (!self.send_streams.is_empty() || !self.recv_streams.is_empty()) && (error == 0) { - qwarn!("close(0) called when streams still active"); + warn!("close(0) called when streams still active"); } self.send_streams.clear(); self.recv_streams.clear(); @@ -849,11 +842,9 @@ impl Http3Connection { where T: AsRequestTarget<'t> + ?Sized + Debug, { - qinfo!( - [self], - "Fetch method={} target: {:?}", - request.method, - request.target, + info!( + "[{self}] Fetch method={} target: {:?}", + request.method, request.target, ); let id = self.create_bidi_transport_stream(conn)?; self.fetch_with_stream(id, conn, send_events, recv_events, push_handler, request)?; @@ -951,7 +942,7 @@ impl Http3Connection { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - qdebug!([self], "read_data from stream {}.", stream_id); + debug!("[{self}] read_data from stream {}.", stream_id); let res = self .recv_streams .get_mut(&stream_id) @@ -968,11 +959,9 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - qinfo!( - [self], - "Reset sending side of stream {} error={}.", - stream_id, - error + info!( + "[{self}] Reset sending side of stream {} error={}.", + stream_id, error ); if self.send_stream_is_critical(stream_id) { @@ -990,11 +979,9 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - qinfo!( - [self], - "Send stop sending for stream {} error={}.", - stream_id, - error + info!( + "[{self}] Send stop sending for stream {} error={}.", + stream_id, error ); if self.recv_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); @@ -1043,7 +1030,7 @@ impl Http3Connection { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "cancel_fetch {} error={}.", stream_id, error); + info!("[{self}] cancel_fetch {} error={}.", stream_id, error); let send_stream = self.send_streams.get(&stream_id); let recv_stream = self.recv_streams.get(&stream_id); match (send_stream, recv_stream) { @@ -1090,7 +1077,7 @@ impl Http3Connection { /// This is called when an application wants to close the sending side of a stream. pub fn stream_close_send(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { - qdebug!([self], "Close the sending side for stream {}.", stream_id); + debug!("[{self}] Close the sending side for stream {}.", stream_id); debug_assert!(self.state.active()); let send_stream = self .send_streams @@ -1117,7 +1104,7 @@ impl Http3Connection { where T: AsRequestTarget<'x> + ?Sized + Debug, { - qinfo!([self], "Create WebTransport"); + info!("[{self}] Create WebTransport"); if !self.webtransport_enabled() { return Err(Error::Unavailable); } @@ -1158,7 +1145,7 @@ impl Http3Connection { events: Box, accept_res: &WebTransportSessionAcceptAction, ) -> Res<()> { - qtrace!( + trace!( "Respond to WebTransport session with accept={}.", accept_res ); @@ -1237,7 +1224,7 @@ impl Http3Connection { error: u32, message: &str, ) -> Res<()> { - qtrace!("Close WebTransport session {:?}", session_id); + trace!("Close WebTransport session {:?}", session_id); let send_stream = self .send_streams .get_mut(&session_id) @@ -1263,7 +1250,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res { - qtrace!( + trace!( "Create new WebTransport stream session={} type={:?}", session_id, stream_type @@ -1304,7 +1291,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res<()> { - qtrace!( + trace!( "Create new WebTransport stream session={} stream_id={}", session_id, stream_id @@ -1401,7 +1388,7 @@ impl Http3Connection { /// `PriorityUpdateRequestPush` which handling is specific to the client and server, we must /// give them to the specific client/server handler. fn handle_control_frame(&mut self, f: HFrame) -> Res> { - qdebug!([self], "Handle a control frame {:?}", f); + debug!("[{self}] Handle a control frame {:?}", f); if !matches!(f, HFrame::Settings { .. }) && !matches!( self.settings_state, @@ -1432,7 +1419,7 @@ impl Http3Connection { } fn handle_settings(&mut self, new_settings: HSettings) -> Res<()> { - qdebug!([self], "Handle SETTINGS frame."); + debug!("[{self}] Handle SETTINGS frame."); match &self.settings_state { Http3RemoteSettingsState::NotReceived => { self.set_qpack_settings(&new_settings)?; @@ -1454,9 +1441,8 @@ impl Http3Connection { continue; } if zero_rtt_value > new_value { - qerror!( - [self], - "The new({}) and the old value({}) of setting {:?} do not match", + error!( + "[{self}] The new({}) and the old value({}) of setting {:?} do not match", new_value, zero_rtt_value, st @@ -1478,7 +1464,7 @@ impl Http3Connection { } } if qpack_changed { - qdebug!([self], "Settings after zero rtt differ."); + debug!("[{self}] Settings after zero rtt differ."); self.set_qpack_settings(&(new_settings))?; } self.settings_state = Http3RemoteSettingsState::Received(new_settings); @@ -1577,7 +1563,7 @@ impl Http3Connection { let (recv, send) = wt.borrow_mut().take_sub_streams(); for id in recv { - qtrace!("Remove the extended connect sub receiver stream {}", id); + trace!("Remove the extended connect sub receiver stream {}", id); // Use CloseType::ResetRemote so that an event will be sent. CloseType::LocalError would // have the same effect. if let Some(mut s) = self.recv_streams.remove(&id) { @@ -1586,7 +1572,7 @@ impl Http3Connection { mem::drop(conn.stream_stop_sending(id, Error::HttpRequestCancelled.code())); } for id in send { - qtrace!("Remove the extended connect sub send stream {}", id); + trace!("Remove the extended connect sub send stream {}", id); if let Some(mut s) = self.send_streams.remove(&id) { s.handle_stop_sending(CloseType::ResetRemote(Error::HttpRequestCancelled.code())); } diff --git a/neqo-http3/src/connection_client.rs b/neqo-http3/src/connection_client.rs index dfb7ef59b5..568b4cb214 100644 --- a/neqo-http3/src/connection_client.rs +++ b/neqo-http3/src/connection_client.rs @@ -13,9 +13,10 @@ use std::{ time::Instant, }; +use log::{debug, info, trace}; use neqo_common::{ - event::Provider as EventProvider, hex, hex_with_len, qdebug, qinfo, qlog::NeqoQlog, qtrace, - Datagram, Decoder, Encoder, Header, MessageType, Role, + event::Provider as EventProvider, hex, hex_with_len, qlog::NeqoQlog, Datagram, Decoder, + Encoder, Header, MessageType, Role, }; use neqo_crypto::{agent::CertificateInfo, AuthenticationStatus, ResumptionToken, SecretAgentInfo}; use neqo_qpack::Stats as QpackStats; @@ -454,7 +455,7 @@ impl Http3Client { let Some(settings_slice) = dec.decode_vvec() else { return Err(Error::InvalidResumptionToken); }; - qtrace!([self], " settings {}", hex_with_len(settings_slice)); + trace!("[{self}] settings {}", hex_with_len(settings_slice)); let mut dec_settings = Decoder::from(settings_slice); let mut settings = HSettings::default(); Error::map_error( @@ -462,7 +463,7 @@ impl Http3Client { Error::InvalidResumptionToken, )?; let tok = dec.decode_remainder(); - qtrace!([self], " Transport token {}", hex(tok)); + trace!("[{self}] Transport token {}", hex(tok)); self.conn.enable_resumption(now, tok)?; if self.conn.state().closed() { let state = self.conn.state().clone(); @@ -489,7 +490,7 @@ impl Http3Client { where S: AsRef + Display, { - qinfo!([self], "Close the connection error={} msg={}.", error, msg); + info!("[{self}] Close the connection error={} msg={}.", error, msg); if !matches!( self.base_handler.state, Http3State::Closing(_) | Http3State::Closed(_) @@ -577,7 +578,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn cancel_fetch(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - qinfo!([self], "reset_stream {} error={}.", stream_id, error); + info!("[{self}] reset_stream {} error={}.", stream_id, error); self.base_handler .cancel_fetch(stream_id, error, &mut self.conn) } @@ -588,7 +589,7 @@ impl Http3Client { /// /// An error will be return if stream does not exist. pub fn stream_close_send(&mut self, stream_id: StreamId) -> Res<()> { - qdebug!([self], "Close sending side stream={}.", stream_id); + debug!("[{self}] Close sending side stream={}.", stream_id); self.base_handler .stream_close_send(&mut self.conn, stream_id) } @@ -597,7 +598,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn stream_reset_send(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - qinfo!([self], "stream_reset_send {} error={}.", stream_id, error); + info!("[{self}] stream_reset_send {} error={}.", stream_id, error); self.base_handler .stream_reset_send(&mut self.conn, stream_id, error) } @@ -606,7 +607,10 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn stream_stop_sending(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - qinfo!([self], "stream_stop_sending {} error={}.", stream_id, error); + info!( + "[{self}] stream_stop_sending {} error={}.", + stream_id, error + ); self.base_handler .stream_stop_sending(&mut self.conn, stream_id, error) } @@ -624,9 +628,8 @@ impl Http3Client { /// info that the stream has been closed.) `InvalidInput` if an empty buffer has been /// supplied. pub fn send_data(&mut self, stream_id: StreamId, buf: &[u8]) -> Res { - qinfo!( - [self], - "send_data from stream {} sending {} bytes.", + info!( + "[{self}] end_data from stream {} sending {} bytes.", stream_id, buf.len() ); @@ -650,7 +653,7 @@ impl Http3Client { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - qdebug!([self], "read_data from stream {}.", stream_id); + debug!("[{self}] read_data from stream {}.", stream_id); let res = self.base_handler.read_data(&mut self.conn, stream_id, buf); if let Err(e) = &res { if e.connection_error() { @@ -775,7 +778,7 @@ impl Http3Client { buf: &[u8], id: impl Into, ) -> Res<()> { - qtrace!("webtransport_send_datagram session:{:?}", session_id); + trace!("webtransport_send_datagram session:{:?}", session_id); self.base_handler .webtransport_send_datagram(session_id, &mut self.conn, buf, id) } @@ -854,7 +857,7 @@ impl Http3Client { /// This function combines `process_input` and `process_output` function. pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - qtrace!([self], "Process."); + trace!("[{self}] Process."); if let Some(d) = dgram { self.process_input(d, now); } @@ -881,7 +884,7 @@ impl Http3Client { now: Instant, ) { let mut dgrams = dgrams.into_iter().peekable(); - qtrace!([self], "Process multiple datagrams"); + trace!("[{self}] Process multiple datagrams"); if dgrams.peek().is_none() { return; } @@ -895,7 +898,7 @@ impl Http3Client { /// the QUC layer and calls `Http3Connection::process_sending` to ensure that HTTP/3 layer /// data, e.g. control frames, are sent. fn process_http3(&mut self, now: Instant) { - qtrace!([self], "Process http3 internal."); + trace!("[{self}] Process http3 internal."); match self.base_handler.state() { Http3State::ZeroRtt | Http3State::Connected | Http3State::GoingAway(..) => { let res = self.check_connection_events(); @@ -944,7 +947,7 @@ impl Http3Client { /// [2]: ../neqo_transport/struct.ConnectionEvents.html /// [3]: ../neqo_transport/struct.Connection.html#method.process_output pub fn process_output(&mut self, now: Instant) -> Output { - qtrace!([self], "Process output."); + trace!("[{self}] Process output."); // Maybe send() stuff on http3-managed streams self.process_http3(now); @@ -962,7 +965,7 @@ impl Http3Client { fn check_result(&mut self, now: Instant, res: &Res) -> bool { match &res { Err(Error::HttpGoaway) => { - qinfo!([self], "Connection error: goaway stream_id increased."); + info!("[{self}] Connection error: goaway stream_id increased."); self.close( now, Error::HttpGeneralProtocol.code(), @@ -971,7 +974,7 @@ impl Http3Client { true } Err(e) => { - qinfo!([self], "Connection error: {}.", e); + info!("[{self}] Connection error: {}.", e); self.close(now, e.code(), format!("{e}")); true } @@ -994,9 +997,9 @@ impl Http3Client { /// [2]: ../neqo_transport/enum.ConnectionEvent.html /// [3]: ../neqo_transport/enum.ConnectionEvent.html#variant.RecvStreamReadable fn check_connection_events(&mut self) -> Res<()> { - qtrace!([self], "Check connection events."); + trace!("[{self}] Check connection events."); while let Some(e) = self.conn.next_event() { - qdebug!([self], "check_connection_events - event {:?}.", e); + debug!("[{self}] check_connection_events - event {:?}.", e); match e { ConnectionEvent::NewStream { stream_id } => { // During this event we only add a new stream to the Http3Connection stream @@ -1178,7 +1181,7 @@ impl Http3Client { } fn handle_goaway(&mut self, goaway_stream_id: StreamId) -> Res<()> { - qinfo!([self], "handle_goaway {}", goaway_stream_id); + info!("[{self}] handle_goaway {}", goaway_stream_id); if goaway_stream_id.is_uni() || goaway_stream_id.is_server_initiated() { return Err(Error::HttpId); @@ -1286,7 +1289,8 @@ impl EventProvider for Http3Client { mod tests { use std::{mem, time::Duration}; - use neqo_common::{event::Provider, qtrace, Datagram, Decoder, Encoder}; + use log::trace; + use neqo_common::{event::Provider, Datagram, Decoder, Encoder}; use neqo_crypto::{AllowZeroRtt, AntiReplay, ResumptionToken}; use neqo_qpack::{encoder::QPackEncoder, QpackSettings}; use neqo_transport::{ @@ -1470,7 +1474,7 @@ mod tests { pub fn create_control_stream(&mut self) { // Create control stream let control = self.conn.stream_create(StreamType::UniDi).unwrap(); - qtrace!(["TestServer"], "control stream: {}", control); + trace!("[TestServer] control stream: {}", control); self.control_stream_id = Some(control); // Send stream type on the control stream. assert_eq!( diff --git a/neqo-http3/src/connection_server.rs b/neqo-http3/src/connection_server.rs index f06cf272ba..0b88bf1200 100644 --- a/neqo-http3/src/connection_server.rs +++ b/neqo-http3/src/connection_server.rs @@ -6,7 +6,8 @@ use std::{rc::Rc, time::Instant}; -use neqo_common::{event::Provider, qdebug, qinfo, qtrace, Header, MessageType, Role}; +use log::{debug, info, trace}; +use neqo_common::{event::Provider, Header, MessageType, Role}; use neqo_transport::{ AppError, Connection, ConnectionEvent, DatagramTracking, StreamId, StreamType, }; @@ -102,7 +103,7 @@ impl Http3ServerHandler { /// /// An error will be returned if stream does not exist. pub fn stream_close_send(&mut self, stream_id: StreamId, conn: &mut Connection) -> Res<()> { - qdebug!([self], "Close sending side stream={}.", stream_id); + debug!("[{self}] Close sending side stream={}.", stream_id); self.base_handler.stream_close_send(conn, stream_id)?; self.needs_processing = true; Ok(()) @@ -120,7 +121,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "cancel_fetch {} error={}.", stream_id, error); + info!("[{self}] cancel_fetch {} error={}.", stream_id, error); self.needs_processing = true; self.base_handler.cancel_fetch(stream_id, error, conn) } @@ -131,7 +132,10 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "stream_stop_sending {} error={}.", stream_id, error); + info!( + "[{self}] stream_stop_sending {} error={}.", + stream_id, error + ); self.needs_processing = true; self.base_handler .stream_stop_sending(conn, stream_id, error) @@ -143,7 +147,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "stream_reset_send {} error={}.", stream_id, error); + info!("[{self}] stream_reset_send {} error={}.", stream_id, error); self.needs_processing = true; self.base_handler.stream_reset_send(conn, stream_id, error) } @@ -215,7 +219,7 @@ impl Http3ServerHandler { /// Process HTTTP3 layer. pub fn process_http3(&mut self, conn: &mut Connection, now: Instant) { - qtrace!([self], "Process http3 internal."); + trace!("[{self}] Process http3 internal."); if matches!(self.base_handler.state(), Http3State::Closed(..)) { return; } @@ -254,7 +258,7 @@ impl Http3ServerHandler { } fn close(&mut self, conn: &mut Connection, now: Instant, err: &Error) { - qinfo!([self], "Connection error: {}.", err); + info!("[{self}] Connection error: {}.", err); conn.close(now, err.code(), format!("{err}")); self.base_handler.close(err.code()); self.events @@ -263,9 +267,9 @@ impl Http3ServerHandler { // If this return an error the connection must be closed. fn check_connection_events(&mut self, conn: &mut Connection, now: Instant) -> Res<()> { - qtrace!([self], "Check connection events."); + trace!("[{self}] Check connection events."); while let Some(e) = conn.next_event() { - qdebug!([self], "check_connection_events - event {e:?}."); + debug!("[{self}] check_connection_events - event {e:?}."); match e { ConnectionEvent::NewStream { stream_id } => { self.base_handler.add_new_stream(stream_id); @@ -411,7 +415,7 @@ impl Http3ServerHandler { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - qdebug!([self], "read_data from stream {}.", stream_id); + debug!("[{self}] read_data from stream {}.", stream_id); let res = self.base_handler.read_data(conn, stream_id, buf); if let Err(e) = &res { if e.connection_error() { diff --git a/neqo-http3/src/control_stream_local.rs b/neqo-http3/src/control_stream_local.rs index 92d12ef97f..a7a591e041 100644 --- a/neqo-http3/src/control_stream_local.rs +++ b/neqo-http3/src/control_stream_local.rs @@ -6,7 +6,8 @@ use std::collections::{HashMap, VecDeque}; -use neqo_common::{qtrace, Encoder}; +use log::trace; +use neqo_common::Encoder; use neqo_transport::{Connection, StreamId, StreamType}; use crate::{frames::HFrame, BufferedStream, Http3StreamType, RecvStream, Res}; @@ -92,7 +93,7 @@ impl ControlStreamLocal { /// Create a control stream. pub fn create(&mut self, conn: &mut Connection) -> Res<()> { - qtrace!([self], "Create a control stream."); + trace!("[{self}] Create a control stream."); self.stream.init(conn.stream_create(StreamType::UniDi)?); self.stream .buffer(&[u8::try_from(HTTP3_UNI_STREAM_TYPE_CONTROL).unwrap()]); diff --git a/neqo-http3/src/control_stream_remote.rs b/neqo-http3/src/control_stream_remote.rs index ef2bf96d5b..2f0c43e130 100644 --- a/neqo-http3/src/control_stream_remote.rs +++ b/neqo-http3/src/control_stream_remote.rs @@ -4,7 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use neqo_common::qdebug; +use log::debug; use neqo_transport::{Connection, StreamId}; use crate::{ @@ -36,7 +36,7 @@ impl ControlStreamRemote { /// Check if a stream is the control stream and read received data. pub fn receive_single(&mut self, conn: &mut Connection) -> Res> { - qdebug!([self], "Receiving data."); + debug!("[{self}] Receiving data."); match self .frame_reader .receive(&mut StreamReaderConnectionWrapper::new( @@ -45,7 +45,7 @@ impl ControlStreamRemote { ))? { (_, true) => Err(Error::HttpClosedCriticalStream), (s, false) => { - qdebug!([self], "received {:?}", s); + debug!("[{self}] received {:?}", s); Ok(s) } } diff --git a/neqo-http3/src/features/extended_connect/webtransport_session.rs b/neqo-http3/src/features/extended_connect/webtransport_session.rs index ea8a87659c..d81c0c62f9 100644 --- a/neqo-http3/src/features/extended_connect/webtransport_session.rs +++ b/neqo-http3/src/features/extended_connect/webtransport_session.rs @@ -6,7 +6,8 @@ use std::{cell::RefCell, collections::BTreeSet, mem, rc::Rc}; -use neqo_common::{qtrace, Encoder, Header, MessageType, Role}; +use log::trace; +use neqo_common::{Encoder, Header, MessageType, Role}; use neqo_qpack::{QPackDecoder, QPackEncoder}; use neqo_transport::{Connection, DatagramTracking, StreamId}; @@ -146,7 +147,7 @@ impl WebTransportSession { } fn receive(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { - qtrace!([self], "receive control data"); + trace!("[{self}] receive control data"); let (out, _) = self.control_stream_recv.receive(conn)?; debug_assert!(out == ReceiveOutput::NoOutput); self.maybe_check_headers(); @@ -207,7 +208,7 @@ impl WebTransportSession { if self.state.closing_state() { return; } - qtrace!("ExtendedConnect close the session"); + trace!("ExtendedConnect close the session"); self.state = SessionState::Done; if !close_type.locally_initiated() { self.events.session_end( @@ -229,7 +230,7 @@ impl WebTransportSession { if let Some((headers, interim, fin)) = self.stream_event_listener.borrow_mut().get_headers() { - qtrace!( + trace!( "ExtendedConnect response headers {:?}, fin={}", headers, fin @@ -346,7 +347,7 @@ impl WebTransportSession { &mut self.control_stream_recv, )) .map_err(|_| Error::HttpGeneralProtocolStream)?; - qtrace!([self], "Received frame: {:?} fin={}", f, fin); + trace!("[{self}] Received frame: {:?} fin={}", f, fin); if let Some(WebTransportFrame::CloseSession { error, message }) = f { self.events.session_end( ExtendedConnectType::WebTransport, @@ -410,7 +411,7 @@ impl WebTransportSession { buf: &[u8], id: impl Into, ) -> Res<()> { - qtrace!([self], "send_datagram state={:?}", self.state); + trace!("[{self}] send_datagram state={:?}", self.state); if self.state == SessionState::Active { let mut dgram_data = Encoder::default(); dgram_data.encode_varint(self.session_id.as_u64() / 4); diff --git a/neqo-http3/src/features/mod.rs b/neqo-http3/src/features/mod.rs index c44ff8eacd..b7924782d7 100644 --- a/neqo-http3/src/features/mod.rs +++ b/neqo-http3/src/features/mod.rs @@ -6,7 +6,7 @@ use std::{fmt::Debug, mem}; -use neqo_common::qtrace; +use log::trace; use crate::{ client_events::Http3ClientEvents, @@ -62,7 +62,7 @@ impl NegotiationState { listener, } = self { - qtrace!( + trace!( "set_negotiated {:?} to {}", feature_type, settings.get(*feature_type) diff --git a/neqo-http3/src/frames/reader.rs b/neqo-http3/src/frames/reader.rs index 6d2c0614b0..7fc92b90b0 100644 --- a/neqo-http3/src/frames/reader.rs +++ b/neqo-http3/src/frames/reader.rs @@ -8,8 +8,9 @@ use std::fmt::Debug; +use log::trace; use neqo_common::{ - hex_with_len, qtrace, Decoder, IncrementalDecoderBuffer, IncrementalDecoderIgnore, + hex_with_len, Decoder, IncrementalDecoderBuffer, IncrementalDecoderIgnore, IncrementalDecoderUint, }; use neqo_transport::{Connection, StreamId}; @@ -173,7 +174,7 @@ impl FrameReader { { (0, f) => (None, false, f), (amount, f) => { - qtrace!("FrameReader::receive: reading {} byte, fin={}", amount, f); + trace!("FrameReader::receive: reading {} byte, fin={}", amount, f); (self.consume::(Decoder::from(&buf[..amount]))?, true, f) } }; @@ -203,13 +204,13 @@ impl FrameReader { match &mut self.state { FrameReaderState::GetType { decoder } => { if let Some(v) = decoder.consume(&mut input) { - qtrace!("FrameReader::receive: read frame type {}", v); + trace!("FrameReader::receive: read frame type {}", v); self.frame_type_decoded::(HFrameType(v))?; } } FrameReaderState::GetLength { decoder } => { if let Some(len) = decoder.consume(&mut input) { - qtrace!( + trace!( "FrameReader::receive: frame type {:?} length {}", self.frame_type, len @@ -219,7 +220,7 @@ impl FrameReader { } FrameReaderState::GetData { decoder } => { if let Some(data) = decoder.consume(&mut input) { - qtrace!( + trace!( "received frame {:?}: {}", self.frame_type, hex_with_len(&data[..]) diff --git a/neqo-http3/src/push_controller.rs b/neqo-http3/src/push_controller.rs index 6efe010c5b..dc73f5e22e 100644 --- a/neqo-http3/src/push_controller.rs +++ b/neqo-http3/src/push_controller.rs @@ -13,7 +13,8 @@ use std::{ slice::SliceIndex, }; -use neqo_common::{qerror, qinfo, qtrace, Header}; +use log::{error, info, trace}; +use neqo_common::Header; use neqo_transport::{Connection, StreamId}; use crate::{ @@ -185,9 +186,8 @@ impl PushController { ref_stream_id: StreamId, new_headers: Vec
, ) -> Res<()> { - qtrace!( - [self], - "New push promise push_id={} headers={:?} max_push={}", + trace!( + "[{self}] New push promise push_id={} headers={:?} max_push={}", push_id, new_headers, self.max_concurent_push @@ -197,7 +197,7 @@ impl PushController { match self.push_streams.get_mut(push_id) { None => { - qtrace!("Push has been closed already {}.", push_id); + trace!("Push has been closed already {}.", push_id); Ok(()) } Some(push_state) => match push_state { @@ -237,7 +237,7 @@ impl PushController { } pub fn add_new_push_stream(&mut self, push_id: u64, stream_id: StreamId) -> Res { - qtrace!( + trace!( "A new push stream with push_id={} stream_id={}", push_id, stream_id @@ -247,7 +247,7 @@ impl PushController { self.push_streams.get_mut(push_id).map_or_else( || { - qinfo!("Push has been closed already."); + info!("Push has been closed already."); Ok(false) }, |push_state| match push_state { @@ -269,7 +269,7 @@ impl PushController { // The following state have already have a push stream: // PushState::OnlyPushStream | PushState::Active _ => { - qerror!("Duplicate push stream."); + error!("Duplicate push stream."); Err(Error::HttpId) } }, @@ -279,7 +279,7 @@ impl PushController { fn check_push_id(&self, push_id: u64) -> Res<()> { // Check if push id is greater than what we allow. if push_id > self.current_max_push_id { - qerror!("Push id is greater than current_max_push_id."); + error!("Push id is greater than current_max_push_id."); Err(Error::HttpId) } else { Ok(()) @@ -292,13 +292,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - qtrace!("CANCEL_PUSH frame has been received, push_id={}", push_id); + trace!("CANCEL_PUSH frame has been received, push_id={}", push_id); self.check_push_id(push_id)?; match self.push_streams.close(push_id) { None => { - qtrace!("Push has already been closed (push_id={}).", push_id); + trace!("Push has already been closed (push_id={}).", push_id); Ok(()) } Some(ps) => match ps { @@ -325,7 +325,7 @@ impl PushController { } pub fn close(&mut self, push_id: u64) { - qtrace!("Push stream has been closed."); + trace!("Push stream has been closed."); if let Some(push_state) = self.push_streams.close(push_id) { debug_assert!(matches!(push_state, PushState::Active { .. })); } else { @@ -339,13 +339,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - qtrace!("Cancel push_id={}", push_id); + trace!("Cancel push_id={}", push_id); self.check_push_id(push_id)?; match self.push_streams.get(push_id) { None => { - qtrace!("Push has already been closed."); + trace!("Push has already been closed."); // If we have some events for the push_id in the event queue, the caller still does // not not know that the push has been closed. Otherwise return // InvalidStreamId. @@ -378,7 +378,7 @@ impl PushController { } pub fn push_stream_reset(&mut self, push_id: u64, close_type: CloseType) { - qtrace!("Push stream has been reset, push_id={}", push_id); + trace!("Push stream has been reset, push_id={}", push_id); if let Some(push_state) = self.push_streams.get(push_id) { match push_state { diff --git a/neqo-http3/src/recv_message.rs b/neqo-http3/src/recv_message.rs index de8dfcec66..4ad2fda5ac 100644 --- a/neqo-http3/src/recv_message.rs +++ b/neqo-http3/src/recv_message.rs @@ -6,7 +6,8 @@ use std::{cell::RefCell, cmp::min, collections::VecDeque, fmt::Debug, rc::Rc}; -use neqo_common::{header::HeadersExt, qdebug, qinfo, qtrace, Header}; +use log::{debug, info, trace}; +use neqo_common::{header::HeadersExt, Header}; use neqo_qpack::decoder::QPackDecoder; use neqo_transport::{Connection, StreamId}; @@ -152,7 +153,7 @@ impl RecvMessage { } fn add_headers(&mut self, mut headers: Vec
, fin: bool) -> Res<()> { - qtrace!([self], "Add new headers fin={}", fin); + trace!("[{self}] Add new headers fin={}", fin); let interim = match self.message_type { MessageType::Request => false, MessageType::Response => is_interim(&headers)?, @@ -199,7 +200,10 @@ impl RecvMessage { fn set_state_to_close_pending(&mut self, post_readable_event: bool) -> Res<()> { // Stream has received fin. Depending on headers state set header_ready // or data_readable event so that app can pick up the fin. - qtrace!([self], "set_state_to_close_pending: state={:?}", self.state); + trace!( + "[{self}] set_state_to_close_pending: state={:?}", + self.state + ); match self.state { RecvMessageState::WaitingForResponseHeaders { .. } => { @@ -250,9 +254,8 @@ impl RecvMessage { } fn receive_internal(&mut self, conn: &mut Connection, post_readable_event: bool) -> Res<()> { - let label = ::neqo_common::log_subject!(::log::Level::Debug, self); loop { - qdebug!([label], "state={:?}.", self.state); + debug!("[{self}] state={:?}.", self.state); match &mut self.state { // In the following 3 states we need to read frames. RecvMessageState::WaitingForResponseHeaders { frame_reader } @@ -267,12 +270,9 @@ impl RecvMessage { } (None, false) => break Ok(()), (Some(frame), fin) => { - qdebug!( - [self], - "A new frame has been received: {:?}; state={:?} fin={}", - frame, - self.state, - fin, + debug!( + "[{self}] A new frame has been received: {:?}; state={:?} fin={}", + frame, self.state, fin, ); match frame { HFrame::Headers { header_block } => { @@ -306,9 +306,8 @@ impl RecvMessage { .refers_dynamic_table(header_block)? && !self.blocked_push_promise.is_empty() { - qinfo!( - [self], - "decoding header is blocked waiting for a push_promise header block." + info!( + "[{self}] decoding header is blocked waiting for a push_promise header block." ); break Ok(()); } @@ -326,7 +325,7 @@ impl RecvMessage { break Ok(()); } } else { - qinfo!([self], "decoding header is blocked."); + info!("[{self}] decoding header is blocked."); break Ok(()); } } diff --git a/neqo-http3/src/send_message.rs b/neqo-http3/src/send_message.rs index 378786d12f..a06ab2fc98 100644 --- a/neqo-http3/src/send_message.rs +++ b/neqo-http3/src/send_message.rs @@ -6,7 +6,8 @@ use std::{cell::RefCell, cmp::min, fmt::Debug, num::NonZeroUsize, rc::Rc}; -use neqo_common::{qdebug, qtrace, Encoder, Header, MessageType}; +use log::{debug, trace}; +use neqo_common::{Encoder, Header, MessageType}; use neqo_qpack::encoder::QPackEncoder; use neqo_transport::{Connection, StreamId}; @@ -119,7 +120,7 @@ impl SendMessage { encoder: Rc>, conn_events: Box, ) -> Self { - qdebug!("Create a request stream_id={}", stream_id); + debug!("Create a request stream_id={}", stream_id); Self { state: MessageState::WaitingForHeaders, message_type, @@ -140,7 +141,7 @@ impl SendMessage { conn: &mut Connection, stream_id: StreamId, ) -> Vec { - qdebug!("Encoding headers"); + debug!("Encoding headers"); let header_block = encoder.encode_header_block(conn, headers, stream_id); let hframe = HFrame::Headers { header_block: header_block.to_vec(), @@ -166,7 +167,7 @@ impl Stream for SendMessage { } impl SendStream for SendMessage { fn send_data(&mut self, conn: &mut Connection, buf: &[u8]) -> Res { - qtrace!([self], "send_body: len={}", buf.len()); + trace!("[{self}] send_body: len={}", buf.len()); self.state.new_data()?; @@ -200,11 +201,9 @@ impl SendStream for SendMessage { min(buf.len(), available - 9) }; - qdebug!( - [self], - "send_request_body: available={} to_send={}.", - available, - to_send + debug!( + "[{self}] send_request_body: available={} to_send={}.", + available, to_send ); let data_frame = HFrame::Data { @@ -250,14 +249,14 @@ impl SendStream for SendMessage { fn send(&mut self, conn: &mut Connection) -> Res<()> { let sent = Error::map_error(self.stream.send_buffer(conn), Error::HttpInternal(5))?; - qtrace!([self], "{} bytes sent", sent); + trace!("[{self}] {} bytes sent", sent); if !self.stream.has_buffered_data() { if self.state.done() { Error::map_error( conn.stream_close_send(self.stream_id()), Error::HttpInternal(6), )?; - qtrace!([self], "done sending request"); + trace!("[{self}] done sending request"); } else { // DataWritable is just a signal for an application to try to write more data, // if writing fails it is fine. Therefore we do not need to properly check diff --git a/neqo-http3/src/server.rs b/neqo-http3/src/server.rs index 8a5dc8a2f3..9ba8dd6a52 100644 --- a/neqo-http3/src/server.rs +++ b/neqo-http3/src/server.rs @@ -14,7 +14,8 @@ use std::{ time::Instant, }; -use neqo_common::{qtrace, Datagram}; +use log::trace; +use neqo_common::Datagram; use neqo_crypto::{AntiReplay, Cipher, PrivateKey, PublicKey, ZeroRttChecker}; use neqo_transport::{ server::{ConnectionRef, Server, ValidateAddress}, @@ -119,13 +120,13 @@ impl Http3Server { } pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - qtrace!([self], "Process."); + trace!("[{self}] Process."); let out = self.server.process(dgram, now); self.process_http3(now); // If we do not that a dgram already try again after process_http3. match out { Output::Datagram(d) => { - qtrace!([self], "Send packet: {:?}", d); + trace!("[{self}] Send packet: {:?}", d); Output::Datagram(d) } _ => self.server.process(Option::::None, now), @@ -134,7 +135,7 @@ impl Http3Server { /// Process HTTP3 layer. fn process_http3(&mut self, now: Instant) { - qtrace!([self], "Process http3 internal."); + trace!("[{self}] Process http3 internal."); // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable // types. #[allow(clippy::mutable_key_type)] diff --git a/neqo-http3/src/server_events.rs b/neqo-http3/src/server_events.rs index 3f174ba0a0..cf04364d84 100644 --- a/neqo-http3/src/server_events.rs +++ b/neqo-http3/src/server_events.rs @@ -13,7 +13,8 @@ use std::{ rc::Rc, }; -use neqo_common::{qdebug, Encoder, Header}; +use log::debug; +use neqo_common::{Encoder, Header}; use neqo_transport::{ server::ConnectionRef, AppError, Connection, DatagramTracking, StreamId, StreamType, }; @@ -114,9 +115,8 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_stop_sending(&self, app_error: AppError) -> Res<()> { - qdebug!( - [self], - "stop sending stream_id:{} error:{}.", + debug!( + "[{self}] stop sending stream_id:{} error:{}.", self.stream_info.stream_id(), app_error ); @@ -133,9 +133,8 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_reset_send(&self, app_error: AppError) -> Res<()> { - qdebug!( - [self], - "reset send stream_id:{} error:{}.", + debug!( + "[{self}] reset send stream_id:{} error:{}.", self.stream_info.stream_id(), app_error ); @@ -152,7 +151,7 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore pub fn cancel_fetch(&self, app_error: AppError) -> Res<()> { - qdebug!([self], "reset error:{}.", app_error); + debug!("[{self}] reset error:{}.", app_error); self.handler.borrow_mut().cancel_fetch( self.stream_info.stream_id(), app_error, @@ -202,7 +201,7 @@ impl Http3OrWebTransportStream { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn send_data(&self, data: &[u8]) -> Res { - qdebug!([self], "Set new response."); + debug!("[{self}] Set new response."); self.stream_handler.send_data(data) } @@ -212,7 +211,7 @@ impl Http3OrWebTransportStream { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_close_send(&self) -> Res<()> { - qdebug!([self], "Set new response."); + debug!("[{self}] Set new response."); self.stream_handler.stream_close_send() } } @@ -283,7 +282,7 @@ impl WebTransportRequest { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn response(&self, accept: &WebTransportSessionAcceptAction) -> Res<()> { - qdebug!([self], "Set a response for a WebTransport session."); + debug!("[{self}] Set a response for a WebTransport session."); self.stream_handler .handler .borrow_mut() diff --git a/neqo-http3/src/stream_type_reader.rs b/neqo-http3/src/stream_type_reader.rs index 8ab8e404b3..89767d6bd7 100644 --- a/neqo-http3/src/stream_type_reader.rs +++ b/neqo-http3/src/stream_type_reader.rs @@ -3,8 +3,8 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. - -use neqo_common::{qtrace, Decoder, IncrementalDecoderUint, Role}; +use log::trace; +use neqo_common::{Decoder, IncrementalDecoderUint, Role}; use neqo_qpack::{decoder::QPACK_UNI_STREAM_TYPE_DECODER, encoder::QPACK_UNI_STREAM_TYPE_ENCODER}; use neqo_transport::{Connection, StreamId, StreamType}; @@ -137,7 +137,7 @@ impl NewStreamHeadReader { return Ok(None); }; - qtrace!("Decoded uint {}", output); + trace!("Decoded uint {}", output); match self { Self::ReadType { role, stream_id, .. @@ -161,7 +161,7 @@ impl NewStreamHeadReader { return Self::map_stream_fin(*t); } (Ok(Some(t)), false) => { - qtrace!("Decoded stream type {:?}", *t); + trace!("Decoded stream type {:?}", *t); *self = Self::Done; return final_type; } @@ -178,7 +178,7 @@ impl NewStreamHeadReader { Self::ReadId { stream_type, .. } => { let is_push = *stream_type == HTTP3_UNI_STREAM_TYPE_PUSH; *self = Self::Done; - qtrace!("New Stream stream push_id={}", output); + trace!("New Stream stream push_id={}", output); if fin { return Err(Error::HttpGeneralProtocol); } diff --git a/neqo-http3/tests/httpconn.rs b/neqo-http3/tests/httpconn.rs index 2e52739fcb..17e60ad233 100644 --- a/neqo-http3/tests/httpconn.rs +++ b/neqo-http3/tests/httpconn.rs @@ -9,7 +9,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{event::Provider, qtrace, Datagram}; +use log::trace; +use neqo_common::{event::Provider, Datagram}; use neqo_crypto::{AuthenticationStatus, ResumptionToken}; use neqo_http3::{ Header, Http3Client, Http3ClientEvent, Http3OrWebTransportStream, Http3Parameters, Http3Server, @@ -174,7 +175,7 @@ fn simple_connect() { fn fetch() { let (mut hconn_c, mut hconn_s, dgram) = connect(); - qtrace!("-----client"); + trace!("-----client"); let req = hconn_c .fetch( now(), @@ -187,13 +188,13 @@ fn fetch() { assert_eq!(req, 0); hconn_c.stream_close_send(req).unwrap(); let out = hconn_c.process(dgram, now()); - qtrace!("-----server"); + trace!("-----server"); let out = hconn_s.process(out.dgram(), now()); mem::drop(hconn_c.process(out.dgram(), now())); process_server_events(&hconn_s); let out = hconn_s.process(None::, now()); - qtrace!("-----client"); + trace!("-----client"); mem::drop(hconn_c.process(out.dgram(), now())); let out = hconn_s.process(None::, now()); mem::drop(hconn_c.process(out.dgram(), now())); @@ -501,7 +502,7 @@ fn fetch_noresponse_will_idletimeout() { let (dgram, mut now) = connect_peers_with_network_propagation_delay(&mut hconn_c, &mut hconn_s, 10); - qtrace!("-----client"); + trace!("-----client"); let req = hconn_c .fetch( now, @@ -514,7 +515,7 @@ fn fetch_noresponse_will_idletimeout() { assert_eq!(req, 0); hconn_c.stream_close_send(req).unwrap(); let _out = hconn_c.process(dgram, now); - qtrace!("-----server"); + trace!("-----server"); let mut done = false; while !done { diff --git a/neqo-qpack/src/decoder.rs b/neqo-qpack/src/decoder.rs index ed1d0b8a18..71e86804fe 100644 --- a/neqo-qpack/src/decoder.rs +++ b/neqo-qpack/src/decoder.rs @@ -4,7 +4,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use neqo_common::{qdebug, Header}; +use log::debug; +use neqo_common::Header; use neqo_transport::{Connection, StreamId}; use crate::{ @@ -40,7 +41,7 @@ impl QPackDecoder { /// If settings include invalid values. #[must_use] pub fn new(qpack_settings: &QpackSettings) -> Self { - qdebug!("Decoder: creating a new qpack decoder."); + debug!("Decoder: creating a new qpack decoder."); let mut send_buf = QpackData::default(); send_buf.encode_varint(QPACK_UNI_STREAM_TYPE_DECODER); Self { @@ -146,7 +147,7 @@ impl QPackDecoder { } fn set_capacity(&mut self, cap: u64) -> Res<()> { - qdebug!([self], "received instruction capacity cap={}", cap); + debug!("[{self}] received instruction capacity cap={}", cap); if cap > self.max_table_size { return Err(Error::EncoderStream); } @@ -186,7 +187,7 @@ impl QPackDecoder { let r = conn .stream_send(self.local_stream_id.unwrap(), &self.send_buf[..]) .map_err(|_| Error::DecoderStream)?; - qdebug!([self], "{} bytes sent.", r); + debug!("[{self}] {} bytes sent.", r); self.send_buf.read(r); } Ok(()) @@ -214,7 +215,7 @@ impl QPackDecoder { buf: &[u8], stream_id: StreamId, ) -> Res>> { - qdebug!([self], "decode header block."); + debug!("[{self}] decode header block."); let mut decoder = HeaderDecoder::new(buf); match decoder.decode_header_block(&self.table, self.max_entries, self.table.base()) { diff --git a/neqo-qpack/src/decoder_instructions.rs b/neqo-qpack/src/decoder_instructions.rs index f69f9da3ac..3dc009fa6d 100644 --- a/neqo-qpack/src/decoder_instructions.rs +++ b/neqo-qpack/src/decoder_instructions.rs @@ -6,7 +6,7 @@ use std::mem; -use neqo_common::{qdebug, qtrace}; +use log::{debug, trace}; use neqo_transport::StreamId; use crate::{ @@ -89,7 +89,7 @@ impl DecoderInstructionReader { /// 2) `ClosedCriticalStream` /// 3) other errors will be translated to `DecoderStream` by the caller of this function. pub fn read_instructions(&mut self, recv: &mut R) -> Res { - qdebug!([self], "read a new instruction"); + debug!("[{self}] read a new instruction"); loop { match &mut self.state { DecoderInstructionReaderState::ReadInstruction => { @@ -108,7 +108,7 @@ impl DecoderInstructionReader { } DecoderInstructionReaderState::ReadInt { reader } => { let val = reader.read(recv)?; - qtrace!([self], "varint read {}", val); + trace!("[{self}] varint read {}", val); match &mut self.instruction { DecoderInstruction::InsertCountIncrement { increment: v } => { *v = val; diff --git a/neqo-qpack/src/encoder.rs b/neqo-qpack/src/encoder.rs index 5ca8e71c4e..14a6e2c528 100644 --- a/neqo-qpack/src/encoder.rs +++ b/neqo-qpack/src/encoder.rs @@ -6,7 +6,8 @@ use std::collections::{HashMap, HashSet, VecDeque}; -use neqo_common::{qdebug, qerror, qlog::NeqoQlog, qtrace, Header}; +use log::{debug, error, trace}; +use neqo_common::{qlog::NeqoQlog, Header}; use neqo_transport::{Connection, Error as TransportError, StreamId}; use crate::{ @@ -92,9 +93,8 @@ impl QPackEncoder { return Ok(()); } - qdebug!( - [self], - "Set max capacity to new capacity:{} old:{} max_table_size={}.", + debug!( + "[{self}] Set max capacity to new capacity:{} old:{} max_table_size={}.", cap, self.table.capacity(), self.max_table_size, @@ -129,7 +129,7 @@ impl QPackEncoder { } fn read_instructions(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { - qdebug!([self], "read a new instruction"); + debug!("[{self}] read a new instruction"); loop { let mut recv = ReceiverConnWrapper::new(conn, stream_id); match self.instruction_reader.read_instructions(&mut recv) { @@ -203,7 +203,7 @@ impl QPackEncoder { } fn call_instruction(&mut self, instruction: DecoderInstruction, qlog: &NeqoQlog) -> Res<()> { - qdebug!([self], "call instruction {:?}", instruction); + debug!("[{self}] call instruction {:?}", instruction); match instruction { DecoderInstruction::InsertCountIncrement { increment } => { qlog::qpack_read_insert_count_increment_instruction( @@ -247,7 +247,7 @@ impl QPackEncoder { name: &[u8], value: &[u8], ) -> Res { - qdebug!([self], "insert {:?} {:?}.", name, value); + debug!("[{self}] insert {:?} {:?}.", name, value); let entry_size = name.len() + value.len() + ADDITIONAL_TABLE_ENTRY_SIZE; @@ -280,7 +280,7 @@ impl QPackEncoder { } fn change_capacity(&mut self, value: u64) { - qdebug!([self], "change capacity: {}", value); + debug!("[{self}] change capacity: {}", value); self.next_capacity = Some(value); } @@ -321,7 +321,7 @@ impl QPackEncoder { pub fn send_encoder_updates(&mut self, conn: &mut Connection) -> Res<()> { match self.local_stream { LocalStreamState::NoStream => { - qerror!("Send call but there is no stream yet."); + error!("Send call but there is no stream yet."); Ok(()) } LocalStreamState::Uninitialized(stream_id) => { @@ -368,7 +368,7 @@ impl QPackEncoder { h: &[Header], stream_id: StreamId, ) -> HeaderEncoder { - qdebug!([self], "encoding headers."); + debug!("[{self}] encoding headers."); // Try to send capacity instructions if present. // This code doesn't try to deal with errors, it just tries @@ -393,7 +393,7 @@ impl QPackEncoder { for iter in h { let name = iter.name().as_bytes().to_vec(); let value = iter.value().as_bytes().to_vec(); - qtrace!("encoding {:x?} {:x?}.", name, value); + trace!("encoding {:x?} {:x?}.", name, value); if let Some(LookupResult { index, @@ -401,9 +401,8 @@ impl QPackEncoder { value_matches, }) = self.table.lookup(&name, &value, can_block) { - qtrace!( - [self], - "found a {} entry, value-match={}", + trace!( + "[{self}] found a {} entry, value-match={}", if static_table { "static" } else { "dynamic" }, value_matches ); diff --git a/neqo-qpack/src/encoder_instructions.rs b/neqo-qpack/src/encoder_instructions.rs index 3fba5c2d96..3a53990c5f 100644 --- a/neqo-qpack/src/encoder_instructions.rs +++ b/neqo-qpack/src/encoder_instructions.rs @@ -6,7 +6,7 @@ use std::mem; -use neqo_common::{qdebug, qtrace}; +use log::{debug, trace}; use crate::{ prefix::{ @@ -176,7 +176,7 @@ impl EncoderInstructionReader { } else { unreachable!("The above patterns match everything."); }; - qdebug!([self], "instruction decoded"); + debug!("[{self}] instruction decoded"); } fn decode_instruction_type(&mut self, recv: &mut T) -> Res<()> { @@ -220,7 +220,7 @@ impl EncoderInstructionReader { &mut self, recv: &mut T, ) -> Res { - qdebug!([self], "reading instructions"); + debug!("[{self}] reading instructions"); loop { match &mut self.state { EncoderInstructionReaderState::ReadInstruction => { @@ -229,7 +229,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadFirstInt { reader } => { let val = reader.read(recv)?; - qtrace!([self], "First varint read {}", val); + trace!("[{self}] First varint read {}", val); match &mut self.instruction { DecodedEncoderInstruction::Capacity { value: v, .. } | DecodedEncoderInstruction::Duplicate { index: v } => { @@ -249,7 +249,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadFirstLiteral { reader } => { let val = reader.read(recv)?; - qtrace!([self], "first literal read {:?}", val); + trace!("[{self}] first literal read {:?}", val); match &mut self.instruction { DecodedEncoderInstruction::InsertWithNameRefStatic { value, .. } | DecodedEncoderInstruction::InsertWithNameRefDynamic { value, .. } => { @@ -268,7 +268,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadSecondLiteral { reader } => { let val = reader.read(recv)?; - qtrace!([self], "second literal read {:?}", val); + trace!("[{self}] second literal read {:?}", val); match &mut self.instruction { DecodedEncoderInstruction::InsertWithNameLiteral { value, .. } => { *value = val; diff --git a/neqo-qpack/src/header_block.rs b/neqo-qpack/src/header_block.rs index d2eab95e3e..c62b5d71ca 100644 --- a/neqo-qpack/src/header_block.rs +++ b/neqo-qpack/src/header_block.rs @@ -9,7 +9,8 @@ use std::{ ops::{Deref, Div}, }; -use neqo_common::{qtrace, Header}; +use log::trace; +use neqo_common::Header; use crate::{ prefix::{ @@ -60,7 +61,7 @@ impl HeaderEncoder { } pub fn encode_indexed_static(&mut self, index: u64) { - qtrace!([self], "encode static index {}.", index); + trace!("[{self}] encode static index {}.", index); self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_STATIC, index); } @@ -76,7 +77,7 @@ impl HeaderEncoder { } pub fn encode_indexed_dynamic(&mut self, index: u64) { - qtrace!([self], "encode dynamic index {}.", index); + trace!("[{self}] encode dynamic index {}.", index); if index < self.base { self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_DYNAMIC, self.base - index - 1); @@ -88,9 +89,8 @@ impl HeaderEncoder { } pub fn encode_literal_with_name_ref(&mut self, is_static: bool, index: u64, value: &[u8]) { - qtrace!( - [self], - "encode literal with name ref - index={}, static={}, value={:x?}", + trace!( + "[{self}] encode literal with name ref - index={}, static={}, value={:x?}", index, is_static, value @@ -116,9 +116,8 @@ impl HeaderEncoder { } pub fn encode_literal_with_name_literal(&mut self, name: &[u8], value: &[u8]) { - qtrace!( - [self], - "encode literal with name literal - name={:x?}, value={:x?}.", + trace!( + "[{self}] encode literal with name literal - name={:x?}, value={:x?}.", name, value ); @@ -147,9 +146,8 @@ impl HeaderEncoder { ) } }); - qtrace!( - [self], - "encode header block prefix max_dynamic_index_ref={:?}, base={}, enc_insert_cnt={}, delta={}, prefix={:?}.", + trace!( + "[{self}] encode header block prefix max_dynamic_index_ref={:?}, base={}, enc_insert_cnt={}, delta={}, prefix={:?}.", self.max_dynamic_index_ref, self.base, enc_insert_cnt, @@ -223,9 +221,8 @@ impl<'a> HeaderDecoder<'a> { )?; if table.base() < self.req_insert_cnt { - qtrace!( - [self], - "decoding is blocked, requested inserts count={}", + trace!( + "[{self}] decoding is blocked, requested inserts count={}", self.req_insert_cnt ); return Ok(HeaderDecoderResult::Blocked(self.req_insert_cnt)); @@ -274,7 +271,7 @@ impl<'a> HeaderDecoder<'a> { } } - qtrace!([self], "done decoding header block."); + trace!("[{self}] done decoding header block."); Ok(HeaderDecoderResult::Headers(h)) } @@ -299,9 +296,8 @@ impl<'a> HeaderDecoder<'a> { .checked_add(base_delta) .ok_or(Error::DecompressionFailed)? }; - qtrace!( - [self], - "requested inserts count is {} and base is {}", + trace!( + "[{self}] requested inserts count is {} and base is {}", self.req_insert_cnt, self.base ); @@ -335,7 +331,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_STATIC.len())?; - qtrace!([self], "decoder static indexed {}.", index); + trace!("[{self}] decoder static indexed {}.", index); let entry = HeaderTable::get_static(index)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -347,7 +343,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC.len())?; - qtrace!([self], "decoder dynamic indexed {}.", index); + trace!("[{self}] decoder dynamic indexed {}.", index); let entry = table.get_dynamic(index, self.base, false)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -359,7 +355,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC_POST.len())?; - qtrace!([self], "decode post-based {}.", index); + trace!("[{self}] decode post-based {}.", index); let entry = table.get_dynamic(index, self.base, true)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -368,10 +364,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_static(&mut self) -> Res
{ - qtrace!( - [self], - "read literal with name reference to the static table." - ); + trace!("[{self}] read literal with name reference to the static table."); let index = self .buf @@ -384,10 +377,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_dynamic(&mut self, table: &HeaderTable) -> Res
{ - qtrace!( - [self], - "read literal with name reference of the dynamic table." - ); + trace!("[{self}] read literal with name reference of the dynamic table."); let index = self .buf @@ -400,7 +390,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_dynamic_post(&mut self, table: &HeaderTable) -> Res
{ - qtrace!([self], "decoder literal with post-based index."); + trace!("[{self}] decoder literal with post-based index."); let index = self .buf @@ -413,7 +403,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_literal(&mut self) -> Res
{ - qtrace!([self], "decode literal with name literal."); + trace!("[{self}] decode literal with name literal."); let name = self .buf diff --git a/neqo-qpack/src/reader.rs b/neqo-qpack/src/reader.rs index d03b118cfa..f564b886a5 100644 --- a/neqo-qpack/src/reader.rs +++ b/neqo-qpack/src/reader.rs @@ -6,7 +6,7 @@ use std::{mem, str}; -use neqo_common::{qdebug, qerror}; +use log::{debug, error}; use neqo_transport::{Connection, StreamId}; use crate::{huffman::decode_huffman, prefix::Prefix, Error, Res}; @@ -207,7 +207,7 @@ impl IntReader { b = s.read_byte()?; if (self.cnt == 63) && (b > 1 || (b == 1 && ((self.value >> 63) == 1))) { - qerror!("Error decoding prefixed encoded int - IntegerOverflow"); + error!("Error decoding prefixed encoded int - IntegerOverflow"); return Err(Error::IntegerOverflow); } self.value += u64::from(b & 0x7f) << self.cnt; @@ -286,7 +286,7 @@ impl LiteralReader { /// When this object is complete. pub fn read(&mut self, s: &mut T) -> Res> { loop { - qdebug!("state = {:?}", self.state); + debug!("state = {:?}", self.state); match &mut self.state { LiteralReaderState::ReadHuffman => { let b = s.read_byte()?; diff --git a/neqo-qpack/src/table.rs b/neqo-qpack/src/table.rs index 8c8b8d5eaf..9936c4aa7a 100644 --- a/neqo-qpack/src/table.rs +++ b/neqo-qpack/src/table.rs @@ -6,7 +6,7 @@ use std::collections::VecDeque; -use neqo_common::qtrace; +use log::trace; use crate::{ static_table::{StaticTableEntry, HEADER_STATIC_TABLE}, @@ -116,7 +116,7 @@ impl HeaderTable { /// The table cannot be reduce if there are entries that are referred at the moment or their /// inserts are unacked. pub fn set_capacity(&mut self, cap: u64) -> Res<()> { - qtrace!([self], "set capacity to {}", cap); + trace!("[{self}] set capacity to {}", cap); if !self.evict_to(cap) { return Err(Error::ChangeCapacity); } @@ -181,7 +181,7 @@ impl HeaderTable { /// Remove a reference to a dynamic table entry. pub fn remove_ref(&mut self, index: u64) { - qtrace!([self], "remove reference to entry {}", index); + trace!("[{self}] remove reference to entry {}", index); self.get_dynamic_with_abs_index(index) .expect("we should have the entry") .remove_ref(); @@ -189,7 +189,7 @@ impl HeaderTable { /// Add a reference to a dynamic table entry. pub fn add_ref(&mut self, index: u64) { - qtrace!([self], "add reference to entry {}", index); + trace!("[{self}] add reference to entry {}", index); self.get_dynamic_with_abs_index(index) .expect("we should have the entry") .add_ref(); @@ -199,9 +199,8 @@ impl HeaderTable { /// The function returns `LookupResult`: `index`, `static_table` (if it is a static table entry) /// and `value_matches` (if the header value matches as well not only header name) pub fn lookup(&mut self, name: &[u8], value: &[u8], can_block: bool) -> Option { - qtrace!( - [self], - "lookup name:{:?} value {:?} can_block={}", + trace!( + "[{self}] lookup name:{:?} value {:?} can_block={}", name, value, can_block @@ -261,9 +260,8 @@ impl HeaderTable { } pub fn evict_to_internal(&mut self, reduce: u64, only_check: bool) -> bool { - qtrace!( - [self], - "reduce table to {}, currently used:{} only_check:{}", + trace!( + "[{self}] reduce table to {}, currently used:{} only_check:{}", reduce, self.used, only_check @@ -296,7 +294,7 @@ impl HeaderTable { /// `DynamicTableFull` if an entry cannot be added to the table because there is not enough /// space and/or other entry cannot be evicted. pub fn insert(&mut self, name: &[u8], value: &[u8]) -> Res { - qtrace!([self], "insert name={:?} value={:?}", name, value); + trace!("[{self}] insert name={:?} value={:?}", name, value); let entry = DynamicTableEntry { name: name.to_vec(), value: value.to_vec(), @@ -328,9 +326,8 @@ impl HeaderTable { name_index: u64, value: &[u8], ) -> Res { - qtrace!( - [self], - "insert with ref to index={} in {} value={:?}", + trace!( + "[{self}] insert with ref to index={} in {} value={:?}", name_index, if name_static_table { "static" @@ -357,7 +354,7 @@ impl HeaderTable { /// space and/or other entry cannot be evicted. /// `HeaderLookup` if the index dos not exits in the static/dynamic table. pub fn duplicate(&mut self, index: u64) -> Res { - qtrace!([self], "duplicate entry={}", index); + trace!("[{self}] duplicate entry={}", index); // need to remember name and value because insert may delete the entry. let name: Vec; let value: Vec; @@ -365,7 +362,7 @@ impl HeaderTable { let entry = self.get_dynamic(index, self.base, false)?; name = entry.name().to_vec(); value = entry.value().to_vec(); - qtrace!([self], "duplicate name={:?} value={:?}", name, value); + trace!("[{self}] duplicate name={:?} value={:?}", name, value); } self.insert(&name, &value) } @@ -376,7 +373,7 @@ impl HeaderTable { /// /// `IncrementAck` if ack is greater than actual number of inserts. pub fn increment_acked(&mut self, increment: u64) -> Res<()> { - qtrace!([self], "increment acked by {}", increment); + trace!("[{self}] increment acked by {}", increment); self.acked_inserts_cnt += increment; if self.base < self.acked_inserts_cnt { return Err(Error::IncrementAck); diff --git a/neqo-transport/src/ackrate.rs b/neqo-transport/src/ackrate.rs index bad69d0a9b..22f2782f31 100644 --- a/neqo-transport/src/ackrate.rs +++ b/neqo-transport/src/ackrate.rs @@ -8,7 +8,7 @@ use std::{cmp::max, time::Duration}; -use neqo_common::qtrace; +use log::trace; use crate::{ connection::params::ACK_RATIO_SCALE, frame::FRAME_TYPE_ACK_FREQUENCY, packet::PacketBuilder, @@ -37,7 +37,7 @@ impl AckRate { let packets = packets.clamp(MIN_PACKETS, MAX_PACKETS) - 1; let delay = rtt * RTT_RATIO / u32::from(ratio); let delay = delay.clamp(minimum, MAX_DELAY); - qtrace!("AckRate inputs: {}/{}/{}, {:?}", cwnd, mtu, ratio, rtt); + trace!("AckRate inputs: {}/{}/{}, {:?}", cwnd, mtu, ratio, rtt); Self { packets, delay } } @@ -82,7 +82,7 @@ impl FlexibleAckRate { mtu: usize, rtt: Duration, ) -> Self { - qtrace!( + trace!( "FlexibleAckRate: {:?} {:?} {}", max_ack_delay, min_ack_delay, @@ -112,7 +112,7 @@ impl FlexibleAckRate { && self.current.needs_update(&self.target) && self.target.write_frame(builder, self.next_frame_seqno) { - qtrace!("FlexibleAckRate: write frame {:?}", self.target); + trace!("FlexibleAckRate: write frame {:?}", self.target); self.frame_outstanding = true; self.next_frame_seqno += 1; tokens.push(RecoveryToken::AckFrequency(self.target.clone())); @@ -131,7 +131,7 @@ impl FlexibleAckRate { fn update(&mut self, cwnd: usize, mtu: usize, rtt: Duration) { self.target = AckRate::new(self.min_ack_delay, self.ratio, cwnd, mtu, rtt); - qtrace!("FlexibleAckRate: {:?} -> {:?}", self.current, self.target); + trace!("FlexibleAckRate: {:?} -> {:?}", self.current, self.target); } fn peer_ack_delay(&self) -> Duration { diff --git a/neqo-transport/src/addr_valid.rs b/neqo-transport/src/addr_valid.rs index 5cb9341e0b..ac7694b3cc 100644 --- a/neqo-transport/src/addr_valid.rs +++ b/neqo-transport/src/addr_valid.rs @@ -11,7 +11,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qinfo, qtrace, Decoder, Encoder, Role}; +use log::{info, trace}; +use neqo_common::{Decoder, Encoder, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, selfencrypt::SelfEncrypt, @@ -148,7 +149,7 @@ impl AddressValidation { } pub fn set_validation(&mut self, validation: ValidateAddress) { - qtrace!("AddressValidation {:p}: set to {:?}", self, validation); + trace!("AddressValidation {:p}: set to {:?}", self, validation); self.validation = validation; } @@ -170,7 +171,7 @@ impl AddressValidation { Some(d) => { let end = self.start_time + Duration::from_millis(u64::from(d)); if end < now { - qtrace!("Expired token: {:?} vs. {:?}", end, now); + trace!("Expired token: {:?} vs. {:?}", end, now); return None; } } @@ -199,7 +200,7 @@ impl AddressValidation { peer_address: SocketAddr, now: Instant, ) -> AddressValidationResult { - qtrace!( + trace!( "AddressValidation {:p}: validate {:?}", self, self.validation @@ -207,15 +208,15 @@ impl AddressValidation { if token.is_empty() { if self.validation == ValidateAddress::Never { - qinfo!("AddressValidation: no token; accepting"); + info!("AddressValidation: no token; accepting"); return AddressValidationResult::Pass; } - qinfo!("AddressValidation: no token; validating"); + info!("AddressValidation: no token; validating"); return AddressValidationResult::Validate; } if token.len() <= TOKEN_IDENTIFIER_RETRY.len() { // Treat bad tokens strictly. - qinfo!("AddressValidation: too short token"); + info!("AddressValidation: too short token"); return AddressValidationResult::Invalid; } let retry = Self::is_likely_retry(token); @@ -227,7 +228,7 @@ impl AddressValidation { if retry { // This is from Retry, so we should have an ODCID >= 8. if cid.len() >= 8 { - qinfo!("AddressValidation: valid Retry token for {}", cid); + info!("AddressValidation: valid Retry token for {}", cid); AddressValidationResult::ValidRetry(cid) } else { panic!("AddressValidation: Retry token with small CID {cid}"); @@ -235,10 +236,10 @@ impl AddressValidation { } else if cid.is_empty() { // An empty connection ID means NEW_TOKEN. if self.validation == ValidateAddress::Always { - qinfo!("AddressValidation: valid NEW_TOKEN token; validating again"); + info!("AddressValidation: valid NEW_TOKEN token; validating again"); AddressValidationResult::Validate } else { - qinfo!("AddressValidation: valid NEW_TOKEN token; accepting"); + info!("AddressValidation: valid NEW_TOKEN token; accepting"); AddressValidationResult::Pass } } else { @@ -249,16 +250,16 @@ impl AddressValidation { // We've either lost the keys or we've received junk. if retry { // If this looked like a Retry, treat it as being bad. - qinfo!("AddressValidation: invalid Retry token; rejecting"); + info!("AddressValidation: invalid Retry token; rejecting"); AddressValidationResult::Invalid } else if self.validation == ValidateAddress::Never { // We don't require validation, so OK. - qinfo!("AddressValidation: invalid NEW_TOKEN token; accepting"); + info!("AddressValidation: invalid NEW_TOKEN token; accepting"); AddressValidationResult::Pass } else { // This might be an invalid NEW_TOKEN token, or a valid one // for which we have since lost the keys. Check again. - qinfo!("AddressValidation: invalid NEW_TOKEN token; validating again"); + info!("AddressValidation: invalid NEW_TOKEN token; validating again"); AddressValidationResult::Validate } } @@ -327,7 +328,7 @@ impl NewTokenState { { for t in old.iter().rev().chain(pending.iter().rev()) { if t == &token { - qinfo!("NewTokenState discarding duplicate NEW_TOKEN"); + info!("NewTokenState discarding duplicate NEW_TOKEN"); return; } } diff --git a/neqo-transport/src/cc/classic_cc.rs b/neqo-transport/src/cc/classic_cc.rs index 5dc7356a19..1f46de65ea 100644 --- a/neqo-transport/src/cc/classic_cc.rs +++ b/neqo-transport/src/cc/classic_cc.rs @@ -12,6 +12,8 @@ use std::{ time::{Duration, Instant}, }; +use log::{debug, info, trace}; + use super::CongestionControl; use crate::{ packet::PacketNumber, @@ -23,7 +25,7 @@ use crate::{ }; #[rustfmt::skip] // to keep `::` and thus prevent conflict with `crate::qlog` use ::qlog::events::{quic::CongestionStateUpdated, EventData}; -use neqo_common::{const_max, const_min, qdebug, qinfo, qlog::NeqoQlog, qtrace}; +use neqo_common::{const_max, const_min, qlog::NeqoQlog}; pub const CWND_INITIAL_PKTS: usize = 10; const PERSISTENT_CONG_THRESH: u32 = 3; @@ -190,7 +192,7 @@ impl CongestionControl for ClassicCongestionControl { let mut is_app_limited = true; let mut new_acked = 0; for pkt in acked_pkts { - qtrace!( + trace!( "packet_acked this={:p}, pn={}, ps={}, ignored={}, lost={}, rtt_est={:?}", self, pkt.pn(), @@ -225,7 +227,7 @@ impl CongestionControl for ClassicCongestionControl { if is_app_limited { self.cc_algorithm.on_app_limited(); - qdebug!("on_packets_acked this={:p}, limited=1, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={}", self, self.bytes_in_flight, self.congestion_window, self.state, new_acked); + debug!("on_packets_acked this={:p}, limited=1, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={}", self, self.bytes_in_flight, self.congestion_window, self.state, new_acked); return; } @@ -235,7 +237,7 @@ impl CongestionControl for ClassicCongestionControl { let increase = min(self.ssthresh - self.congestion_window, self.acked_bytes); self.congestion_window += increase; self.acked_bytes -= increase; - qdebug!([self], "slow start += {}", increase); + debug!("[{self}] slow start += {}", increase); if self.congestion_window == self.ssthresh { // This doesn't look like it is necessary, but it can happen // after persistent congestion. @@ -278,7 +280,7 @@ impl CongestionControl for ClassicCongestionControl { ], now, ); - qdebug!([self], "on_packets_acked this={:p}, limited=0, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={}", self, self.bytes_in_flight, self.congestion_window, self.state, new_acked); + debug!("[{self}] on_packets_acked this={:p}, limited=0, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={}", self, self.bytes_in_flight, self.congestion_window, self.state, new_acked); } /// Update congestion controller state based on lost packets. @@ -295,7 +297,7 @@ impl CongestionControl for ClassicCongestionControl { } for pkt in lost_packets.iter().filter(|pkt| pkt.cc_in_flight()) { - qdebug!( + debug!( "packet_lost this={:p}, pn={}, ps={}", self, pkt.pn(), @@ -331,12 +333,9 @@ impl CongestionControl for ClassicCongestionControl { lost_packets.rev(), now, ); - qdebug!( + debug!( "on_packets_lost this={:p}, bytes_in_flight={}, cwnd={}, state={:?}", - self, - self.bytes_in_flight, - self.congestion_window, - self.state + self, self.bytes_in_flight, self.congestion_window, self.state ); congestion || persistent_congestion } @@ -358,7 +357,7 @@ impl CongestionControl for ClassicCongestionControl { &[QlogMetric::BytesInFlight(self.bytes_in_flight)], now, ); - qtrace!([self], "Ignore pkt with size {}", pkt.len()); + trace!("[{self}] Ignore pkt with size {}", pkt.len()); } } @@ -390,7 +389,7 @@ impl CongestionControl for ClassicCongestionControl { } self.bytes_in_flight += pkt.len(); - qdebug!( + debug!( "packet_sent this={:p}, pn={}, ps={}", self, pkt.pn(), @@ -457,7 +456,7 @@ impl ClassicCongestionControl { fn set_state(&mut self, state: State, now: Instant) { if self.state != state { - qdebug!([self], "state -> {:?}", state); + debug!("[{self}] state -> {:?}", state); let old_state = self.state; self.qlog.add_event_data_with_instant( || { @@ -520,7 +519,7 @@ impl ClassicCongestionControl { .checked_duration_since(t) .expect("time is monotonic"); if elapsed > pc_period { - qinfo!([self], "persistent congestion"); + info!("[{self}] persistent congestion"); self.congestion_window = self.cwnd_min(); self.acked_bytes = 0; self.set_state(State::PersistentCongestion, now); @@ -566,11 +565,9 @@ impl ClassicCongestionControl { self.congestion_window = max(cwnd, self.cwnd_min()); self.acked_bytes = acked_bytes; self.ssthresh = self.congestion_window; - qdebug!( - [self], - "Cong event -> recovery; cwnd {}, ssthresh {}", - self.congestion_window, - self.ssthresh + debug!( + "[{self}] Cong event -> recovery; cwnd {}, ssthresh {}", + self.congestion_window, self.ssthresh ); qlog::metrics_updated( &self.qlog, @@ -609,7 +606,8 @@ mod tests { time::{Duration, Instant}, }; - use neqo_common::{qinfo, IpTosEcn}; + use log::info; + use neqo_common::IpTosEcn; use test_fixture::now; use super::{ClassicCongestionControl, WindowAdjustment, PERSISTENT_CONG_THRESH}; @@ -1144,7 +1142,7 @@ mod tests { (ABOVE_APP_LIMIT_PKTS - i - 1) * cc.max_datagram_size() ); // increase acked_bytes with each packet - qinfo!( + info!( "{} {}", cc.congestion_window, cwnd + i * cc.max_datagram_size() diff --git a/neqo-transport/src/cc/cubic.rs b/neqo-transport/src/cc/cubic.rs index c8c0188ddb..51c78a65fd 100644 --- a/neqo-transport/src/cc/cubic.rs +++ b/neqo-transport/src/cc/cubic.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::qtrace; +use log::trace; use crate::cc::classic_cc::WindowAdjustment; @@ -119,7 +119,7 @@ impl Cubic { self.w_max = self.last_max_cwnd; self.k = self.calc_k(curr_cwnd_f64, max_datagram_size); } - qtrace!([self], "New epoch"); + trace!("[{self}] New epoch"); } } diff --git a/neqo-transport/src/cid.rs b/neqo-transport/src/cid.rs index 0e3144a707..5a046b418e 100644 --- a/neqo-transport/src/cid.rs +++ b/neqo-transport/src/cid.rs @@ -14,7 +14,8 @@ use std::{ rc::Rc, }; -use neqo_common::{hex, hex_with_len, qdebug, qinfo, Decoder, Encoder}; +use log::{debug, info}; +use neqo_common::{hex, hex_with_len, Decoder, Encoder}; use neqo_crypto::{random, randomize}; use smallvec::{smallvec, SmallVec}; @@ -392,7 +393,7 @@ impl ConnectionIdStore<[u8; 16]> { } // It's not OK if any individual piece matches though. if self.cids.iter().any(|c| c.any_part_equal(&entry)) { - qinfo!("ConnectionIdStore found reused part in NEW_CONNECTION_ID"); + info!("ConnectionIdStore found reused part in NEW_CONNECTION_ID"); return Err(Error::ProtocolViolation); } @@ -521,7 +522,7 @@ impl ConnectionIdManager { .iter() .any(|c| c.seqno == seqno && c.cid.is_empty()); if empty_cid { - qdebug!("Connection ID {seqno} is zero-length, not retiring"); + debug!("Connection ID {seqno} is zero-length, not retiring"); } else { self.connection_ids.retire(seqno); self.lost_new_connection_id.retain(|cid| cid.seqno != seqno); diff --git a/neqo-transport/src/connection/dump.rs b/neqo-transport/src/connection/dump.rs index 10e1025524..071ec692ef 100644 --- a/neqo-transport/src/connection/dump.rs +++ b/neqo-transport/src/connection/dump.rs @@ -9,7 +9,8 @@ use std::fmt::Write; -use neqo_common::{qdebug, Decoder, IpTos}; +use log::debug; +use neqo_common::{Decoder, IpTos}; use crate::{ connection::Connection, @@ -45,9 +46,8 @@ pub fn dump_packet( _ = write!(&mut s, "\n {} {}", dir, &x); } } - qdebug!( - [conn], - "pn={} type={:?} {} {:?} len {}{}", + debug!( + "[{conn}] pn={} type={:?} {} {:?} len {}{}", pn, pt, path.borrow(), diff --git a/neqo-transport/src/connection/idle.rs b/neqo-transport/src/connection/idle.rs index c5b570a09c..f47a9bc7a0 100644 --- a/neqo-transport/src/connection/idle.rs +++ b/neqo-transport/src/connection/idle.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::qtrace; +use log::trace; use crate::recovery::RecoveryToken; @@ -56,7 +56,7 @@ impl IdleTimeout { pub fn expiry(&self, now: Instant, pto: Duration) -> Instant { let delay = max(self.timeout, pto * 3); let t = self.start(now) + delay; - qtrace!("IdleTimeout::expiry@{now:?} pto={pto:?} => {t:?}"); + trace!("IdleTimeout::expiry@{now:?} pto={pto:?} => {t:?}"); t } diff --git a/neqo-transport/src/connection/mod.rs b/neqo-transport/src/connection/mod.rs index 6233746c22..5c796ca374 100644 --- a/neqo-transport/src/connection/mod.rs +++ b/neqo-transport/src/connection/mod.rs @@ -18,9 +18,10 @@ use std::{ time::{Duration, Instant}, }; +use log::{debug, error, info, trace, warn}; use neqo_common::{ - event::Provider as EventProvider, hex, hex_snip_middle, hrtime, qdebug, qerror, qinfo, - qlog::NeqoQlog, qtrace, qwarn, Datagram, Decoder, Encoder, Role, + event::Provider as EventProvider, hex, hex_snip_middle, hrtime, qlog::NeqoQlog, Datagram, + Decoder, Encoder, Role, }; use neqo_crypto::{ agent::CertificateInfo, Agent, AntiReplay, AuthenticationStatus, Cipher, Client, Group, @@ -505,8 +506,8 @@ impl Connection { self.tps.borrow_mut().local.set(tp, value); Ok(()) } else { - qerror!("Current state: {:?}", self.state()); - qerror!("Cannot set local tparam when not in an initial connection state."); + error!("Current state: {:?}", self.state()); + error!("Cannot set local tparam when not in an initial connection state."); Err(Error::ConnectionState) } } @@ -522,9 +523,8 @@ impl Connection { retry_cid: &ConnectionId, ) { debug_assert_eq!(self.role, Role::Server); - qtrace!( - [self], - "Retry CIDs: odcid={} remote={} retry={}", + trace!( + "[{self}] Retry CIDs: odcid={} remote={} retry={}", odcid, remote_cid, retry_cid @@ -560,7 +560,7 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> { if self.state != State::Init { - qerror!([self], "Cannot enable ciphers in state {:?}", self.state); + error!("[{self}] Cannot enable ciphers in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.set_ciphers(ciphers)?; @@ -572,7 +572,7 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn set_groups(&mut self, groups: &[Group]) -> Res<()> { if self.state != State::Init { - qerror!([self], "Cannot enable groups in state {:?}", self.state); + error!("[{self}] Cannot enable groups in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.set_groups(groups)?; @@ -584,7 +584,7 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn send_additional_key_shares(&mut self, count: usize) -> Res<()> { if self.state != State::Init { - qerror!([self], "Cannot enable groups in state {:?}", self.state); + error!("[{self}] Cannot enable groups in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.send_additional_key_shares(count)?; @@ -648,9 +648,8 @@ impl Connection { return; } - qtrace!( - [self], - "Maybe create resumption token: {} {}", + trace!( + "[{self}] Maybe create resumption token: {} {}", self.crypto.has_resumption_token(), self.new_token.has_token() ); @@ -717,16 +716,15 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn enable_resumption(&mut self, now: Instant, token: impl AsRef<[u8]>) -> Res<()> { if self.state != State::Init { - qerror!([self], "set token in state {:?}", self.state); + error!("[{self}] set token in state {:?}", self.state); return Err(Error::ConnectionState); } if self.role == Role::Server { return Err(Error::ConnectionState); } - qinfo!( - [self], - "resumption token {}", + info!( + "[{self}] resumption token {}", hex_snip_middle(token.as_ref()) ); let mut dec = Decoder::from(token.as_ref()); @@ -735,25 +733,25 @@ impl Connection { dec.decode_uint::() .ok_or(Error::InvalidResumptionToken)?, )?; - qtrace!([self], " version {:?}", version); + trace!("[{self}] version {:?}", version); if !self.conn_params.get_versions().all().contains(&version) { return Err(Error::DisabledVersion); } let rtt = Duration::from_millis(dec.decode_varint().ok_or(Error::InvalidResumptionToken)?); - qtrace!([self], " RTT {:?}", rtt); + trace!("[{self}] RTT {:?}", rtt); let tp_slice = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?; - qtrace!([self], " transport parameters {}", hex(tp_slice)); + trace!("[{self}] transport parameters {}", hex(tp_slice)); let mut dec_tp = Decoder::from(tp_slice); let tp = TransportParameters::decode(&mut dec_tp).map_err(|_| Error::InvalidResumptionToken)?; let init_token = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?; - qtrace!([self], " Initial token {}", hex(init_token)); + trace!("[{self}] Initial token {}", hex(init_token)); let tok = dec.decode_remainder(); - qtrace!([self], " TLS token {}", hex(tok)); + trace!("[{self}] TLS token {}", hex(tok)); match self.crypto.tls { Agent::Client(ref mut c) => { @@ -788,7 +786,7 @@ impl Connection { } pub(crate) fn set_validation(&mut self, validation: &Rc>) { - qtrace!([self], "Enabling NEW_TOKEN"); + trace!("[{self}] Enabling NEW_TOKEN"); assert_eq!(self.role, Role::Server); self.address_validation = AddressValidationInfo::Server(Rc::downgrade(validation)); } @@ -809,7 +807,7 @@ impl Connection { }); enc.encode(extra); let records = s.send_ticket(now, enc.as_ref())?; - qdebug!([self], "send session ticket {}", hex(&enc)); + debug!("[{self}] send session ticket {}", hex(&enc)); self.crypto.buffer_records(records)?; } else { unreachable!(); @@ -855,7 +853,7 @@ impl Connection { /// the connection to fail. However, if no packets have been /// exchanged, it's not OK. pub fn authenticated(&mut self, status: AuthenticationStatus, now: Instant) { - qdebug!([self], "Authenticated {:?}", status); + debug!("[{self}] Authenticated {:?}", status); self.crypto.tls.authenticated(status); let res = self.handshake(now, self.version, PacketNumberSpace::Handshake, None); self.absorb_error(now, res); @@ -917,7 +915,7 @@ impl Connection { State::Closing { error: err, .. } | State::Draining { error: err, .. } | State::Closed(err) => { - qwarn!([self], "Closing again after error {:?}", err); + warn!("[{self}] Closing again after error {:?}", err); } State::Init => { // We have not even sent anything just close the connection without sending any @@ -972,12 +970,12 @@ impl Connection { if *timeout <= now { let st = State::Closed(error.clone()); self.set_state(st, now); - qinfo!("Closing timer expired"); + info!("Closing timer expired"); return; } } State::Closed(_) => { - qdebug!("Timer fired while closed"); + debug!("Timer fired while closed"); return; } _ => (), @@ -985,7 +983,7 @@ impl Connection { let pto = self.pto(); if self.idle_timeout.expired(now, pto) { - qinfo!([self], "idle timeout expired"); + info!("[{self}] idle timeout expired"); self.set_state( State::Closed(CloseReason::Transport(Error::IdleTimeout)), now, @@ -994,7 +992,7 @@ impl Connection { } if self.state.closing() { - qtrace!([self], "Closing, not processing other timers"); + trace!("[{self}] Closing, not processing other timers"); return; } @@ -1017,7 +1015,7 @@ impl Connection { .paths .process_timeout(now, pto, &mut self.stats.borrow_mut()) { - qinfo!([self], "last available path failed"); + info!("[{self}] last available path failed"); self.absorb_error::(now, Err(Error::NoAvailablePath)); } } @@ -1053,7 +1051,7 @@ impl Connection { /// Get the time that we next need to be called back, relative to `now`. fn next_delay(&mut self, now: Instant, paced: bool) -> Duration { - qtrace!([self], "Get callback delay {:?}", now); + trace!("[{self}] Get callback delay {:?}", now); // Only one timer matters when closing... if let State::Closing { timeout, .. } | State::Draining { timeout, .. } = self.state { @@ -1063,7 +1061,7 @@ impl Connection { let mut delays = SmallVec::<[_; 7]>::new(); if let Some(ack_time) = self.acks.ack_time(now) { - qtrace!([self], "Delayed ACK timer {:?}", ack_time); + trace!("[{self}] Delayed ACK timer {:?}", ack_time); delays.push(ack_time); } @@ -1073,36 +1071,36 @@ impl Connection { let pto = rtt.pto(self.confirmed()); let idle_time = self.idle_timeout.expiry(now, pto); - qtrace!([self], "Idle timer {:?}", idle_time); + trace!("[{self}] Idle timer {:?}", idle_time); delays.push(idle_time); if self.streams.need_keep_alive() { if let Some(keep_alive_time) = self.idle_timeout.next_keep_alive(now, pto) { - qtrace!([self], "Keep alive timer {:?}", keep_alive_time); + trace!("[{self}] Keep alive timer {:?}", keep_alive_time); delays.push(keep_alive_time); } } if let Some(lr_time) = self.loss_recovery.next_timeout(&path) { - qtrace!([self], "Loss recovery timer {:?}", lr_time); + trace!("[{self}] Loss recovery timer {:?}", lr_time); delays.push(lr_time); } if paced { if let Some(pace_time) = path.sender().next_paced(rtt.estimate()) { - qtrace!([self], "Pacing timer {:?}", pace_time); + trace!("[{self}] Pacing timer {:?}", pace_time); delays.push(pace_time); } } if let Some(path_time) = self.paths.next_timeout(pto) { - qtrace!([self], "Path probe timer {:?}", path_time); + trace!("[{self}] Path probe timer {:?}", path_time); delays.push(path_time); } } if let Some(key_update_time) = self.crypto.states.update_time() { - qtrace!([self], "Key update timer {:?}", key_update_time); + trace!("[{self}] Key update timer {:?}", key_update_time); delays.push(key_update_time); } @@ -1116,7 +1114,7 @@ impl Connection { // rather than just clamping to zero here. debug_assert!(earliest > now); let delay = earliest.saturating_duration_since(now); - qdebug!([self], "delay duration {:?}", delay); + debug!("[{self}] delay duration {:?}", delay); self.hrtime.update(delay / 4); delay } @@ -1127,7 +1125,7 @@ impl Connection { /// even if no incoming packets. #[must_use = "Output of the process_output function must be handled"] pub fn process_output(&mut self, now: Instant) -> Output { - qtrace!([self], "process_output {:?} {:?}", self.state, now); + trace!("[{self}] process_output {:?} {:?}", self.state, now); match (&self.state, self.role) { (State::Init, Role::Client) => { @@ -1186,7 +1184,7 @@ impl Connection { } fn handle_retry(&mut self, packet: &PublicPacket, now: Instant) -> Res<()> { - qinfo!([self], "received Retry"); + info!("[{self}] received Retry"); if matches!(self.address_validation, AddressValidationInfo::Retry { .. }) { self.stats.borrow_mut().pkt_dropped("Extra Retry"); return Ok(()); @@ -1217,9 +1215,8 @@ impl Connection { path.borrow_mut().set_remote_cid(packet.scid()); let retry_scid = ConnectionId::from(packet.scid()); - qinfo!( - [self], - "Valid Retry received, token={} scid={}", + info!( + "[{self}] Valid Retry received, token={} scid={}", hex(packet.token()), retry_scid ); @@ -1241,7 +1238,7 @@ impl Connection { fn discard_keys(&mut self, space: PacketNumberSpace, now: Instant) { if self.crypto.discard(space) { - qdebug!([self], "Drop packet number space {}", space); + debug!("[{self}] Drop packet number space {}", space); if let Some(path) = self.paths.primary() { self.loss_recovery.discard(&path, space, now); } @@ -1269,7 +1266,7 @@ impl Connection { if first && self.is_stateless_reset(path, d) { // Failing to process a packet in a datagram might // indicate that there is a stateless reset present. - qdebug!([self], "Stateless reset: {}", hex(&d[d.len() - 16..])); + debug!("[{self}] Stateless reset: {}", hex(&d[d.len() - 16..])); self.state_signaling.reset(); self.set_state( State::Draining { @@ -1287,10 +1284,10 @@ impl Connection { /// Process any saved datagrams that might be available for processing. fn process_saved(&mut self, now: Instant) { while let Some(cspace) = self.saved_datagrams.available() { - qdebug!([self], "process saved for space {:?}", cspace); + debug!("[{self}] process saved for space {:?}", cspace); debug_assert!(self.crypto.states.rx_hp(self.version, cspace).is_some()); for saved in self.saved_datagrams.take_saved() { - qtrace!([self], "input saved @{:?}: {:?}", saved.t, saved.d); + trace!("[{self}] input saved @{:?}: {:?}", saved.t, saved.d); self.input(saved.d, saved.t, now); } } @@ -1323,7 +1320,7 @@ impl Connection { if let Some(version) = self.conn_params.get_versions().preferred(supported) { assert_ne!(self.version, version); - qinfo!([self], "Version negotiation: trying {:?}", version); + info!("[{self}] Version negotiation: trying {:?}", version); let path = self.paths.primary().ok_or(Error::NoAvailablePath)?; let local_addr = path.borrow().local_address(); let remote_addr = path.borrow().remote_address(); @@ -1353,7 +1350,7 @@ impl Connection { ); Ok(()) } else { - qinfo!([self], "Version negotiation: failed with {:?}", supported); + info!("[{self}] Version negotiation: failed with {:?}", supported); // This error goes straight to closed. self.set_state( State::Closed(CloseReason::Transport(Error::VersionNegotiation)), @@ -1400,9 +1397,8 @@ impl Connection { self.stats.borrow_mut().pkt_dropped("Invalid Initial"); return Ok(PreprocessResult::Next); } - qinfo!( - [self], - "Received valid Initial packet with scid {:?} dcid {:?}", + info!( + "[{self}] Received valid Initial packet with scid {:?} dcid {:?}", packet.scid(), packet.dcid() ); @@ -1525,7 +1521,7 @@ impl Connection { *space_ecn_marks += d.tos().into(); self.stats.borrow_mut().ecn_rx = *space_ecn_marks; } else { - qtrace!("Not tracking ECN for dropped packet number space"); + trace!("Not tracking ECN for dropped packet number space"); } if self.state == State::WaitInitial { @@ -1569,7 +1565,7 @@ impl Connection { let mut slc = d.as_ref(); let mut dcid = None; - qtrace!([self], "{} input {}", path.borrow(), hex(&d)); + trace!("[{self}] {} input {}", path.borrow(), hex(&d)); let pto = path.borrow().rtt().pto(self.confirmed()); // Handle each packet in the datagram. @@ -1579,8 +1575,8 @@ impl Connection { match PublicPacket::decode(slc, self.cid_manager.decoder().as_ref()) { Ok((packet, remainder)) => (packet, remainder), Err(e) => { - qinfo!([self], "Garbage packet: {}", e); - qtrace!([self], "Garbage packet contents: {}", hex(slc)); + info!("[{self}] Garbage packet: {}", e); + trace!("[{self}] Garbage packet contents: {}", hex(slc)); self.stats.borrow_mut().pkt_dropped("Garbage packet"); break; } @@ -1591,7 +1587,7 @@ impl Connection { PreprocessResult::End => return Ok(()), } - qtrace!([self], "Received unverified packet {:?}", packet); + trace!("[{self}] Received unverified packet {:?}", packet); match packet.decrypt(&mut self.crypto.states, now + pto) { Ok(payload) => { @@ -1622,7 +1618,7 @@ impl Connection { let space = PacketNumberSpace::from(payload.packet_type()); if let Some(space) = self.acks.get_mut(space) { if space.is_duplicate(payload.pn()) { - qdebug!("Duplicate packet {}-{}", space, payload.pn()); + debug!("Duplicate packet {}-{}", space, payload.pn()); self.stats.borrow_mut().dups_rx += 1; } else { match self.process_packet(path, &payload, now) { @@ -1636,9 +1632,8 @@ impl Connection { } } } else { - qdebug!( - [self], - "Received packet {} for untracked space {}", + debug!( + "[{self}] Received packet {} for untracked space {}", space, payload.pn() ); @@ -1738,9 +1733,8 @@ impl Connection { { space.set_received(now, packet.pn(), ack_eliciting) } else { - qdebug!( - [self], - "processed a {:?} packet without tracking it", + debug!( + "[{self}] processed a {:?} packet without tracking it", packet.packet_type(), ); // This was a valid packet that caused the same packet number to be @@ -1797,11 +1791,11 @@ impl Connection { .make_permanent(path, None, ConnectionIdEntry::empty_remote(), now); Ok(()) } else { - qtrace!([self], "Unable to make path permanent: {}", path.borrow()); + trace!("[{self}] Unable to make path permanent: {}", path.borrow()); Err(Error::InvalidMigration) } } else { - qtrace!([self], "Unable to make path permanent: {}", path.borrow()); + trace!("[{self}] Unable to make path permanent: {}", path.borrow()); Err(Error::InvalidMigration) } } else { @@ -1827,7 +1821,7 @@ impl Connection { } fn start_handshake(&mut self, path: &PathRef, packet: &PublicPacket, now: Instant) { - qtrace!([self], "starting handshake"); + trace!("[{self}] starting handshake"); debug_assert_eq!(packet.packet_type(), PacketType::Initial); self.remote_initial_source_cid = Some(ConnectionId::from(packet.scid())); @@ -1838,17 +1832,17 @@ impl Connection { self.setup_handshake_path(path, now); self.zero_rtt_state = if self.crypto.enable_0rtt(self.version, self.role) == Ok(true) { - qdebug!([self], "Accepted 0-RTT"); + debug!("[{self}] Accepted 0-RTT"); ZeroRttState::AcceptedServer } else { - qtrace!([self], "Rejected 0-RTT"); + trace!("[{self}] Rejected 0-RTT"); ZeroRttState::Rejected }; // The server knows the final version if it has remote transport parameters. self.tps.borrow().remote.is_some() } else { - qdebug!([self], "Changing to use Server CID={}", packet.scid()); + debug!("[{self}] Changing to use Server CID={}", packet.scid()); debug_assert!(path.borrow().is_primary()); path.borrow_mut().set_remote_cid(packet.scid()); @@ -1927,9 +1921,8 @@ impl Connection { now, ); self.ensure_permanent(&path, now)?; - qinfo!( - [self], - "Migrate to {} probe {}", + info!( + "[{self}] Migrate to {} probe {}", path.borrow(), if force { "now" } else { "after" } ); @@ -1947,7 +1940,7 @@ impl Connection { self.conn_params.get_preferred_address(), PreferredAddressConfig::Disabled ) { - qdebug!([self], "Preferred address is disabled"); + debug!("[{self}] Preferred address is disabled"); None } else { self.tps.borrow_mut().remote().get_preferred_address() @@ -1975,18 +1968,18 @@ impl Connection { // Ignore preferred address that move to loopback from non-loopback. // `migrate` doesn't enforce this rule. if !prev.ip().is_loopback() && remote.ip().is_loopback() { - qwarn!([self], "Ignoring a move to a loopback address: {}", remote); + warn!("[{self}] Ignoring a move to a loopback address: {}", remote); return Ok(()); } if self.migrate(None, Some(remote), false, now).is_err() { - qwarn!([self], "Ignoring bad preferred address: {}", remote); + warn!("[{self}] Ignoring bad preferred address: {}", remote); } } else { - qwarn!([self], "Unable to migrate to a different address family"); + warn!("[{self}] Unable to migrate to a different address family"); } } else { - qdebug!([self], "No preferred address to migrate to"); + debug!("[{self}] No preferred address to migrate to"); } Ok(()) } @@ -2009,16 +2002,15 @@ impl Connection { self.paths .handle_migration(path, d.source(), now, &mut self.stats.borrow_mut()); } else { - qinfo!( - [self], - "{} Peer migrated, but no connection ID available", + info!( + "[{self}] {} Peer migrated, but no connection ID available", path.borrow() ); } } fn output(&mut self, now: Instant) -> SendOption { - qtrace!([self], "output {:?}", now); + trace!("[{self}] output {:?}", now); let res = match &self.state { State::Init | State::WaitInitial @@ -2042,7 +2034,7 @@ impl Connection { // a packet on a new path, we avoid sending (and the privacy risk) rather // than reuse a connection ID. let res = if path.borrow().is_temporary() { - qerror!([self], "Attempting to close with a temporary path"); + error!("[{self}] Attempting to close with a temporary path"); Err(Error::InternalError) } else { self.output_path(&path, now, Some(&details)) @@ -2066,10 +2058,10 @@ impl Connection { ) -> (PacketType, PacketBuilder) { let pt = PacketType::from(cspace); let mut builder = if pt == PacketType::Short { - qdebug!("Building Short dcid {:?}", path.remote_cid()); + debug!("Building Short dcid {:?}", path.remote_cid()); PacketBuilder::short(encoder, tx.key_phase(), path.remote_cid()) } else { - qdebug!( + debug!( "Building {:?} dcid {:?} scid {:?}", pt, path.remote_cid(), @@ -2385,7 +2377,7 @@ impl Connection { // Determine how we are sending packets (PTO, etc..). let profile = self.loss_recovery.send_profile(&path.borrow(), now); - qdebug!([self], "output_path send_profile {:?}", profile); + debug!("[{self}] output_path send_profile {:?}", profile); // Frames for different epochs must go in different packets, but then these // packets can go in a single datagram @@ -2515,16 +2507,15 @@ impl Connection { } if encoder.is_empty() { - qdebug!("TX blocked, profile={:?}", profile); + debug!("TX blocked, profile={:?}", profile); Ok(SendOption::No(profile.paced())) } else { // Perform additional padding for Initial packets as necessary. let mut packets: Vec = encoder.into(); if let Some(mut initial) = initial_sent.take() { if needs_padding { - qdebug!( - [self], - "pad Initial from {} to PLPMTU {}", + debug!( + "[{self}] pad Initial from {} to PLPMTU {}", packets.len(), profile.limit() ); @@ -2550,7 +2541,7 @@ impl Connection { let la = self .loss_recovery .largest_acknowledged_pn(PacketNumberSpace::ApplicationData); - qinfo!([self], "Initiating key update"); + info!("[{self}] Initiating key update"); self.crypto.states.initiate_key_update(la) } else { Err(Error::KeyUpdateBlocked) @@ -2564,7 +2555,7 @@ impl Connection { } fn client_start(&mut self, now: Instant) -> Res<()> { - qdebug!([self], "client_start"); + debug!("[{self}] client_start"); debug_assert_eq!(self.role, Role::Client); if let Some(path) = self.paths.primary() { qlog::client_connection_started(&self.qlog, &path, now); @@ -2578,7 +2569,7 @@ impl Connection { self.handshake(now, self.version, PacketNumberSpace::Initial, None)?; self.set_state(State::WaitInitial, now); self.zero_rtt_state = if self.crypto.enable_0rtt(self.version, self.role)? { - qdebug!([self], "Enabled 0-RTT"); + debug!("[{self}] Enabled 0-RTT"); ZeroRttState::Sending } else { ZeroRttState::Init @@ -2689,9 +2680,8 @@ impl Connection { .map(ConnectionId::as_cid_ref) != tp.map(ConnectionIdRef::from) { - qwarn!( - [self], - "ISCID test failed: self cid {:?} != tp cid {:?}", + warn!( + "[{self}] ISCID test failed: self cid {:?} != tp cid {:?}", self.remote_initial_source_cid, tp.map(hex), ); @@ -2706,9 +2696,8 @@ impl Connection { .map(ConnectionId::as_cid_ref) != tp.map(ConnectionIdRef::from) { - qwarn!( - [self], - "ODCID test failed: self cid {:?} != tp cid {:?}", + warn!( + "[{self}] ODCID test failed: self cid {:?} != tp cid {:?}", self.original_destination_cid, tp.map(hex), ); @@ -2725,9 +2714,8 @@ impl Connection { None }; if expected != tp.map(ConnectionIdRef::from) { - qwarn!( - [self], - "RSCID test failed. self cid {:?} != tp cid {:?}", + warn!( + "[{self}] RSCID test failed. self cid {:?} != tp cid {:?}", expected, tp.map(hex), ); @@ -2745,9 +2733,8 @@ impl Connection { // `current` and `other` are the value from the peer's transport parameters. // We're checking that these match our expectations. if let Some((current, other)) = remote_tps.get_versions() { - qtrace!( - [self], - "validate_versions: current={:x} chosen={:x} other={:x?}", + trace!( + "[{self}] validate_versions: current={:x} chosen={:x} other={:x?}", self.version.wire_version(), current, other, @@ -2759,7 +2746,7 @@ impl Connection { // was provided. Ok(()) } else if self.version().wire_version() != current { - qinfo!([self], "validate_versions: current version mismatch"); + info!("[{self}] validate_versions: current version mismatch"); Err(Error::VersionNegotiation) } else if self .conn_params @@ -2784,12 +2771,12 @@ impl Connection { { Ok(()) } else { - qinfo!([self], "validate_versions: failed"); + info!("[{self}] validate_versions: failed"); Err(Error::VersionNegotiation) } } } else if self.version != Version::Version1 && !self.version.is_draft() { - qinfo!([self], "validate_versions: missing extension"); + info!("[{self}] validate_versions: missing extension"); Err(Error::VersionNegotiation) } else { Ok(()) @@ -2798,7 +2785,7 @@ impl Connection { fn confirm_version(&mut self, v: Version) { if self.version != v { - qdebug!([self], "Compatible upgrade {:?} ==> {:?}", self.version, v); + debug!("[{self}] Compatible upgrade {:?} ==> {:?}", self.version, v); } self.crypto.confirm_version(v); self.version = v; @@ -2830,7 +2817,7 @@ impl Connection { space: PacketNumberSpace, data: Option<&[u8]>, ) -> Res<()> { - qtrace!([self], "Handshake space={} data={:0x?}", space, data); + trace!("[{self}] Handshake space={} data={:0x?}", space, data); let was_authentication_pending = *self.crypto.tls.state() == HandshakeState::AuthenticationPending; @@ -2851,7 +2838,7 @@ impl Connection { } } _ => { - qerror!("Crypto state should not be new or failed after successful handshake"); + error!("Crypto state should not be new or failed after successful handshake"); return Err(Error::CryptoError(neqo_crypto::Error::InternalError)); } } @@ -2901,7 +2888,7 @@ impl Connection { now: Instant, ) -> Res<()> { if !frame.is_allowed(packet_type) { - qinfo!("frame not allowed: {:?} {:?}", frame, packet_type); + info!("frame not allowed: {:?} {:?}", frame, packet_type); return Err(Error::ProtocolViolation); } let space = PacketNumberSpace::from(packet_type); @@ -2933,7 +2920,7 @@ impl Connection { // (If we ever start using non-contiguous packet numbers, we need to check all the // packet numbers in the ACKed ranges.) if largest_acknowledged >= next_pn { - qwarn!("Largest ACKed {} was never sent", largest_acknowledged); + warn!("Largest ACKed {} was never sent", largest_acknowledged); return Err(Error::AckedUnsentPacket); } @@ -2942,9 +2929,8 @@ impl Connection { self.handle_ack(space, ranges, ecn_count, ack_delay, now); } Frame::Crypto { offset, data } => { - qtrace!( - [self], - "Crypto frame on space={} offset={}, data={:0x?}", + trace!( + "[{self}] Crypto frame on space={} offset={}, data={:0x?}", space, offset, &data @@ -2954,7 +2940,7 @@ impl Connection { if self.crypto.streams.data_ready(space) { let mut buf = Vec::new(); let read = self.crypto.streams.read_to_end(space, &mut buf); - qdebug!("Read {:?} bytes", read); + debug!("Read {:?} bytes", read); self.handshake(now, packet_version, space, Some(&buf))?; self.create_resumption_token(now); } else { @@ -2987,7 +2973,7 @@ impl Connection { self.paths .retire_cids(retire_prior, &mut self.connection_ids); if self.connection_ids.len() >= LOCAL_ACTIVE_CID_LIMIT { - qinfo!([self], "received too many connection IDs"); + info!("[{self}] received too many connection IDs"); return Err(Error::ConnectionIdLimitExceeded); } } @@ -3018,12 +3004,9 @@ impl Connection { reason_phrase, } => { self.stats.borrow_mut().frame_rx.connection_close += 1; - qinfo!( - [self], - "ConnectionClose received. Error code: {:?} frame type {:x} reason {}", - error_code, - frame_type, - reason_phrase + info!( + "[{self}] ConnectionClose received. Error code: {:?} frame type {:x} reason {}", + error_code, frame_type, reason_phrase ); let (detail, frame_type) = if let CloseError::Application(_) = error_code { // Use a transport error here because we want to send @@ -3089,7 +3072,7 @@ impl Connection { fn handle_lost_packets(&mut self, lost_packets: &[SentPacket]) { for lost in lost_packets { for token in lost.tokens() { - qdebug!([self], "Lost: {:?}", token); + debug!("[{self}] Lost: {:?}", token); match token { RecoveryToken::Ack(ack_token) => { // If we lost an ACK frame during the handshake, send another one. @@ -3138,7 +3121,7 @@ impl Connection { R: IntoIterator> + Debug, R::IntoIter: ExactSizeIterator, { - qdebug!([self], "Rx ACK space={}, ranges={:?}", space, ack_ranges); + debug!("[{self}] Rx ACK space={}, ranges={:?}", space, ack_ranges); let Some(path) = self.paths.primary() else { return; @@ -3193,7 +3176,7 @@ impl Connection { if !matches!(self.zero_rtt_state, ZeroRttState::Sending) { return; } - qdebug!([self], "0-RTT rejected"); + debug!("[{self}] 0-RTT rejected"); self.resend_0rtt(now); self.streams.zero_rtt_rejected(); self.crypto.states.discard_0rtt_keys(); @@ -3201,9 +3184,9 @@ impl Connection { } fn set_connected(&mut self, now: Instant) -> Res<()> { - qdebug!([self], "TLS connection complete"); + debug!("[{self}] TLS connection complete"); if self.crypto.tls.info().map(SecretAgentInfo::alpn).is_none() { - qwarn!([self], "No ALPN. Closing connection."); + warn!("[{self}] No ALPN. Closing connection."); // 120 = no_application_protocol return Err(Error::CryptoAlert(120)); } @@ -3249,13 +3232,13 @@ impl Connection { self.state_signaling.handshake_done(); self.set_confirmed(now)?; } - qinfo!([self], "Connection established"); + info!("[{self}] Connection established"); Ok(()) } fn set_state(&mut self, state: State, now: Instant) { if state > self.state { - qdebug!([self], "State change from {:?} -> {:?}", self.state, state); + debug!("[{self}] State change from {:?} -> {:?}", self.state, state); self.state = state.clone(); if self.state.closed() { self.streams.clear_streams(); diff --git a/neqo-transport/src/connection/saved.rs b/neqo-transport/src/connection/saved.rs index d5e0313e52..39d95b13f6 100644 --- a/neqo-transport/src/connection/saved.rs +++ b/neqo-transport/src/connection/saved.rs @@ -6,7 +6,8 @@ use std::{mem, time::Instant}; -use neqo_common::{qdebug, qinfo, Datagram}; +use log::{debug, info}; +use neqo_common::Datagram; use crate::crypto::CryptoSpace; @@ -41,10 +42,10 @@ impl SavedDatagrams { let store = self.store(cspace); if store.len() < MAX_SAVED_DATAGRAMS { - qdebug!("saving datagram of {} bytes", d.len()); + debug!("saving datagram of {} bytes", d.len()); store.push(SavedDatagram { d, t }); } else { - qinfo!("not saving datagram of {} bytes", d.len()); + info!("not saving datagram of {} bytes", d.len()); } } diff --git a/neqo-transport/src/connection/tests/cc.rs b/neqo-transport/src/connection/tests/cc.rs index 09bcefb7a4..92ea4e7e8f 100644 --- a/neqo-transport/src/connection/tests/cc.rs +++ b/neqo-transport/src/connection/tests/cc.rs @@ -6,7 +6,8 @@ use std::{mem, time::Duration}; -use neqo_common::{qdebug, qinfo, Datagram, IpTosEcn}; +use log::{debug, info}; +use neqo_common::{Datagram, IpTosEcn}; use super::{ super::Output, ack_bytes, assert_full_cwnd, connect_rtt_idle, cwnd, cwnd_avail, cwnd_packets, @@ -239,7 +240,7 @@ fn cc_cong_avoidance_recovery_period_to_cong_avoidance() { // Should be in CARP now. now += DEFAULT_RTT / 2; - qinfo!("moving to congestion avoidance {}", cwnd(&client)); + info!("moving to congestion avoidance {}", cwnd(&client)); // Now make sure that we increase congestion window according to the // accurate byte counting version of congestion avoidance. @@ -249,10 +250,10 @@ fn cc_cong_avoidance_recovery_period_to_cong_avoidance() { let (mut c_tx_dgrams, next_now) = fill_cwnd(&mut client, stream_id, now); now = next_now; for i in 0..5 { - qinfo!("iteration {}", i); + info!("iteration {}", i); let c_tx_size: usize = c_tx_dgrams.iter().map(Datagram::len).sum(); - qinfo!( + info!( "client sending {} bytes into cwnd of {}", c_tx_size, cwnd(&client) @@ -398,7 +399,7 @@ fn ack_are_not_cc() { // The server hasn't received any of these packets yet, the server // won't ACK, but if it sends an ack-eliciting packet instead. - qdebug!([server], "Sending ack-eliciting"); + debug!("[{server}] Sending ack-eliciting"); let other_stream = server.stream_create(StreamType::BiDi).unwrap(); assert_eq!(other_stream, 1); server.stream_send(other_stream, b"dropped").unwrap(); @@ -412,10 +413,10 @@ fn ack_are_not_cc() { assert!(ack_eliciting_packet.is_some()); // The client can ack the server packet even if cc windows is full. - qdebug!([client], "Process ack-eliciting"); + debug!("[{client}] Process ack-eliciting"); let ack_pkt = client.process(ack_eliciting_packet, now).dgram(); assert!(ack_pkt.is_some()); - qdebug!([server], "Handle ACK"); + debug!("[{server}] Handle ACK"); let prev_ack_count = server.stats().frame_rx.ack; server.process_input(ack_pkt.unwrap(), now); assert_eq!(server.stats().frame_rx.ack, prev_ack_count + 1); diff --git a/neqo-transport/src/connection/tests/handshake.rs b/neqo-transport/src/connection/tests/handshake.rs index dcdbd9e276..c44724f0b6 100644 --- a/neqo-transport/src/connection/tests/handshake.rs +++ b/neqo-transport/src/connection/tests/handshake.rs @@ -12,7 +12,8 @@ use std::{ time::Duration, }; -use neqo_common::{event::Provider, qdebug, Datagram}; +use log::debug; +use neqo_common::{event::Provider, Datagram}; use neqo_crypto::{ constants::TLS_CHACHA20_POLY1305_SHA256, generate_ech_keys, AuthenticationStatus, }; @@ -45,19 +46,19 @@ const ECH_CONFIG_ID: u8 = 7; const ECH_PUBLIC_NAME: &str = "public.example"; fn full_handshake(pmtud: bool) { - qdebug!("---- client: generate CH"); + debug!("---- client: generate CH"); let mut client = new_client(ConnectionParameters::default().pmtud(pmtud)); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(out.as_dgram_ref().unwrap().len(), client.plpmtu()); - qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = new_server(ConnectionParameters::default().pmtud(pmtud)); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(out.as_dgram_ref().unwrap().len(), server.plpmtu()); - qdebug!("---- client: cert verification"); + debug!("---- client: cert verification"); let out = client.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); @@ -66,17 +67,17 @@ fn full_handshake(pmtud: bool) { assert!(maybe_authenticate(&mut client)); - qdebug!("---- client: SH..FIN -> FIN"); + debug!("---- client: SH..FIN -> FIN"); let out = client.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(*client.state(), State::Connected); - qdebug!("---- server: FIN -> ACKS"); + debug!("---- server: FIN -> ACKS"); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(*server.state(), State::Confirmed); - qdebug!("---- client: ACKS -> 0"); + debug!("---- client: ACKS -> 0"); let out = client.process(out.dgram(), now()); if pmtud { // PMTUD causes a PING probe to be sent here @@ -100,17 +101,17 @@ fn handshake_pmtud() { #[test] fn handshake_failed_authentication() { - qdebug!("---- client: generate CH"); + debug!("---- client: generate CH"); let mut client = default_client(); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); - qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); - qdebug!("---- client: cert verification"); + debug!("---- client: cert verification"); let out = client.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); @@ -119,14 +120,14 @@ fn handshake_failed_authentication() { let authentication_needed = |e| matches!(e, ConnectionEvent::AuthenticationNeeded); assert!(client.events().any(authentication_needed)); - qdebug!("---- client: Alert(certificate_revoked)"); + debug!("---- client: Alert(certificate_revoked)"); client.authenticated(AuthenticationStatus::CertRevoked, now()); - qdebug!("---- client: -> Alert(certificate_revoked)"); + debug!("---- client: -> Alert(certificate_revoked)"); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); - qdebug!("---- server: Alert(certificate_revoked)"); + debug!("---- server: Alert(certificate_revoked)"); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_error(&client, &CloseReason::Transport(Error::CryptoAlert(44))); @@ -157,42 +158,42 @@ fn no_alpn() { #[test] fn dup_server_flight1() { - qdebug!("---- client: generate CH"); + debug!("---- client: generate CH"); let mut client = default_client(); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(out.as_dgram_ref().unwrap().len(), client.plpmtu()); - qdebug!("Output={:0x?}", out.as_dgram_ref()); + debug!("Output={:0x?}", out.as_dgram_ref()); - qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let out_to_rep = server.process(out.dgram(), now()); assert!(out_to_rep.as_dgram_ref().is_some()); - qdebug!("Output={:0x?}", out_to_rep.as_dgram_ref()); + debug!("Output={:0x?}", out_to_rep.as_dgram_ref()); - qdebug!("---- client: cert verification"); + debug!("---- client: cert verification"); let out = client.process(Some(out_to_rep.as_dgram_ref().cloned().unwrap()), now()); assert!(out.as_dgram_ref().is_some()); - qdebug!("Output={:0x?}", out.as_dgram_ref()); + debug!("Output={:0x?}", out.as_dgram_ref()); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_none()); assert!(maybe_authenticate(&mut client)); - qdebug!("---- client: SH..FIN -> FIN"); + debug!("---- client: SH..FIN -> FIN"); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); - qdebug!("Output={:0x?}", out.as_dgram_ref()); + debug!("Output={:0x?}", out.as_dgram_ref()); assert_eq!(3, client.stats().packets_rx); assert_eq!(0, client.stats().dups_rx); assert_eq!(1, client.stats().dropped_rx); - qdebug!("---- Dup, ignored"); + debug!("---- Dup, ignored"); let out = client.process(out_to_rep.dgram(), now()); assert!(out.as_dgram_ref().is_none()); - qdebug!("Output={:0x?}", out.as_dgram_ref()); + debug!("Output={:0x?}", out.as_dgram_ref()); // Four packets total received, 1 of them is a dup and one has been dropped because Initial keys // are dropped. Add 2 counts of the padding that the server adds to Initial packets. diff --git a/neqo-transport/src/connection/tests/idle.rs b/neqo-transport/src/connection/tests/idle.rs index 024d0f9157..59d8888923 100644 --- a/neqo-transport/src/connection/tests/idle.rs +++ b/neqo-transport/src/connection/tests/idle.rs @@ -9,7 +9,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qtrace, Encoder}; +use log::{trace, warn}; +use neqo_common::Encoder; use test_fixture::{now, split_datagram}; use super::{ @@ -338,7 +339,7 @@ fn idle_caching() { // Now let the server Initial through, with the CRYPTO frame. let dgram = server.process_output(end).dgram(); let (initial, _) = split_datagram(&dgram.unwrap()); - neqo_common::qwarn!("client ingests initial, finally"); + warn!("client ingests initial, finally"); mem::drop(client.process(Some(initial), end)); maybe_authenticate(&mut client); let dgram = client.process_output(end).dgram(); @@ -359,7 +360,7 @@ fn create_stream_idle_rtt( ) -> (Instant, StreamId) { let check_idle = |endpoint: &mut Connection, now: Instant| { let delay = endpoint.process_output(now).callback(); - qtrace!([endpoint], "idle timeout {:?}", delay); + trace!("[{endpoint}] idle timeout {:?}", delay); if rtt < default_timeout() / 4 { assert_eq!(default_timeout(), delay); } else { @@ -640,7 +641,7 @@ fn keep_alive_large_rtt() { for endpoint in &mut [client, server] { endpoint.stream_keep_alive(stream, true).unwrap(); let delay = endpoint.process_output(now).callback(); - qtrace!([endpoint], "new delay {:?}", delay); + trace!("[{endpoint}] new delay {:?}", delay); assert!(delay > keep_alive_timeout()); assert!(delay > rtt); } diff --git a/neqo-transport/src/connection/tests/keys.rs b/neqo-transport/src/connection/tests/keys.rs index 59bbc2f24c..a4c71cfdf3 100644 --- a/neqo-transport/src/connection/tests/keys.rs +++ b/neqo-transport/src/connection/tests/keys.rs @@ -6,7 +6,8 @@ use std::mem; -use neqo_common::{qdebug, Datagram}; +use log::debug; +use neqo_common::Datagram; use test_fixture::now; use super::{ @@ -55,18 +56,18 @@ fn overwrite_invocations(n: PacketNumber) { #[test] fn discarded_initial_keys() { - qdebug!("---- client: generate CH"); + debug!("---- client: generate CH"); let mut client = default_client(); let init_pkt_c = client.process_output(now()).dgram(); assert!(init_pkt_c.is_some()); assert_eq!(init_pkt_c.as_ref().unwrap().len(), client.plpmtu()); - qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let init_pkt_s = server.process(init_pkt_c.clone(), now()).dgram(); assert!(init_pkt_s.is_some()); - qdebug!("---- client: cert verification"); + debug!("---- client: cert verification"); let out = client.process(init_pkt_s.clone(), now()).dgram(); assert!(out.is_some()); @@ -85,7 +86,7 @@ fn discarded_initial_keys() { // The dropped packet is padding. The Initial packet has been mark dup. check_discarded(&mut server, &init_pkt_c.clone().unwrap(), false, 1, 1); - qdebug!("---- client: SH..FIN -> FIN"); + debug!("---- client: SH..FIN -> FIN"); let out = client.process_output(now()).dgram(); assert!(out.is_some()); diff --git a/neqo-transport/src/connection/tests/migration.rs b/neqo-transport/src/connection/tests/migration.rs index 9e05c9d289..8d54bc47d3 100644 --- a/neqo-transport/src/connection/tests/migration.rs +++ b/neqo-transport/src/connection/tests/migration.rs @@ -12,7 +12,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qdebug, Datagram, Decoder}; +use log::debug; +use neqo_common::{Datagram, Decoder}; use test_fixture::{ assertions::{assert_v4_path, assert_v6_path}, fixture_init, new_neqo_qlog, now, DEFAULT_ADDR, DEFAULT_ADDR_V4, @@ -102,10 +103,10 @@ fn rebind( new_path: fn(&Datagram) -> Datagram, mut now: Instant, ) -> Instant { - qdebug!("Rebinding"); + debug!("Rebinding"); let c1 = send_something(client, now); let c1_new = new_path(&c1); - qdebug!("Rebinding to {}", c1_new.source()); + debug!("Rebinding to {}", c1_new.source()); // Server will reply to modified datagram with a PATH_CHALLENGE. // Due to the amplification limit, this will not be padded to MIN_INITIAL_PACKET_SIZE. @@ -230,7 +231,7 @@ fn rebind( now += server.process_output(now).callback(); } - qdebug!("Rebinding done"); + debug!("Rebinding done"); now } diff --git a/neqo-transport/src/connection/tests/mod.rs b/neqo-transport/src/connection/tests/mod.rs index e897b7082b..550583ab18 100644 --- a/neqo-transport/src/connection/tests/mod.rs +++ b/neqo-transport/src/connection/tests/mod.rs @@ -14,7 +14,8 @@ use std::{ }; use enum_map::enum_map; -use neqo_common::{event::Provider, qdebug, qtrace, Datagram, Decoder, Role}; +use log::{debug, trace}; +use neqo_common::{event::Provider, Datagram, Decoder, Role}; use neqo_crypto::{random, AllowZeroRtt, AuthenticationStatus, ResumptionToken}; use test_fixture::{fixture_init, new_neqo_qlog, now, DEFAULT_ADDR}; @@ -228,7 +229,7 @@ fn handshake_with_modifier( did_ping[a.role()] = true; } input = output.and_then(modifier); - qtrace!("handshake: t += {:?}", rtt / 2); + trace!("handshake: t += {:?}", rtt / 2); now += rtt / 2; mem::swap(&mut a, &mut b); } @@ -346,7 +347,7 @@ fn connect_rtt_idle_with_modifier( // Drain events from both as well. _ = client.events().count(); _ = server.events().count(); - qtrace!("----- connected and idle with RTT {:?}", rtt); + trace!("----- connected and idle with RTT {:?}", rtt); now } @@ -370,7 +371,7 @@ fn fill_stream(c: &mut Connection, stream: StreamId) { const BLOCK_SIZE: usize = 4_096; loop { let bytes_sent = c.stream_send(stream, &[0x42; BLOCK_SIZE]).unwrap(); - qtrace!("fill_cwnd wrote {} bytes", bytes_sent); + trace!("fill_cwnd wrote {} bytes", bytes_sent); if bytes_sent < BLOCK_SIZE { break; } @@ -384,13 +385,13 @@ fn fill_stream(c: &mut Connection, stream: StreamId) { /// pacing, this looks at the congestion window to tell when to stop. /// Returns a list of datagrams and the new time. fn fill_cwnd(c: &mut Connection, stream: StreamId, mut now: Instant) -> (Vec, Instant) { - qtrace!("fill_cwnd starting cwnd: {}", cwnd_avail(c)); + trace!("fill_cwnd starting cwnd: {}", cwnd_avail(c)); fill_stream(c, stream); let mut total_dgrams = Vec::new(); loop { let pkt = c.process_output(now); - qtrace!( + trace!( "fill_cwnd cwnd remaining={}, output: {:?}", cwnd_avail(c), pkt @@ -409,7 +410,7 @@ fn fill_cwnd(c: &mut Connection, stream: StreamId, mut now: Instant) -> (Vec() ); @@ -465,14 +466,14 @@ where let mut srv_buf = [0; 4_096]; let in_dgrams = in_dgrams.into_iter(); - qdebug!([dest], "ack_bytes {} datagrams", in_dgrams.len()); + debug!("[{dest}] ack_bytes {} datagrams", in_dgrams.len()); for dgram in in_dgrams { dest.process_input(dgram, now); } loop { let (bytes_read, _fin) = dest.stream_recv(stream, &mut srv_buf).unwrap(); - qtrace!([dest], "ack_bytes read {} bytes", bytes_read); + trace!("[{dest}] ack_bytes read {} bytes", bytes_read); if bytes_read == 0 { break; } @@ -502,13 +503,13 @@ fn induce_persistent_congestion( ) -> Instant { // Note: wait some arbitrary time that should be longer than pto // timer. This is rather brittle. - qtrace!([client], "induce_persistent_congestion"); + trace!("[{client}] induce_persistent_congestion"); now += AT_LEAST_PTO; let mut pto_counts = [0; MAX_PTO_COUNTS]; assert_eq!(client.stats.borrow().pto_counts, pto_counts); - qtrace!([client], "first PTO"); + trace!("[{client}] first PTO"); let (c_tx_dgrams, next_now) = fill_cwnd(client, stream, now); now = next_now; assert_eq!(c_tx_dgrams.len(), 2); // Two PTO packets @@ -516,7 +517,7 @@ fn induce_persistent_congestion( pto_counts[0] = 1; assert_eq!(client.stats.borrow().pto_counts, pto_counts); - qtrace!([client], "second PTO"); + trace!("[{client}] second PTO"); now += AT_LEAST_PTO * 2; let (c_tx_dgrams, next_now) = fill_cwnd(client, stream, now); now = next_now; @@ -526,7 +527,7 @@ fn induce_persistent_congestion( pto_counts[1] = 1; assert_eq!(client.stats.borrow().pto_counts, pto_counts); - qtrace!([client], "third PTO"); + trace!("[{client}] third PTO"); now += AT_LEAST_PTO * 4; let (c_tx_dgrams, next_now) = fill_cwnd(client, stream, now); now = next_now; @@ -591,7 +592,7 @@ fn send_something_paced_with_modifier( let stream_id = sender.stream_create(StreamType::UniDi).unwrap(); assert!(sender.stream_send(stream_id, DEFAULT_STREAM_DATA).is_ok()); assert!(sender.stream_close_send(stream_id).is_ok()); - qdebug!([sender], "send_something on {}", stream_id); + debug!("[{sender}] send_something on {}", stream_id); let dgram = match sender.process_output(now) { Output::Callback(t) => { assert!(allow_pacing, "send_something: unexpected delay"); diff --git a/neqo-transport/src/connection/tests/recovery.rs b/neqo-transport/src/connection/tests/recovery.rs index f3c319bdec..d7279e3bd1 100644 --- a/neqo-transport/src/connection/tests/recovery.rs +++ b/neqo-transport/src/connection/tests/recovery.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::qdebug; +use log::debug; use neqo_crypto::AuthenticationStatus; use test_fixture::{ assertions::{assert_handshake, assert_initial}, @@ -166,7 +166,7 @@ fn pto_initial() { const INITIAL_PTO: Duration = Duration::from_millis(300); let mut now = now(); - qdebug!("---- client: generate CH"); + debug!("---- client: generate CH"); let mut client = default_client(); let pkt1 = client.process_output(now).dgram(); assert!(pkt1.is_some()); @@ -240,7 +240,7 @@ fn pto_handshake_complete() { now += HALF_RTT; client.authenticated(AuthenticationStatus::Ok, now); - qdebug!("---- client: SH..FIN -> FIN"); + debug!("---- client: SH..FIN -> FIN"); let pkt1 = client.process_output(now).dgram(); assert_handshake(pkt1.as_ref().unwrap()); assert_eq!(*client.state(), State::Connected); @@ -253,7 +253,7 @@ fn pto_handshake_complete() { // Wait for PTO to expire and resend a handshake packet. // Wait long enough that the 1-RTT PTO also fires. - qdebug!("---- client: PTO"); + debug!("---- client: PTO"); now += HALF_RTT * 6; let pkt2 = client.process_output(now).dgram(); assert_handshake(pkt2.as_ref().unwrap()); @@ -280,7 +280,7 @@ fn pto_handshake_complete() { // We still have only a single PTO assert_eq!(client.stats.borrow().pto_counts, pto_counts); - qdebug!("---- server: receive FIN and send ACK"); + debug!("---- server: receive FIN and send ACK"); now += HALF_RTT; // Now let the server have pkt1 and expect an immediate Handshake ACK. // The output will be a Handshake packet with ACK and 1-RTT packet with @@ -332,17 +332,17 @@ fn pto_handshake_complete() { #[test] fn pto_handshake_frames() { let mut now = now(); - qdebug!("---- client: generate CH"); + debug!("---- client: generate CH"); let mut client = default_client(); let pkt = client.process_output(now); now += Duration::from_millis(10); - qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let pkt = server.process(pkt.dgram(), now); now += Duration::from_millis(10); - qdebug!("---- client: cert verification"); + debug!("---- client: cert verification"); let pkt = client.process(pkt.dgram(), now); now += Duration::from_millis(10); @@ -354,7 +354,7 @@ fn pto_handshake_frames() { let stream = client.stream_create(StreamType::UniDi).unwrap(); assert_eq!(stream, 2); assert_eq!(client.stream_send(stream, b"zero").unwrap(), 4); - qdebug!("---- client: SH..FIN -> FIN and 1RTT packet"); + debug!("---- client: SH..FIN -> FIN and 1RTT packet"); let pkt1 = client.process_output(now).dgram(); assert!(pkt1.is_some()); @@ -646,7 +646,7 @@ fn trickle(sender: &mut Connection, receiver: &mut Connection, mut count: usize, let id = sender.stream_create(StreamType::UniDi).unwrap(); let mut maybe_ack = None; while count > 0 { - qdebug!("trickle: remaining={}", count); + debug!("trickle: remaining={}", count); assert_eq!(sender.stream_send(id, &[9]).unwrap(), 1); let dgram = sender.process(maybe_ack, now).dgram(); diff --git a/neqo-transport/src/connection/tests/stream.rs b/neqo-transport/src/connection/tests/stream.rs index 89e1773dae..56865678fc 100644 --- a/neqo-transport/src/connection/tests/stream.rs +++ b/neqo-transport/src/connection/tests/stream.rs @@ -6,7 +6,8 @@ use std::{cmp::max, collections::HashMap, mem}; -use neqo_common::{event::Provider, qdebug}; +use log::debug; +use neqo_common::event::Provider; use test_fixture::now; use super::{ @@ -62,7 +63,7 @@ fn transfer() { let mut server = default_server(); connect_force_idle(&mut client, &mut server); - qdebug!("---- client sends"); + debug!("---- client sends"); // Send let client_stream_id = client.stream_create(StreamType::UniDi).unwrap(); client.stream_send(client_stream_id, &[6; 100]).unwrap(); @@ -84,12 +85,12 @@ fn transfer() { assert_eq!(datagrams.len(), 4); assert_eq!(*client.state(), State::Confirmed); - qdebug!("---- server receives"); + debug!("---- server receives"); for d in datagrams { let out = server.process(Some(d), now()); // With an RTT of zero, the server will acknowledge every packet immediately. assert!(out.as_dgram_ref().is_some()); - qdebug!("Output={:0x?}", out.as_dgram_ref()); + debug!("Output={:0x?}", out.as_dgram_ref()); } assert_eq!(*server.state(), State::Confirmed); @@ -122,7 +123,7 @@ fn sendorder_test(order_of_sendorder: &[Option]) { let mut server = default_server(); connect_force_idle(&mut client, &mut server); - qdebug!("---- client sends"); + debug!("---- client sends"); // open all streams and set the sendorders let mut ordered = Vec::new(); let mut streams = Vec::::new(); @@ -149,10 +150,10 @@ fn sendorder_test(order_of_sendorder: &[Option]) { } assert_eq!(*client.state(), State::Confirmed); - qdebug!("---- server receives"); + debug!("---- server receives"); for d in datagrams { let out = server.process(Some(d), now()); - qdebug!("Output={:0x?}", out.as_dgram_ref()); + debug!("Output={:0x?}", out.as_dgram_ref()); } assert_eq!(*server.state(), State::Confirmed); diff --git a/neqo-transport/src/connection/tests/zerortt.rs b/neqo-transport/src/connection/tests/zerortt.rs index 1370e3f659..aeb135b906 100644 --- a/neqo-transport/src/connection/tests/zerortt.rs +++ b/neqo-transport/src/connection/tests/zerortt.rs @@ -6,7 +6,8 @@ use std::{cell::RefCell, rc::Rc, time::Duration}; -use neqo_common::{event::Provider, qdebug}; +use log::debug; +use neqo_common::event::Provider; use neqo_crypto::{AllowZeroRtt, AntiReplay}; use test_fixture::{assertions, now}; @@ -291,7 +292,7 @@ fn zero_rtt_loss_accepted() { assertions::assert_coalesced_0rtt(&ci.as_dgram_ref().unwrap()[..]); // Drop CI/0-RTT a number of times - qdebug!("Drop CI/0-RTT {i} extra times"); + debug!("Drop CI/0-RTT {i} extra times"); for _ in 0..i { now += client.process_output(now).callback(); ci = client.process_output(now); diff --git a/neqo-transport/src/crypto.rs b/neqo-transport/src/crypto.rs index 756cdbb771..b282f7799f 100644 --- a/neqo-transport/src/crypto.rs +++ b/neqo-transport/src/crypto.rs @@ -14,7 +14,8 @@ use std::{ time::Instant, }; -use neqo_common::{hex, hex_snip_middle, qdebug, qinfo, qtrace, Encoder, Role}; +use log::{debug, info, trace}; +use neqo_common::{hex, hex_snip_middle, Encoder, Role}; use neqo_crypto::{ hkdf, hp::HpKey, Aead, Agent, AntiReplay, Cipher, Epoch, Error as CryptoError, HandshakeState, PrivateKey, PublicKey, Record, RecordList, ResumptionToken, SymKey, ZeroRttChecker, @@ -190,7 +191,7 @@ impl Crypto { data: Option<&[u8]>, ) -> Res<&HandshakeState> { let input = data.map(|d| { - qtrace!("Handshake record received {:0x?} ", d); + trace!("Handshake record received {:0x?} ", d); let epoch = match space { PacketNumberSpace::Initial => TLS_EPOCH_INITIAL, PacketNumberSpace::Handshake => TLS_EPOCH_HANDSHAKE, @@ -211,7 +212,7 @@ impl Crypto { } Err(CryptoError::EchRetry(v)) => Err(Error::EchRetry(v)), Err(e) => { - qinfo!("Handshake failed {:?}", e); + info!("Handshake failed {:?}", e); Err(self .tls .alert() @@ -265,7 +266,7 @@ impl Crypto { } fn install_handshake_keys(&mut self) -> Res { - qtrace!([self], "Attempt to install handshake keys"); + trace!("[{self}] Attempt to install handshake keys"); let Some(write_secret) = self.tls.write_secret(TLS_EPOCH_HANDSHAKE) else { // No keys is fine. return Ok(false); @@ -281,15 +282,15 @@ impl Crypto { .ok_or(Error::InternalError)?; self.states .set_handshake_keys(self.version, &write_secret, &read_secret, cipher)?; - qdebug!([self], "Handshake keys installed"); + debug!("[{self}] Handshake keys installed"); Ok(true) } fn maybe_install_application_write_key(&mut self, version: Version) -> Res<()> { - qtrace!([self], "Attempt to install application write key"); + trace!("[{self}] Attempt to install application write key"); if let Some(secret) = self.tls.write_secret(TLS_EPOCH_APPLICATION_DATA) { self.states.set_application_write_key(version, &secret)?; - qdebug!([self], "Application write key installed"); + debug!("[{self}] Application write key installed"); } Ok(()) } @@ -305,7 +306,7 @@ impl Crypto { .ok_or(Error::InternalError)?; self.states .set_application_read_key(version, &read_secret, expire_0rtt)?; - qdebug!([self], "application read keys installed"); + debug!("[{self}] application read keys installed"); Ok(()) } @@ -315,7 +316,7 @@ impl Crypto { if r.ct != TLS_CT_HANDSHAKE { return Err(Error::ProtocolViolation); } - qtrace!([self], "Adding CRYPTO data {:?}", r); + trace!("[{self}] Adding CRYPTO data {:?}", r); self.streams .send(PacketNumberSpace::from(r.epoch), &r.data)?; } @@ -333,21 +334,17 @@ impl Crypto { } pub fn acked(&mut self, token: &CryptoRecoveryToken) { - qdebug!( + debug!( "Acked crypto frame space={} offset={} length={}", - token.space, - token.offset, - token.length + token.space, token.offset, token.length ); self.streams.acked(token); } pub fn lost(&mut self, token: &CryptoRecoveryToken) { - qinfo!( + info!( "Lost crypto frame space={} offset={} length={}", - token.space, - token.offset, - token.length + token.space, token.offset, token.length ); self.streams.lost(token); } @@ -374,7 +371,7 @@ impl Crypto { ) -> Option { if let Agent::Client(ref mut c) = self.tls { c.resumption_token().as_ref().map(|t| { - qtrace!("TLS token {}", hex(t.as_ref())); + trace!("TLS token {}", hex(t.as_ref())); let mut enc = Encoder::default(); enc.encode_uint(4, version.wire_version()); enc.encode_varint(rtt); @@ -383,7 +380,7 @@ impl Crypto { }); enc.encode_vvec(new_token.unwrap_or(&[])); enc.encode(t.as_ref()); - qdebug!("resumption token {}", hex_snip_middle(enc.as_ref())); + debug!("resumption token {}", hex_snip_middle(enc.as_ref())); ResumptionToken::new(enc.into(), t.expiration_time()) }) } else { @@ -448,12 +445,9 @@ impl CryptoDxState { secret: &SymKey, cipher: Cipher, ) -> Res { - qdebug!( + debug!( "Making {:?} {} CryptoDxState, v={:?} cipher={}", - direction, - epoch, - version, - cipher, + direction, epoch, version, cipher, ); let hplabel = String::from(version.label_prefix()) + "hp"; Ok(Self { @@ -475,7 +469,7 @@ impl CryptoDxState { label: &str, dcid: &[u8], ) -> Res { - qtrace!("new_initial {:?} {}", version, ConnectionIdRef::from(dcid)); + trace!("new_initial {:?} {}", version, ConnectionIdRef::from(dcid)); let salt = version.initial_salt(); let cipher = TLS_AES_128_GCM_SHA256; let initial_secret = hkdf::extract( @@ -514,7 +508,7 @@ impl CryptoDxState { #[cfg(test)] OVERWRITE_INVOCATIONS.with(|v| { if let Some(i) = v.borrow_mut().take() { - neqo_common::qwarn!("Setting {:?} invocations to {}", self.direction, i); + log::warn!("Setting {:?} invocations to {}", self.direction, i); self.invocations = i; } }); @@ -581,12 +575,9 @@ impl CryptoDxState { self.used_pn = next..next; Ok(()) } else if prev.used_pn.end > self.used_pn.start { - qdebug!( - [self], - "Found packet with too new packet number {} > {}, compared to {}", - self.used_pn.start, - prev.used_pn.end, - prev, + debug!( + "[{self}] Found packet with too new packet number {} > {}, compared to {}", + self.used_pn.start, prev.used_pn.end, prev, ); Err(Error::PacketNumberOverlap) } else { @@ -600,11 +591,9 @@ impl CryptoDxState { /// old keys are received after a key update. That needs to be caught elsewhere. pub fn used(&mut self, pn: PacketNumber) -> Res<()> { if pn < self.min_pn { - qdebug!( - [self], - "Found packet with too old packet number: {} < {}", - pn, - self.min_pn + debug!( + "[{self}] Found packet with too old packet number: {} < {}", + pn, self.min_pn ); return Err(Error::PacketNumberOverlap); } @@ -633,7 +622,7 @@ impl CryptoDxState { pub fn compute_mask(&self, sample: &[u8]) -> Res<[u8; HpKey::SAMPLE_SIZE]> { let mask = self.hpkey.mask(sample)?; - qtrace!([self], "HP sample={} mask={}", hex(sample), hex(mask)); + trace!("[{self}] HP sample={} mask={}", hex(sample), hex(mask)); Ok(mask) } @@ -644,9 +633,8 @@ impl CryptoDxState { pub fn encrypt(&mut self, pn: PacketNumber, hdr: &[u8], body: &[u8]) -> Res> { debug_assert_eq!(self.direction, CryptoDxDirection::Write); - qtrace!( - [self], - "encrypt pn={} hdr={} body={}", + trace!( + "[{self}] encrypt pn={} hdr={} body={}", pn, hex(hdr), hex(body) @@ -667,7 +655,7 @@ impl CryptoDxState { let mut out = vec![0; size]; let res = self.aead.encrypt(pn, hdr, body, &mut out)?; - qtrace!([self], "encrypt ct={}", hex(res)); + trace!("[{self}] encrypt ct={}", hex(res)); debug_assert_eq!(pn, self.next_pn()); self.used(pn)?; Ok(res.to_vec()) @@ -680,9 +668,8 @@ impl CryptoDxState { pub fn decrypt(&mut self, pn: PacketNumber, hdr: &[u8], body: &[u8]) -> Res> { debug_assert_eq!(self.direction, CryptoDxDirection::Read); - qtrace!( - [self], - "decrypt pn={} hdr={} body={}", + trace!( + "[{self}] decrypt pn={} hdr={} body={}", pn, hex(hdr), hex(body) @@ -961,9 +948,8 @@ impl CryptoStates { }; for v in versions { - qdebug!( - [self], - "Creating initial cipher state v={:?}, role={:?} dcid={}", + debug!( + "[{self}] Creating initial cipher state v={:?}, role={:?} dcid={}", v, role, hex(dcid) @@ -974,9 +960,8 @@ impl CryptoStates { rx: CryptoDxState::new_initial(*v, CryptoDxDirection::Read, read, dcid)?, }; if let Some(prev) = self.initials.get(v) { - qinfo!( - [self], - "Continue packet numbers for initial after retry (write is {:?})", + info!( + "[{self}] Continue packet numbers for initial after retry (write is {:?})", prev.rx.used_pn, ); initial.tx.continuation(&prev.tx)?; @@ -1024,7 +1009,7 @@ impl CryptoStates { secret: &SymKey, cipher: Cipher, ) -> Res<()> { - qtrace!([self], "install 0-RTT keys"); + trace!("[{self}] install 0-RTT keys"); self.zero_rtt = Some(CryptoDxState::new( version, dir, @@ -1049,7 +1034,7 @@ impl CryptoStates { } pub fn discard_0rtt_keys(&mut self) { - qtrace!([self], "discard 0-RTT keys"); + trace!("[{self}] discard 0-RTT keys"); assert!( self.app_read.is_none(), "Can't discard 0-RTT after setting application keys" @@ -1131,11 +1116,11 @@ impl CryptoStates { if self.maybe_update_write()? { Ok(()) } else { - qdebug!([self], "Write keys already updated"); + debug!("[{self}] Write keys already updated"); Err(Error::KeyUpdateBlocked) } } else { - qdebug!([self], "Waiting for ACK or blocked on read key timer"); + debug!("[{self}] Waiting for ACK or blocked on read key timer"); Err(Error::KeyUpdateBlocked) } } @@ -1149,7 +1134,7 @@ impl CryptoStates { let write = &self.app_write.as_ref().ok_or(Error::InternalError)?; let read = &self.app_read.as_ref().ok_or(Error::InternalError)?; if write.epoch() == read.epoch() { - qdebug!([self], "Update write keys to epoch={}", write.epoch() + 1); + debug!("[{self}] Update write keys to epoch={}", write.epoch() + 1); self.app_write = Some(write.next()?); Ok(true) } else { @@ -1163,7 +1148,7 @@ impl CryptoStates { pub fn auto_update(&mut self) -> Res<()> { if let Some(app_write) = self.app_write.as_ref() { if app_write.dx.should_update() { - qinfo!([self], "Initiating automatic key update"); + info!("[{self}] Initiating automatic key update"); if !self.maybe_update_write()? { return Err(Error::KeysExhausted); } @@ -1183,7 +1168,7 @@ impl CryptoStates { /// we want to ensure that we can continue to receive any delayed /// packets that use the old keys. So we just set a timer. pub fn key_update_received(&mut self, expiration: Instant) -> Res<()> { - qtrace!([self], "Key update received"); + trace!("[{self}] Key update received"); // If we received a key update, then we assume that the peer has // acknowledged a packet we sent in this epoch. It's OK to do that // because they aren't allowed to update without first having received @@ -1213,10 +1198,10 @@ impl CryptoStates { // If enough time has passed, then install new keys and clear the timer. if now >= expiry { if self.has_0rtt_read() { - qtrace!([self], "Discarding 0-RTT keys"); + trace!("[{self}] Discarding 0-RTT keys"); self.zero_rtt = None; } else { - qtrace!([self], "Rotating read keys"); + trace!("[{self}] Rotating read keys"); mem::swap(&mut self.app_read, &mut self.app_read_next); self.app_read_next = Some(self.app_read.as_ref().ok_or(Error::InternalError)?.next()?); @@ -1241,7 +1226,7 @@ impl CryptoStates { pub fn check_pn_overlap(&mut self) -> Res<()> { // We only need to do the check while we are waiting for read keys to be updated. if self.read_update_time.is_some() { - qtrace!([self], "Checking for PN overlap"); + trace!("[{self}] Checking for PN overlap"); let next_dx = &mut self.app_read_next.as_mut().ok_or(Error::InternalError)?.dx; next_dx.continuation(&self.app_read.as_ref().ok_or(Error::InternalError)?.dx)?; } @@ -1541,7 +1526,7 @@ impl CryptoStreams { }; for (offset, length) in written.into_iter().flatten() { cs.tx.mark_as_sent(offset, length); - qdebug!("CRYPTO for {} offset={}, len={}", space, offset, length); + debug!("CRYPTO for {} offset={}, len={}", space, offset, length); tokens.push(RecoveryToken::Crypto(CryptoRecoveryToken { space, offset, diff --git a/neqo-transport/src/ecn.rs b/neqo-transport/src/ecn.rs index 944c63ac8a..6f475a356e 100644 --- a/neqo-transport/src/ecn.rs +++ b/neqo-transport/src/ecn.rs @@ -7,7 +7,8 @@ use std::ops::{AddAssign, Deref, DerefMut, Sub}; use enum_map::{Enum, EnumMap}; -use neqo_common::{qdebug, qinfo, qwarn, IpTosEcn}; +use log::{debug, info, warn}; +use neqo_common::IpTosEcn; use crate::{ packet::{PacketNumber, PacketType}, @@ -187,9 +188,9 @@ impl EcnInfo { pub fn on_packet_sent(&mut self, stats: &mut Stats) { if let EcnValidationState::Testing { probes_sent, .. } = &mut self.state { *probes_sent += 1; - qdebug!("ECN probing: sent {} probes", probes_sent); + debug!("ECN probing: sent {} probes", probes_sent); if *probes_sent == ECN_TEST_COUNT { - qdebug!("ECN probing concluded with {} probes sent", probes_sent); + debug!("ECN probing concluded with {} probes sent", probes_sent); self.state.set(EcnValidationState::Unknown, stats); } } @@ -230,7 +231,7 @@ impl EcnInfo { // If we have lost all initial probes a bunch of times, we can conclude that the path // is not ECN capable and likely drops all ECN marked packets. if probes_sent == probes_lost && *probes_lost == ECN_TEST_COUNT_INITIAL_PHASE { - qdebug!( + debug!( "ECN validation failed, all {} initial marked packets were lost", probes_lost ); @@ -276,7 +277,7 @@ impl EcnInfo { // > either the ECT(0) or ECT(1) codepoint set, ECN validation fails if the // > corresponding ECN counts are not present in the ACK frame. let Some(ack_ecn) = ack_ecn else { - qwarn!("ECN validation failed, no ECN counts in ACK frame"); + warn!("ECN validation failed, no ECN counts in ACK frame"); self.disable_ecn(stats, EcnValidationError::Bleaching); return; }; @@ -293,24 +294,24 @@ impl EcnInfo { .try_into() .unwrap(); if newly_acked_sent_with_ect0 == 0 { - qwarn!("ECN validation failed, no ECT(0) packets were newly acked"); + warn!("ECN validation failed, no ECT(0) packets were newly acked"); self.disable_ecn(stats, EcnValidationError::Bleaching); return; } let ecn_diff = ack_ecn - self.baseline; let sum_inc = ecn_diff[IpTosEcn::Ect0] + ecn_diff[IpTosEcn::Ce]; if sum_inc < newly_acked_sent_with_ect0 { - qwarn!( + warn!( "ECN validation failed, ACK counted {} new marks, but {} of newly acked packets were sent with ECT(0)", sum_inc, newly_acked_sent_with_ect0 ); self.disable_ecn(stats, EcnValidationError::Bleaching); } else if ecn_diff[IpTosEcn::Ect1] > 0 { - qwarn!("ECN validation failed, ACK counted ECT(1) marks that were never sent"); + warn!("ECN validation failed, ACK counted ECT(1) marks that were never sent"); self.disable_ecn(stats, EcnValidationError::ReceivedUnsentECT1); } else if self.state != EcnValidationState::Capable { - qinfo!("ECN validation succeeded, path is capable"); + info!("ECN validation succeeded, path is capable"); self.state.set(EcnValidationState::Capable, stats); } self.baseline = ack_ecn; diff --git a/neqo-transport/src/fc.rs b/neqo-transport/src/fc.rs index acc4d6582d..e8deec33eb 100644 --- a/neqo-transport/src/fc.rs +++ b/neqo-transport/src/fc.rs @@ -12,7 +12,8 @@ use std::{ ops::{Deref, DerefMut, Index, IndexMut}, }; -use neqo_common::{qtrace, Role}; +use log::trace; +use neqo_common::Role; use crate::{ frame::{ @@ -325,7 +326,7 @@ impl ReceiverFlowControl<()> { pub fn consume(&mut self, count: u64) -> Res<()> { if self.consumed + count > self.max_allowed { - qtrace!( + trace!( "Session RX window exceeded: consumed:{} new:{} limit:{}", self.consumed, count, @@ -383,7 +384,7 @@ impl ReceiverFlowControl { } if consumed > self.max_allowed { - qtrace!("Stream RX window exceeded: {}", consumed); + trace!("Stream RX window exceeded: {}", consumed); return Err(Error::FlowControlError); } let new_consumed = consumed - self.consumed; diff --git a/neqo-transport/src/frame.rs b/neqo-transport/src/frame.rs index c858c41b5c..1ebe078244 100644 --- a/neqo-transport/src/frame.rs +++ b/neqo-transport/src/frame.rs @@ -8,7 +8,8 @@ use std::ops::RangeInclusive; -use neqo_common::{qtrace, Decoder, Encoder}; +use log::trace; +use neqo_common::{Decoder, Encoder}; use crate::{ cid::MAX_CONNECTION_ID_LEN, @@ -529,10 +530,10 @@ impl<'a> Frame<'a> { }; let fill = (t & STREAM_FRAME_BIT_LEN) == 0; let data = if fill { - qtrace!("STREAM frame, extends to the end of the packet"); + trace!("STREAM frame, extends to the end of the packet"); dec.decode_remainder() } else { - qtrace!("STREAM frame, with length"); + trace!("STREAM frame, with length"); d(dec.decode_vvec())? }; if o + u64::try_from(data.len())? > ((1 << 62) - 1) { @@ -646,10 +647,10 @@ impl<'a> Frame<'a> { FRAME_TYPE_DATAGRAM | FRAME_TYPE_DATAGRAM_WITH_LEN => { let fill = (t & DATAGRAM_FRAME_BIT_LEN) == 0; let data = if fill { - qtrace!("DATAGRAM frame, extends to the end of the packet"); + trace!("DATAGRAM frame, extends to the end of the packet"); dec.decode_remainder() } else { - qtrace!("DATAGRAM frame, with length"); + trace!("DATAGRAM frame, with length"); d(dec.decode_vvec())? }; Ok(Self::Datagram { data, fill }) diff --git a/neqo-transport/src/lib.rs b/neqo-transport/src/lib.rs index 869ef7a4d1..897d1346c9 100644 --- a/neqo-transport/src/lib.rs +++ b/neqo-transport/src/lib.rs @@ -6,7 +6,7 @@ #![allow(clippy::module_name_repetitions)] // This lint doesn't work here. -use neqo_common::qwarn; +use log::warn; use neqo_crypto::Error as CryptoError; mod ackrate; @@ -179,7 +179,7 @@ impl Error { impl From for Error { fn from(err: CryptoError) -> Self { - qwarn!("Crypto operation failed {:?}", err); + warn!("Crypto operation failed {:?}", err); match err { CryptoError::EchRetry(config) => Self::EchRetry(config), _ => Self::CryptoError(err), diff --git a/neqo-transport/src/pace.rs b/neqo-transport/src/pace.rs index 642a656da2..eb8991e2e2 100644 --- a/neqo-transport/src/pace.rs +++ b/neqo-transport/src/pace.rs @@ -12,7 +12,7 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::qtrace; +use log::trace; use crate::rtt::GRANULARITY; @@ -76,7 +76,7 @@ impl Pacer { /// the current time is). pub fn next(&self, rtt: Duration, cwnd: usize) -> Instant { if self.c >= self.p { - qtrace!([self], "next {cwnd}/{rtt:?} no wait = {:?}", self.t); + trace!("[{self}] next {cwnd}/{rtt:?} no wait = {:?}", self.t); return self.t; } @@ -89,12 +89,12 @@ impl Pacer { // If the increment is below the timer granularity, send immediately. if w < GRANULARITY { - qtrace!([self], "next {cwnd}/{rtt:?} below granularity ({w:?})",); + trace!("[{self}] next {cwnd}/{rtt:?} below granularity ({w:?})",); return self.t; } let nxt = self.t + w; - qtrace!([self], "next {cwnd}/{rtt:?} wait {w:?} = {nxt:?}"); + trace!("[{self}] next {cwnd}/{rtt:?} wait {w:?} = {nxt:?}"); nxt } @@ -108,7 +108,7 @@ impl Pacer { return; } - qtrace!([self], "spend {} over {}, {:?}", count, cwnd, rtt); + trace!("[{self}] spend {} over {}, {:?}", count, cwnd, rtt); // Increase the capacity by: // `(now - self.t) * PACER_SPEEDUP * cwnd / rtt` // That is, the elapsed fraction of the RTT times rate that data is added. diff --git a/neqo-transport/src/packet/mod.rs b/neqo-transport/src/packet/mod.rs index f52f87978d..707d4b04a3 100644 --- a/neqo-transport/src/packet/mod.rs +++ b/neqo-transport/src/packet/mod.rs @@ -12,7 +12,8 @@ use std::{ time::Instant, }; -use neqo_common::{hex, hex_with_len, qtrace, qwarn, Decoder, Encoder}; +use log::{trace, warn}; +use neqo_common::{hex, hex_with_len, Decoder, Encoder}; use neqo_crypto::random; use crate::{ @@ -397,7 +398,7 @@ impl PacketBuilder { /// This will return an error if the packet is too large. pub fn build(mut self, crypto: &mut CryptoDxState) -> Res { if self.len() > self.limit { - qwarn!("Packet contents are more than the limit"); + warn!("Packet contents are more than the limit"); debug_assert!(false); return Err(Error::InternalError); } @@ -409,7 +410,7 @@ impl PacketBuilder { let hdr = &self.encoder.as_ref()[self.header.clone()]; let body = &self.encoder.as_ref()[self.header.end..]; - qtrace!( + trace!( "Packet build pn={} hdr={} body={}", self.pn, hex(hdr), @@ -434,7 +435,7 @@ impl PacketBuilder { // Finally, cut off the plaintext and add back the ciphertext. self.encoder.truncate(self.header.end); self.encoder.encode(&ciphertext); - qtrace!("Packet built {}", hex(&self.encoder)); + trace!("Packet built {}", hex(&self.encoder)); Ok(self.encoder) } @@ -798,7 +799,7 @@ impl<'a> PublicPacket<'a> { .data .get(sample_offset..(sample_offset + SAMPLE_SIZE)) .map_or(Err(Error::NoMoreData), |sample| { - qtrace!("unmask hdr={}", hex(&self.data[..sample_offset])); + trace!("unmask hdr={}", hex(&self.data[..sample_offset])); crypto.compute_mask(sample) })?; @@ -827,7 +828,7 @@ impl<'a> PublicPacket<'a> { hdrbytes.truncate(self.header_len + pn_len); pn_encoded >>= 8 * (MAX_PACKET_NUMBER_LEN - pn_len); - qtrace!("unmasked hdr={}", hex(&hdrbytes)); + trace!("unmasked hdr={}", hex(&hdrbytes)); let key_phase = self.packet_type == PacketType::Short && (first_byte & PACKET_BIT_KEY_PHASE) == PACKET_BIT_KEY_PHASE; @@ -856,7 +857,7 @@ impl<'a> PublicPacket<'a> { // fail is if the cryptographic module is bad or the packet is // too small (which is public information). let (key_phase, pn, header, body) = self.decrypt_header(rx)?; - qtrace!([rx], "decoded header: {:?}", header); + trace!("[{rx}] decoded header: {:?}", header); let Some(rx) = crypto.rx(version, cspace, key_phase) else { return Err(Error::DecryptError); }; @@ -877,7 +878,7 @@ impl<'a> PublicPacket<'a> { } else if crypto.rx_pending(cspace) { Err(Error::KeysPending(cspace)) } else { - qtrace!("keys for {:?} already discarded", cspace); + trace!("keys for {:?} already discarded", cspace); Err(Error::KeysDiscarded(cspace)) } } diff --git a/neqo-transport/src/packet/retry.rs b/neqo-transport/src/packet/retry.rs index 1ef8a3cbfd..3260916677 100644 --- a/neqo-transport/src/packet/retry.rs +++ b/neqo-transport/src/packet/retry.rs @@ -6,7 +6,7 @@ use std::cell::RefCell; -use neqo_common::qerror; +use log::error; use neqo_crypto::{hkdf, Aead, TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}; use crate::{version::Version, Error, Res}; @@ -43,7 +43,7 @@ where } .try_with(|aead| f(&aead.borrow())) .map_err(|e| { - qerror!("Unable to access Retry AEAD: {:?}", e); + error!("Unable to access Retry AEAD: {:?}", e); Error::InternalError })? } diff --git a/neqo-transport/src/path.rs b/neqo-transport/src/path.rs index 7ab36d8f3b..9454da935d 100644 --- a/neqo-transport/src/path.rs +++ b/neqo-transport/src/path.rs @@ -15,7 +15,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{hex, qdebug, qinfo, qlog::NeqoQlog, qtrace, Datagram, Encoder, IpTos, IpTosEcn}; +use log::{debug, info, trace}; +use neqo_common::{hex, qlog::NeqoQlog, Datagram, Encoder, IpTos, IpTosEcn}; use neqo_crypto::random; use crate::{ @@ -113,7 +114,7 @@ impl Paths { if let Some(cid) = &retired.borrow().remote_cid { let seqno = cid.sequence_number(); if cid.connection_id().is_empty() { - qdebug!("Connection ID {seqno} is zero-length, not retiring"); + debug!("Connection ID {seqno} is zero-length, not retiring"); } else { to_retire.push(seqno); } @@ -142,16 +143,16 @@ impl Paths { .as_ref() .is_some_and(|target| Rc::ptr_eq(target, &removed)) { - qinfo!( - [path.borrow()], - "The migration target path had to be removed" + info!( + "[{}] The migration target path had to be removed", + path.borrow() ); self.migration_target = None; } debug_assert_eq!(Rc::strong_count(&removed), 1); } - qdebug!([path.borrow()], "Make permanent"); + debug!("[{}] Make permanent", path.borrow()); path.borrow_mut().make_permanent(local_cid, remote_cid); self.paths.push(Rc::clone(path)); if self.primary.is_none() { @@ -164,7 +165,7 @@ impl Paths { /// to a migration from a peer, in which case the old path needs to be probed. #[must_use] fn select_primary(&mut self, path: &PathRef, now: Instant) -> Option { - qdebug!([path.borrow()], "set as primary path"); + debug!("[{}] set as primary path", path.borrow()); let old_path = self.primary.replace(Rc::clone(path)).inspect(|old| { old.borrow_mut().set_primary(false, now); }); @@ -223,7 +224,7 @@ impl Paths { if p.borrow_mut().process_timeout(now, pto, stats) { true } else { - qdebug!([p.borrow()], "Retiring path"); + debug!("[{}] Retiring path", p.borrow()); if p.borrow().is_primary() { primary_failed = true; } @@ -244,7 +245,7 @@ impl Paths { { // Need a clone as `fallback` is borrowed from `self`. let path = Rc::clone(fallback); - qinfo!([path.borrow()], "Failing over after primary path failed"); + info!("[{}] Failing over after primary path failed", path.borrow()); mem::drop(self.select_primary(&path, now)); true } else { @@ -363,9 +364,9 @@ impl Paths { .as_ref() .is_some_and(|target| Rc::ptr_eq(target, p)) { - qinfo!( - [path], - "NEW_CONNECTION_ID with Retire Prior To forced migration to fail" + info!( + "[{}] NEW_CONNECTION_ID with Retire Prior To forced migration to fail", + path ); *migration_target = None; } @@ -595,7 +596,7 @@ impl Path { /// Set whether this path is primary. pub(crate) fn set_primary(&mut self, primary: bool, now: Instant) { - qtrace!([self], "Make primary {}", primary); + trace!("[{self}] Make primary {}", primary); debug_assert!(self.remote_cid.is_some()); self.primary = primary; if !primary { @@ -606,7 +607,7 @@ impl Path { /// Set the current path as valid. This updates the time that the path was /// last validated and cancels any path validation. pub fn set_valid(&mut self, now: Instant) { - qdebug!([self], "Path validated {:?}", now); + debug!("[{self}] Path validated {:?}", now); self.state = ProbeState::Valid; self.validated = Some(now); } @@ -700,7 +701,7 @@ impl Path { let need_full_probe = !*mtu; self.set_valid(now); if need_full_probe { - qdebug!([self], "Sub-MTU probe successful, reset probe count"); + debug!("[{self}] Sub-MTU probe successful, reset probe count"); self.probe(stats); } true @@ -729,19 +730,16 @@ impl Path { self.state = if probe_count >= MAX_PATH_PROBES { if self.ecn_info.ecn_mark() == IpTosEcn::Ect0 { // The path validation failure may be due to ECN blackholing, try again without ECN. - qinfo!( - [self], - "Possible ECN blackhole, disabling ECN and re-probing path" - ); + info!("[{self}] Possible ECN blackhole, disabling ECN and re-probing path"); self.ecn_info .disable_ecn(stats, crate::ecn::EcnValidationError::BlackHole); ProbeState::ProbeNeeded { probe_count: 0 } } else { - qinfo!([self], "Probing failed"); + info!("[{self}] Probing failed"); ProbeState::Failed } } else { - qdebug!([self], "Initiating probe"); + debug!("[{self}] Initiating probe"); ProbeState::ProbeNeeded { probe_count } }; } @@ -763,7 +761,7 @@ impl Path { } // Send PATH_RESPONSE. let resp_sent = if let Some(challenge) = self.challenge.take() { - qtrace!([self], "Responding to path challenge {}", hex(challenge)); + trace!("[{self}] Responding to path challenge {}", hex(challenge)); builder.encode_varint(FRAME_TYPE_PATH_RESPONSE); builder.encode(&challenge[..]); @@ -780,7 +778,7 @@ impl Path { // Send PATH_CHALLENGE. if let ProbeState::ProbeNeeded { probe_count } = self.state { - qtrace!([self], "Initiating path challenge {}", probe_count); + trace!("[{self}] Initiating path challenge {}", probe_count); let data = random::<8>(); builder.encode_varint(FRAME_TYPE_PATH_CHALLENGE); builder.encode(&data); @@ -931,9 +929,8 @@ impl Path { // that there is some RTT information, which is better than nothing. // Two cases: 1. at the client when handling a Retry and // 2. at the server when disposing the Initial packet number space. - qinfo!( - [self], - "discarding a packet without an RTT estimate; guessing RTT={:?}", + info!( + "[{self}] discarding a packet without an RTT estimate; guessing RTT={:?}", now - sent.time_sent() ); stats.rtt_init_guess = true; diff --git a/neqo-transport/src/pmtud.rs b/neqo-transport/src/pmtud.rs index 880ef70dfc..f82a9ea3af 100644 --- a/neqo-transport/src/pmtud.rs +++ b/neqo-transport/src/pmtud.rs @@ -10,7 +10,7 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qdebug, qinfo}; +use log::{debug, info}; use static_assertions::const_assert; use crate::{frame::FRAME_TYPE_PING, packet::PacketBuilder, recovery::SentPacket, Stats}; @@ -89,7 +89,7 @@ impl Pmtud { /// Checks whether the PMTUD raise timer should be fired, and does so if needed. pub fn maybe_fire_raise_timer(&mut self, now: Instant) { if self.probe_state == Probe::NotNeeded && self.raise_timer.is_some_and(|t| now >= t) { - qdebug!("PMTUD raise timer fired"); + debug!("PMTUD raise timer fired"); self.raise_timer = None; self.start(); } @@ -129,10 +129,9 @@ impl Pmtud { stats.pmtud_tx += 1; self.probe_count += 1; self.probe_state = Probe::Sent; - qdebug!( + debug!( "Sending PMTUD probe of size {}, count {}", - self.search_table[self.probe_index], - self.probe_count + self.search_table[self.probe_index], self.probe_count ); } @@ -186,7 +185,7 @@ impl Pmtud { // total number of successful probes. stats.pmtud_ack += acked; self.mtu = self.search_table[self.probe_index]; - qdebug!("PMTUD probe of size {} succeeded", self.mtu); + debug!("PMTUD probe of size {} succeeded", self.mtu); self.start(); } @@ -198,7 +197,7 @@ impl Pmtud { self.probe_count = 0; // Reset the count self.loss_counts.fill(0); // Reset the loss counts self.raise_timer = Some(now + PMTU_RAISE_TIMER); - qinfo!( + info!( "PMTUD stopped, PLPMTU is now {}, raise timer {:?}", self.mtu, self.raise_timer.unwrap() @@ -270,10 +269,9 @@ impl Pmtud { }; let last_ok = first_failed - 1; - qdebug!( + debug!( "Packet of size > {} lost >= {} times", - self.search_table[last_ok], - MAX_PROBES + self.search_table[last_ok], MAX_PROBES ); if self.probe_state == Probe::NotNeeded { // We saw multiple losses of packets <= the current MTU outside of PMTU discovery, @@ -297,7 +295,7 @@ impl Pmtud { self.loss_counts.fill(0); self.raise_timer = None; stats.pmtud_change += 1; - qdebug!("PMTUD restarted, PLPMTU is now {}", self.mtu); + debug!("PMTUD restarted, PLPMTU is now {}", self.mtu); self.start(); } @@ -307,7 +305,7 @@ impl Pmtud { self.probe_state = Probe::Needed; // We need to send a probe self.probe_count = 0; // For the first time self.probe_index += 1; // At this size - qdebug!( + debug!( "PMTUD started with probe size {}", self.search_table[self.probe_index], ); @@ -333,7 +331,8 @@ mod tests { time::Instant, }; - use neqo_common::{qdebug, Encoder, IpTosEcn}; + use log::debug; + use neqo_common::{Encoder, IpTosEcn}; use test_fixture::{fixture_init, now}; use crate::{ @@ -458,7 +457,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - qdebug!("Reducing MTU to {}", smaller_mtu); + debug!("Reducing MTU to {}", smaller_mtu); // Drop packets > smaller_mtu until we need a probe again. while !pmtud.needs_probe() { let pn = prot.next_pn(); @@ -511,7 +510,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - qdebug!("Increasing MTU to {}", larger_mtu); + debug!("Increasing MTU to {}", larger_mtu); let now = now + PMTU_RAISE_TIMER; pmtud.maybe_fire_raise_timer(now); while pmtud.needs_probe() { diff --git a/neqo-transport/src/qlog.rs b/neqo-transport/src/qlog.rs index 07a7db1846..ffd266fe6d 100644 --- a/neqo-transport/src/qlog.rs +++ b/neqo-transport/src/qlog.rs @@ -11,7 +11,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{hex, qinfo, qlog::NeqoQlog, Decoder, IpTosEcn}; +use log::info; +use neqo_common::{hex, qlog::NeqoQlog, Decoder, IpTosEcn}; use qlog::events::{ connectivity::{ConnectionStarted, ConnectionState, ConnectionStateUpdated}, quic::{ @@ -231,7 +232,7 @@ pub fn packet_sent( if let Ok(f) = Frame::decode(&mut d) { frames.push(QuicFrame::from(f)); } else { - qinfo!("qlog: invalid frame"); + info!("qlog: invalid frame"); break; } } @@ -325,7 +326,7 @@ pub fn packet_received( if let Ok(f) = Frame::decode(&mut d) { frames.push(QuicFrame::from(f)); } else { - qinfo!("qlog: invalid frame"); + info!("qlog: invalid frame"); break; } } diff --git a/neqo-transport/src/recovery/mod.rs b/neqo-transport/src/recovery/mod.rs index 8f89b1cfcd..0ed45172d1 100644 --- a/neqo-transport/src/recovery/mod.rs +++ b/neqo-transport/src/recovery/mod.rs @@ -20,7 +20,8 @@ use std::{ }; use enum_map::{enum_map, EnumMap}; -use neqo_common::{qdebug, qinfo, qlog::NeqoQlog, qtrace, qwarn}; +use log::{debug, info, trace, warn}; +use neqo_common::qlog::NeqoQlog; pub use sent::SentPacket; use sent::SentPackets; pub use token::{RecoveryToken, StreamRecoveryToken}; @@ -182,7 +183,7 @@ impl LossRecoverySpace { .iter_mut() .filter_map(|sent| { if sent.pto() { - qtrace!("PTO: marking packet {} lost ", sent.pn()); + trace!("PTO: marking packet {} lost ", sent.pn()); Some(&*sent) } else { None @@ -250,7 +251,7 @@ impl LossRecoverySpace { debug_assert!(self.in_flight_outstanding >= count); self.in_flight_outstanding -= count; if self.in_flight_outstanding == 0 { - qtrace!("remove_packet outstanding == 0 for space {}", self.space); + trace!("remove_packet outstanding == 0 for space {}", self.space); } } @@ -322,7 +323,7 @@ impl LossRecoverySpace { // Housekeeping. self.remove_old_lost(now, cleanup_delay); - qtrace!( + trace!( "detect lost {}: now={:?} delay={:?}", self.space, now, @@ -340,14 +341,14 @@ impl LossRecoverySpace { { // Packets sent before now - loss_delay are deemed lost. if packet.time_sent() + loss_delay <= now { - qtrace!( + trace!( "lost={}, time sent {:?} is before lost_delay {:?}", packet.pn(), packet.time_sent(), loss_delay ); } else if largest_acked >= Some(packet.pn() + PACKET_THRESHOLD) { - qtrace!( + trace!( "lost={}, is >= {} from largest acked {:?}", packet.pn(), PACKET_THRESHOLD, @@ -551,14 +552,13 @@ impl LossRecovery { pub fn on_packet_sent(&mut self, path: &PathRef, mut sent_packet: SentPacket, now: Instant) { let pn_space = PacketNumberSpace::from(sent_packet.packet_type()); - qtrace!([self], "packet {}-{} sent", pn_space, sent_packet.pn()); + trace!("[{self}] packet {}-{} sent", pn_space, sent_packet.pn()); if let Some(space) = self.spaces.get_mut(pn_space) { path.borrow_mut().packet_sent(&mut sent_packet, now); space.on_packet_sent(sent_packet); } else { - qwarn!( - [self], - "ignoring {}-{} from dropped space", + warn!( + "[{self}] ignoring {}-{} from dropped space", pn_space, sent_packet.pn() ); @@ -617,7 +617,7 @@ impl LossRecovery { R::IntoIter: ExactSizeIterator, { let Some(space) = self.spaces.get_mut(pn_space) else { - qinfo!("ACK on discarded space"); + info!("ACK on discarded space"); return (Vec::new(), Vec::new()); }; @@ -646,9 +646,8 @@ impl LossRecovery { } } - qdebug!( - [self], - "ACK for {} - largest_acked={}", + debug!( + "[{self}] ACK for {} - largest_acked={}", pn_space, largest_acked_pkt.pn() ); @@ -736,7 +735,7 @@ impl LossRecovery { /// Discard state for a given packet number space. pub fn discard(&mut self, primary_path: &PathRef, space: PacketNumberSpace, now: Instant) { - qdebug!([self], "Reset loss recovery state for {}", space); + debug!("[{self}] Reset loss recovery state for {}", space); let mut path = primary_path.borrow_mut(); for p in self.spaces.drop_space(space) { path.discard_packet(&p, now, &mut self.stats.borrow_mut()); @@ -763,9 +762,8 @@ impl LossRecovery { } else { None }; - qtrace!( - [self], - "next_timeout loss={:?} pto={:?}", + trace!( + "[{self}] next_timeout loss={:?} pto={:?}", loss_time, pto_time ); @@ -872,7 +870,7 @@ impl LossRecovery { if let Some(t) = self.pto_time(rtt, *pn_space) { allow_probes[*pn_space] = true; if t <= now { - qdebug!([self], "PTO timer fired for {}", pn_space); + debug!("[{self}] PTO timer fired for {}", pn_space); let space = self.spaces.get_mut(*pn_space).unwrap(); lost.extend( space @@ -888,13 +886,13 @@ impl LossRecovery { // This has to happen outside the loop. Increasing the PTO count here causes the // pto_time to increase which might cause PTO for later packet number spaces to not fire. if let Some(pn_space) = pto_space { - qtrace!([self], "PTO {}, probing {:?}", pn_space, allow_probes); + trace!("[{self}] PTO {}, probing {:?}", pn_space, allow_probes); self.fire_pto(pn_space, allow_probes, now); } } pub fn timeout(&mut self, primary_path: &PathRef, now: Instant) -> Vec { - qtrace!([self], "timeout {:?}", now); + trace!("[{self}] timeout {:?}", now); let loss_delay = primary_path.borrow().rtt().loss_delay(); let confirmed = self.confirmed(); @@ -928,7 +926,7 @@ impl LossRecovery { /// what the current congestion window is, and what the pacer says. #[allow(clippy::option_if_let_else)] pub fn send_profile(&mut self, path: &Path, now: Instant) -> SendProfile { - qtrace!([self], "get send profile {:?}", now); + trace!("[{self}] get send profile {:?}", now); let sender = path.sender(); let mtu = path.plpmtu(); if let Some(profile) = self diff --git a/neqo-transport/src/recv_stream.rs b/neqo-transport/src/recv_stream.rs index 7d564abfff..f900cbb165 100644 --- a/neqo-transport/src/recv_stream.rs +++ b/neqo-transport/src/recv_stream.rs @@ -15,7 +15,8 @@ use std::{ rc::{Rc, Weak}, }; -use neqo_common::{qtrace, Role}; +use log::trace; +use neqo_common::Role; use smallvec::SmallVec; use crate::{ @@ -132,7 +133,7 @@ impl RxStreamOrderer { /// Only when `u64` values cannot be converted to `usize`, which only /// happens on 32-bit machines that hold far too much data at the same time. pub fn inbound_frame(&mut self, mut new_start: u64, mut new_data: &[u8]) { - qtrace!("Inbound data offset={} len={}", new_start, new_data.len()); + trace!("Inbound data offset={} len={}", new_start, new_data.len()); // Get entry before where new entry would go, so we can see if we already // have the new bytes. @@ -165,7 +166,7 @@ impl RxStreamOrderer { // Add a range containing only new data // (In-order frames will take this path, with no overlap) let overlap = prev_end.saturating_sub(new_start); - qtrace!( + trace!( "New frame {}-{} received, overlap: {}", new_start, new_end, @@ -182,7 +183,7 @@ impl RxStreamOrderer { // NNNN // NNNN // Do nothing - qtrace!( + trace!( "Dropping frame with already-received range {}-{}", new_start, new_end @@ -190,7 +191,7 @@ impl RxStreamOrderer { return; } } else { - qtrace!("New frame {}-{} received", new_start, new_end); + trace!("New frame {}-{} received", new_start, new_end); false }; @@ -227,7 +228,7 @@ impl RxStreamOrderer { // Fills in the hole, exactly (probably common) break; } else if next_end >= new_end { - qtrace!( + trace!( "New frame {}-{} overlaps with next frame by {}, truncating", new_start, new_end, @@ -237,7 +238,7 @@ impl RxStreamOrderer { to_add = &new_data[..truncate_to]; break; } - qtrace!( + trace!( "New frame {}-{} spans entire next frame {}-{}, replacing", new_start, new_end, @@ -324,7 +325,7 @@ impl RxStreamOrderer { /// Copy received data (if any) into the buffer. Returns bytes copied. fn read(&mut self, buf: &mut [u8]) -> usize { - qtrace!("Reading {} bytes, {} available", buf.len(), self.buffered()); + trace!("Reading {} bytes, {} available", buf.len(), self.buffered()); let mut copied = 0; for (&range_start, range_data) in &mut self.data_ranges { @@ -561,7 +562,7 @@ impl RecvStream { mem::discriminant(&self.state), mem::discriminant(&new_state) ); - qtrace!( + trace!( "RecvStream {} state {} -> {}", self.stream_id.as_u64(), self.state.name(), @@ -684,7 +685,7 @@ impl RecvStream { | RecvStreamState::AbortReading { .. } | RecvStreamState::WaitForReset { .. } | RecvStreamState::ResetRecvd { .. } => { - qtrace!("data received when we are in state {}", self.state.name()); + trace!("data received when we are in state {}", self.state.name()); } } @@ -847,7 +848,7 @@ impl RecvStream { } pub fn stop_sending(&mut self, err: AppError) { - qtrace!("stop_sending called when in state {}", self.state.name()); + trace!("stop_sending called when in state {}", self.state.name()); match &mut self.state { RecvStreamState::Recv { fc, @@ -1001,7 +1002,8 @@ impl RecvStream { mod tests { use std::{cell::RefCell, ops::Range, rc::Rc}; - use neqo_common::{qtrace, Encoder}; + use log::trace; + use neqo_common::Encoder; use super::RecvStream; use crate::{ @@ -1016,7 +1018,7 @@ mod tests { fn recv_ranges(ranges: &[Range], available: usize) { const ZEROES: &[u8] = &[0; 100]; - qtrace!("recv_ranges {:?}", ranges); + trace!("recv_ranges {:?}", ranges); let mut s = RxStreamOrderer::default(); for r in ranges { @@ -1028,7 +1030,7 @@ mod tests { let mut total_recvd = 0; loop { let recvd = s.read(&mut buf[..]); - qtrace!("recv_ranges read {}", recvd); + trace!("recv_ranges read {}", recvd); total_recvd += recvd; if recvd == 0 { assert_eq!(total_recvd, available); diff --git a/neqo-transport/src/rtt.rs b/neqo-transport/src/rtt.rs index c18bbd62ec..bc0483b73e 100644 --- a/neqo-transport/src/rtt.rs +++ b/neqo-transport/src/rtt.rs @@ -11,7 +11,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qlog::NeqoQlog, qtrace}; +use log::trace; +use neqo_common::qlog::NeqoQlog; use crate::{ ackrate::{AckRate, PeerAckDelay}, @@ -74,7 +75,7 @@ impl RttEstimate { } pub fn set_initial(&mut self, rtt: Duration) { - qtrace!("initial RTT={:?}", rtt); + trace!("initial RTT={:?}", rtt); if rtt >= GRANULARITY { // Ignore if the value is too small. self.init(rtt); @@ -140,7 +141,7 @@ impl RttEstimate { self.rttvar = (self.rttvar * 3 + rttvar_sample) / 4; self.smoothed_rtt = (self.smoothed_rtt * 7 + rtt_sample) / 8; } - qtrace!( + trace!( "RTT latest={:?} -> estimate={:?}~{:?}", self.latest_rtt, self.smoothed_rtt, diff --git a/neqo-transport/src/send_stream.rs b/neqo-transport/src/send_stream.rs index e05a0efa3f..8c6fd8dda2 100644 --- a/neqo-transport/src/send_stream.rs +++ b/neqo-transport/src/send_stream.rs @@ -18,7 +18,8 @@ use std::{ }; use indexmap::IndexMap; -use neqo_common::{qdebug, qerror, qtrace, Encoder, Role}; +use log::{debug, error, trace}; +use neqo_common::{Encoder, Role}; use smallvec::SmallVec; use crate::{ @@ -405,7 +406,7 @@ impl RangeTracker { fn unmark_range(&mut self, off: u64, len: usize) { if len == 0 { - qdebug!("unmark 0-length range at {}", off); + debug!("unmark 0-length range at {}", off); return; } @@ -423,7 +424,7 @@ impl RangeTracker { // Check for overlap if *cur_off + *cur_len > off { if *cur_state == RangeState::Acked { - qdebug!( + debug!( "Attempted to unmark Acked range {}-{} with unmark_range {}-{}", cur_off, cur_len, @@ -438,7 +439,7 @@ impl RangeTracker { } if *cur_state == RangeState::Acked { - qdebug!( + debug!( "Attempted to unmark Acked range {}-{} with unmark_range {}-{}", cur_off, cur_len, @@ -646,7 +647,7 @@ impl SendStreamState { } fn transition(&mut self, new_state: Self) { - qtrace!("SendStream state {} -> {}", self.name(), new_state.name()); + trace!("SendStream state {} -> {}", self.name(), new_state.name()); *self = new_state; } } @@ -760,7 +761,7 @@ impl SendStream { tokens: &mut Vec, stats: &mut FrameStats, ) { - qtrace!("write STREAM frames at priority {:?}", priority); + trace!("write STREAM frames at priority {:?}", priority); if !self.write_reset_frame(priority, builder, tokens, stats) { self.write_blocked_frame(priority, builder, tokens, stats); self.write_stream_frame(priority, builder, tokens, stats); @@ -878,7 +879,7 @@ impl SendStream { let result = send_buf.next_bytes(); if let Some((offset, slice)) = result { if retransmission_only { - qtrace!( + trace!( "next_bytes apply retransmission limit at {}", self.retransmission_offset ); @@ -926,7 +927,7 @@ impl SendStream { fn length_and_fill(data_len: usize, space: usize) -> (usize, bool) { if data_len >= space { // More data than space allows, or an exact fit => fast path. - qtrace!("SendStream::length_and_fill fill {}", space); + trace!("SendStream::length_and_fill fill {}", space); return (space, true); } @@ -939,7 +940,7 @@ impl SendStream { // From here we can always fit `data_len`, but we might as well fill // if there is no space for the length field plus another frame. let fill = data_len + length_len + PacketBuilder::MINIMUM_FRAME_SIZE > space; - qtrace!("SendStream::length_and_fill {} fill {}", data_len, fill); + trace!("SendStream::length_and_fill {} fill {}", data_len, fill); (data_len, fill) } @@ -971,14 +972,14 @@ impl SendStream { 0 }; if overhead > builder.remaining() { - qtrace!([self], "write_frame no space for header"); + trace!("[{self}] write_frame no space for header"); return; } let (length, fill) = Self::length_and_fill(data.len(), builder.remaining() - overhead); let fin = final_size.is_some_and(|fs| fs == offset + u64::try_from(length).unwrap()); if length == 0 && !fin { - qtrace!([self], "write_frame no data, no fin"); + trace!("[{self}] write_frame no data, no fin"); return; } @@ -1015,7 +1016,7 @@ impl SendStream { | SendStreamState::Send { .. } | SendStreamState::DataSent { .. } | SendStreamState::DataRecvd { .. } => { - qtrace!([self], "Reset acked while in {} state?", self.state.name()); + trace!("[{self}] Reset acked while in {} state?", self.state.name()); } SendStreamState::ResetSent { final_retired, @@ -1025,7 +1026,7 @@ impl SendStream { final_retired, final_written, }), - SendStreamState::ResetRecvd { .. } => qtrace!([self], "already in ResetRecvd state"), + SendStreamState::ResetRecvd { .. } => trace!("[{self}] already in ResetRecvd state"), }; } @@ -1085,7 +1086,7 @@ impl SendStream { { fc.frame_lost(limit); } else { - qtrace!([self], "Ignoring lost STREAM_DATA_BLOCKED({})", limit); + trace!("[{self}] Ignoring lost STREAM_DATA_BLOCKED({})", limit); } } @@ -1153,9 +1154,8 @@ impl SendStream { }); } } - _ => qtrace!( - [self], - "mark_as_acked called from state {}", + _ => trace!( + "[{self}] mark_as_acked called from state {}", self.state.name() ), } @@ -1167,9 +1167,8 @@ impl SendStream { self.retransmission_offset, offset + u64::try_from(len).unwrap(), ); - qtrace!( - [self], - "mark_as_lost retransmission offset={}", + trace!( + "[{self}] mark_as_lost retransmission offset={}", self.retransmission_offset ); if let Some(buf) = self.state.tx_buf_mut() { @@ -1259,7 +1258,7 @@ impl SendStream { fn send_internal(&mut self, buf: &[u8], atomic: bool) -> Res { if buf.is_empty() { - qerror!([self], "zero-length send on stream"); + error!("[{self}] zero-length send on stream"); return Err(Error::InvalidInput); } @@ -1323,10 +1322,10 @@ impl SendStream { fin_acked: false, }); } - SendStreamState::DataSent { .. } => qtrace!([self], "already in DataSent state"), - SendStreamState::DataRecvd { .. } => qtrace!([self], "already in DataRecvd state"), - SendStreamState::ResetSent { .. } => qtrace!([self], "already in ResetSent state"), - SendStreamState::ResetRecvd { .. } => qtrace!([self], "already in ResetRecvd state"), + SendStreamState::DataSent { .. } => trace!("[{self}] already in DataSent state"), + SendStreamState::DataRecvd { .. } => trace!("[{self}] already in DataRecvd state"), + SendStreamState::ResetSent { .. } => trace!("[{self}] already in ResetSent state"), + SendStreamState::ResetRecvd { .. } => trace!("[{self}] already in ResetRecvd state"), } } @@ -1367,9 +1366,9 @@ impl SendStream { final_written: buffered, }); } - SendStreamState::DataRecvd { .. } => qtrace!([self], "already in DataRecvd state"), - SendStreamState::ResetSent { .. } => qtrace!([self], "already in ResetSent state"), - SendStreamState::ResetRecvd { .. } => qtrace!([self], "already in ResetRecvd state"), + SendStreamState::DataRecvd { .. } => trace!("[{self}] already in DataRecvd state"), + SendStreamState::ResetSent { .. } => trace!("[{self}] already in ResetSent state"), + SendStreamState::ResetRecvd { .. } => trace!("[{self}] already in ResetRecvd state"), }; } @@ -1580,7 +1579,7 @@ impl SendStreams { self.get_mut(stream_id).unwrap().set_sendorder(sendorder); group = self.group_mut(sendorder); group.insert(stream_id); - qtrace!( + trace!( "ordering of stream_ids: {:?}", self.sendordered.values().collect::>() ); @@ -1694,7 +1693,7 @@ impl SendStreams { tokens: &mut Vec, stats: &mut FrameStats, ) { - qtrace!("write STREAM frames at priority {:?}", priority); + trace!("write STREAM frames at priority {:?}", priority); // WebTransport data (which is Normal) may have a SendOrder // priority attached. The spec states (6.3 write-chunk 6.1): @@ -1728,16 +1727,16 @@ impl SendStreams { // Iterate the map, but only those without fairness, then iterate // OrderGroups, then iterate each group - qtrace!("processing streams... unfair:"); + trace!("processing streams... unfair:"); for stream in self.map.values_mut() { if !stream.is_fair() { - qtrace!(" {}", stream); + trace!(" {}", stream); if !stream.write_frames_with_early_return(priority, builder, tokens, stats) { break; } } } - qtrace!("fair streams:"); + trace!("fair streams:"); let stream_ids = self.regular.iter().chain( self.sendordered .values_mut() @@ -1747,9 +1746,9 @@ impl SendStreams { for stream_id in stream_ids { let stream = self.map.get_mut(&stream_id).unwrap(); if let Some(order) = stream.sendorder() { - qtrace!(" {} ({})", stream_id, order); + trace!(" {} ({})", stream_id, order); } else { - qtrace!(" None"); + trace!(" None"); } if !stream.write_frames_with_early_return(priority, builder, tokens, stats) { break; @@ -1793,7 +1792,8 @@ pub struct SendStreamRecoveryToken { mod tests { use std::{cell::RefCell, collections::VecDeque, num::NonZeroUsize, rc::Rc}; - use neqo_common::{event::Provider, hex_with_len, qtrace, Encoder}; + use log::trace; + use neqo_common::{event::Provider, hex_with_len, Encoder}; use super::SendStreamRecoveryToken; use crate::{ @@ -2943,7 +2943,7 @@ mod tests { fn frame_sent_sid(stream: u64, offset: usize, len: usize, fin: bool, space: usize) -> bool { const BUF: &[u8] = &[0x42; 128]; - qtrace!( + trace!( "frame_sent stream={} offset={} len={} fin={}, space={}", stream, offset, @@ -2974,7 +2974,7 @@ mod tests { &mut tokens, &mut stats, ); - qtrace!( + trace!( "STREAM frame: {}", hex_with_len(&builder.as_ref()[header_len..]) ); @@ -3058,7 +3058,7 @@ mod tests { fn stream_frame_at_boundary(data: &[u8]) { fn send_with_extra_capacity(data: &[u8], extra: usize, expect_full: bool) -> Vec { - qtrace!("send_with_extra_capacity {} + {}", data.len(), extra); + trace!("send_with_extra_capacity {} + {}", data.len(), extra); let mut s = stream_with_sent(0, 0); s.send(data).unwrap(); s.close(); diff --git a/neqo-transport/src/sender.rs b/neqo-transport/src/sender.rs index e6075ee327..bceb40502c 100644 --- a/neqo-transport/src/sender.rs +++ b/neqo-transport/src/sender.rs @@ -13,7 +13,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qdebug, qlog::NeqoQlog}; +use log::debug; +use neqo_common::qlog::NeqoQlog; use crate::{ cc::{ClassicCongestionControl, CongestionControl, CongestionControlAlgorithm, Cubic, NewReno}, @@ -92,7 +93,7 @@ impl PacketSender { fn maybe_update_pacer_mtu(&mut self) { let current_mtu = self.pmtud().plpmtu(); if current_mtu != self.pacer.mtu() { - qdebug!( + debug!( "PLPMTU changed from {} to {}, updating pacer", self.pacer.mtu(), current_mtu diff --git a/neqo-transport/src/server.rs b/neqo-transport/src/server.rs index 154ad17ed3..6df956f416 100644 --- a/neqo-transport/src/server.rs +++ b/neqo-transport/src/server.rs @@ -16,10 +16,8 @@ use std::{ time::Instant, }; -use neqo_common::{ - event::Provider, hex, qdebug, qerror, qinfo, qlog::NeqoQlog, qtrace, qwarn, Datagram, IpTos, - Role, -}; +use log::{debug, error, info, trace, warn}; +use neqo_common::{event::Provider, hex, qlog::NeqoQlog, Datagram, IpTos, Role}; use neqo_crypto::{ encode_ech_config, AntiReplay, Cipher, PrivateKey, PublicKey, ZeroRttCheckResult, ZeroRttChecker, @@ -199,7 +197,7 @@ impl Server { dgram: Datagram>, now: Instant, ) -> Output { - qdebug!([self], "Handle initial"); + debug!("[{self}] Handle initial"); let res = self .address_validation .borrow() @@ -211,7 +209,7 @@ impl Server { self.accept_connection(initial, dgram, Some(orig_dcid), now) } AddressValidationResult::Validate => { - qinfo!([self], "Send retry for {:?}", initial.dst_cid); + info!("[{self}] Send retry for {:?}", initial.dst_cid); let res = self.address_validation.borrow().generate_retry_token( &initial.dst_cid, @@ -219,7 +217,7 @@ impl Server { now, ); let Ok(token) = res else { - qerror!([self], "unable to generate token, dropping packet"); + error!("[{self}] unable to generate token, dropping packet"); return Output::None; }; if let Some(new_dcid) = self.cid_generator.borrow_mut().generate_cid() { @@ -232,13 +230,12 @@ impl Server { ); packet.map_or_else( |_| { - qerror!([self], "unable to encode retry, dropping packet"); + error!("[{self}] unable to encode retry, dropping packet"); Output::None }, |p| { - qdebug!( - [self], - "type={:?} path:{} {}->{} {:?} len {}", + debug!( + "[{self}] type={:?} path:{} {}->{} {:?} len {}", PacketType::Retry, initial.dst_cid, dgram.destination(), @@ -255,7 +252,7 @@ impl Server { }, ) } else { - qerror!([self], "no connection ID for retry, dropping packet"); + error!("[{self}] no connection ID for retry, dropping packet"); Output::None } } @@ -274,7 +271,7 @@ impl Server { format!("server-{odcid}"), ) .unwrap_or_else(|e| { - qerror!("failed to create NeqoQlog: {}", e); + error!("failed to create NeqoQlog: {}", e); NeqoQlog::disabled() }) }) @@ -288,7 +285,7 @@ impl Server { ) { let zcheck = self.zero_rtt_checker.clone(); if c.server_enable_0rtt(&self.anti_replay, zcheck).is_err() { - qwarn!([self], "Unable to enable 0-RTT"); + warn!("[{self}] Unable to enable 0-RTT"); } if let Some(odcid) = &orig_dcid { // There was a retry, so set the connection IDs for. @@ -300,7 +297,7 @@ impl Server { if c.server_enable_ech(cfg.config, &cfg.public_name, &cfg.sk, &cfg.pk) .is_err() { - qwarn!([self], "Unable to enable ECH"); + warn!("[{self}] Unable to enable ECH"); } } } @@ -312,9 +309,8 @@ impl Server { orig_dcid: Option, now: Instant, ) -> Output { - qinfo!( - [self], - "Accept connection {:?}", + info!( + "[{self}] Accept connection {:?}", orig_dcid.as_ref().unwrap_or(&initial.dst_cid) ); // The internal connection ID manager that we use is not used directly. @@ -337,7 +333,7 @@ impl Server { out } Err(e) => { - qwarn!([self], "Unable to create connection"); + warn!("[{self}] Unable to create connection"); if e == crate::Error::VersionNegotiation { crate::qlog::server_version_information_failed( &self.create_qlog_trace(orig_dcid.unwrap_or(initial.dst_cid).as_cid_ref()), @@ -352,13 +348,13 @@ impl Server { } fn process_input(&mut self, dgram: Datagram>, now: Instant) -> Output { - qtrace!("Process datagram: {}", hex(&dgram[..])); + trace!("Process datagram: {}", hex(&dgram[..])); // This is only looking at the first packet header in the datagram. // All packets in the datagram are routed to the same connection. let res = PublicPacket::decode(&dgram[..], self.cid_generator.borrow().as_decoder()); let Ok((packet, _remainder)) = res else { - qtrace!([self], "Discarding {:?}", dgram); + trace!("[{self}] Discarding {:?}", dgram); return Output::None; }; @@ -373,7 +369,7 @@ impl Server { if packet.packet_type() == PacketType::Short { // TODO send a stateless reset here. - qtrace!([self], "Short header packet for an unknown connection"); + trace!("[{self}] Short header packet for an unknown connection"); return Output::None; } @@ -386,20 +382,19 @@ impl Server { .contains(&packet.version().unwrap())) { if dgram.len() < MIN_INITIAL_PACKET_SIZE { - qdebug!([self], "Unsupported version: too short"); + debug!("[{self}] Unsupported version: too short"); return Output::None; } - qdebug!([self], "Unsupported version: {:x}", packet.wire_version()); + debug!("[{self}] Unsupported version: {:x}", packet.wire_version()); let vn = PacketBuilder::version_negotiation( &packet.scid()[..], &packet.dcid()[..], packet.wire_version(), self.conn_params.get_versions().all(), ); - qdebug!( - [self], - "type={:?} path:{} {}->{} {:?} len {}", + debug!( + "[{self}] type={:?} path:{} {}->{} {:?} len {}", PacketType::VersionNegotiation, packet.dcid(), dgram.destination(), @@ -426,7 +421,7 @@ impl Server { match packet.packet_type() { PacketType::Initial => { if dgram.len() < MIN_INITIAL_PACKET_SIZE { - qdebug!([self], "Drop initial: too short"); + debug!("[{self}] Drop initial: too short"); return Output::None; } // Copy values from `packet` because they are currently still borrowing from @@ -436,12 +431,12 @@ impl Server { } PacketType::ZeroRtt => { let dcid = ConnectionId::from(packet.dcid()); - qdebug!([self], "Dropping 0-RTT for unknown connection {}", dcid); + debug!("[{self}] Dropping 0-RTT for unknown connection {}", dcid); Output::None } PacketType::OtherVersion => unreachable!(), _ => { - qtrace!([self], "Not an initial packet"); + trace!("[{self}] Not an initial packet"); Output::None } } diff --git a/neqo-transport/src/shuffle.rs b/neqo-transport/src/shuffle.rs index fd81190c27..bc1cf06c34 100644 --- a/neqo-transport/src/shuffle.rs +++ b/neqo-transport/src/shuffle.rs @@ -6,7 +6,8 @@ use std::ops::Range; -use neqo_common::{qtrace, Decoder}; +use log::trace; +use neqo_common::Decoder; /// Finds the range where the SNI extension lives, or returns `None`. #[must_use] @@ -54,7 +55,7 @@ pub fn find_sni(buf: &[u8]) -> Option> { if end > dec.offset() + dec.remaining() { return None; } - qtrace!( + trace!( "SNI range {start}..{end}: {:?}", String::from_utf8_lossy(&buf[start..end]) ); diff --git a/neqo-transport/src/stats.rs b/neqo-transport/src/stats.rs index af8ae69a70..ae60b7fe07 100644 --- a/neqo-transport/src/stats.rs +++ b/neqo-transport/src/stats.rs @@ -14,7 +14,7 @@ use std::{ time::Duration, }; -use neqo_common::qwarn; +use log::warn; use crate::{ ecn::{EcnCount, EcnValidationCount}, @@ -222,9 +222,9 @@ impl Stats { pub fn pkt_dropped(&mut self, reason: impl AsRef) { self.dropped_rx += 1; - qwarn!( - [self.info], - "Dropped received packet: {}; Total: {}", + warn!( + "[{}] Dropped received packet: {}; Total: {}", + self.info, reason.as_ref(), self.dropped_rx ); diff --git a/neqo-transport/src/streams.rs b/neqo-transport/src/streams.rs index 059607be08..ca3387c19c 100644 --- a/neqo-transport/src/streams.rs +++ b/neqo-transport/src/streams.rs @@ -7,7 +7,8 @@ // Stream management for a connection. use std::{cell::RefCell, cmp::Ordering, rc::Rc}; -use neqo_common::{qtrace, qwarn, Role}; +use log::{trace, warn}; +use neqo_common::Role; use crate::{ fc::{LocalStreamLimits, ReceiverFlowControl, RemoteStreamLimits, SenderFlowControl}, @@ -164,7 +165,7 @@ impl Streams { stream_id, maximum_stream_data, } => { - qtrace!( + trace!( "Stream {} Received MaxStreamData {}", *stream_id, *maximum_stream_data @@ -183,12 +184,12 @@ impl Streams { } Frame::DataBlocked { data_limit } => { // Should never happen since we set data limit to max - qwarn!("Received DataBlocked with data limit {}", data_limit); + warn!("Received DataBlocked with data limit {}", data_limit); stats.data_blocked += 1; self.handle_data_blocked(); } Frame::StreamDataBlocked { stream_id, .. } => { - qtrace!("Received StreamDataBlocked"); + trace!("Received StreamDataBlocked"); stats.stream_data_blocked += 1; // Terminate connection with STREAM_STATE_ERROR if send-only // stream (-transport 19.13) diff --git a/neqo-transport/src/tparams.rs b/neqo-transport/src/tparams.rs index 723492c448..10463e2288 100644 --- a/neqo-transport/src/tparams.rs +++ b/neqo-transport/src/tparams.rs @@ -13,7 +13,8 @@ use std::{ rc::Rc, }; -use neqo_common::{hex, qdebug, qinfo, qtrace, Decoder, Encoder, Role}; +use log::{debug, info, trace}; +use neqo_common::{hex, Decoder, Encoder, Role}; use neqo_crypto::{ constants::{TLS_HS_CLIENT_HELLO, TLS_HS_ENCRYPTED_EXTENSIONS}, ext::{ExtensionHandler, ExtensionHandlerResult, ExtensionWriterResult}, @@ -139,7 +140,7 @@ pub enum TransportParameter { impl TransportParameter { fn encode(&self, enc: &mut Encoder, tp: TransportParameterId) { - qtrace!("TP encoded; type 0x{:02x} val {:?}", tp, self); + trace!("TP encoded; type 0x{:02x} val {:?}", tp, self); enc.encode_varint(tp); match self { Self::Bytes(a) => { @@ -250,7 +251,7 @@ impl TransportParameter { fn decode(dec: &mut Decoder) -> Res> { let tp = dec.decode_varint().ok_or(Error::NoMoreData)?; let content = dec.decode_vvec().ok_or(Error::NoMoreData)?; - qtrace!("TP {:x} length {:x}", tp, content.len()); + trace!("TP {:x} length {:x}", tp, content.len()); let mut d = Decoder::from(content); let value = match tp { ORIGINAL_DESTINATION_CONNECTION_ID @@ -309,7 +310,7 @@ impl TransportParameter { if d.remaining() > 0 { return Err(Error::TooMuchData); } - qtrace!("TP decoded; type 0x{:02x} val {:?}", tp, value); + trace!("TP decoded; type 0x{:02x} val {:?}", tp, value); Ok(Some((tp, value))) } } @@ -334,7 +335,7 @@ impl TransportParameters { /// using the provided decoder. pub(crate) fn decode(d: &mut Decoder) -> Res { let mut tps = Self::default(); - qtrace!("Parsed fixed TP header"); + trace!("Parsed fixed TP header"); while d.remaining() > 0 { match TransportParameter::decode(d) { @@ -627,7 +628,7 @@ impl TransportParametersHandler { fn compatible_upgrade(&mut self, remote_tp: &TransportParameters) -> Res<()> { if let Some((current, other)) = remote_tp.get_versions() { - qtrace!( + trace!( "Peer versions: {:x} {:x?}; config {:?}", current, other, @@ -639,7 +640,7 @@ impl TransportParametersHandler { if self.versions.compatible().any(|&v| v == chosen) { Ok(()) } else { - qinfo!( + info!( "Chosen version {:x} is not compatible with initial version {:x}", current, self.versions.initial().wire_version(), @@ -648,7 +649,7 @@ impl TransportParametersHandler { } } else { if current != self.versions.initial().wire_version() { - qinfo!( + info!( "Current version {:x} != own version {:x}", current, self.versions.initial().wire_version(), @@ -658,7 +659,7 @@ impl TransportParametersHandler { if let Some(preferred) = self.versions.preferred_compatible(other) { if preferred != self.versions.initial() { - qinfo!( + info!( "Compatible upgrade {:?} ==> {:?}", self.versions.initial(), preferred @@ -668,7 +669,7 @@ impl TransportParametersHandler { } Ok(()) } else { - qinfo!("Unable to find any compatible version"); + info!("Unable to find any compatible version"); Err(Error::TransportParameterError) } } @@ -684,7 +685,7 @@ impl ExtensionHandler for TransportParametersHandler { return ExtensionWriterResult::Skip; } - qdebug!("Writing transport parameters, msg={:?}", msg); + debug!("Writing transport parameters, msg={:?}", msg); // TODO(ekr@rtfm.com): Modify to avoid a copy. let mut enc = Encoder::default(); @@ -695,7 +696,7 @@ impl ExtensionHandler for TransportParametersHandler { } fn handle(&mut self, msg: HandshakeMessage, d: &[u8]) -> ExtensionHandlerResult { - qtrace!( + trace!( "Handling transport parameters, msg={:?} value={}", msg, hex(d), @@ -748,24 +749,24 @@ where fn check(&self, token: &[u8]) -> ZeroRttCheckResult { // Reject 0-RTT if there is no token. if token.is_empty() { - qdebug!("0-RTT: no token, no 0-RTT"); + debug!("0-RTT: no token, no 0-RTT"); return ZeroRttCheckResult::Reject; } let mut dec = Decoder::from(token); let Some(tpslice) = dec.decode_vvec() else { - qinfo!("0-RTT: token code error"); + info!("0-RTT: token code error"); return ZeroRttCheckResult::Fail; }; let mut dec_tp = Decoder::from(tpslice); let Ok(remembered) = TransportParameters::decode(&mut dec_tp) else { - qinfo!("0-RTT: transport parameter decode error"); + info!("0-RTT: transport parameter decode error"); return ZeroRttCheckResult::Fail; }; if self.handler.borrow().local.ok_for_0rtt(&remembered) { - qinfo!("0-RTT: transport parameters OK, passing to application checker"); + info!("0-RTT: transport parameters OK, passing to application checker"); self.app_checker.check(dec.decode_remainder()) } else { - qinfo!("0-RTT: transport parameters bad, rejecting"); + info!("0-RTT: transport parameters bad, rejecting"); ZeroRttCheckResult::Reject } } diff --git a/neqo-transport/src/tracking.rs b/neqo-transport/src/tracking.rs index 17ec6d6f9c..ebf83a94f1 100644 --- a/neqo-transport/src/tracking.rs +++ b/neqo-transport/src/tracking.rs @@ -14,7 +14,8 @@ use std::{ }; use enum_map::{enum_map, Enum, EnumMap}; -use neqo_common::{qdebug, qinfo, qtrace, qwarn, IpTosEcn}; +use log::{debug, info, trace, warn}; +use neqo_common::IpTosEcn; use neqo_crypto::{Epoch, TLS_EPOCH_HANDSHAKE, TLS_EPOCH_INITIAL}; use crate::{ @@ -180,12 +181,12 @@ impl PacketRange { assert!(!self.contains(pn)); // Only insert if this is adjacent the current range. if (self.largest + 1) == pn { - qtrace!([self], "Adding largest {}", pn); + trace!("[{self}] Adding largest {}", pn); self.largest += 1; self.ack_needed = true; InsertionResult::Largest } else if self.smallest == (pn + 1) { - qtrace!([self], "Adding smallest {}", pn); + trace!("[{self}] Adding smallest {}", pn); self.smallest -= 1; self.ack_needed = true; InsertionResult::Smallest @@ -196,7 +197,7 @@ impl PacketRange { /// Maybe merge a higher-numbered range into this. fn merge_larger(&mut self, other: &Self) { - qinfo!([self], "Merging {}", other); + info!("[{self}] Merging {}", other); // This only works if they are immediately adjacent. assert_eq!(self.largest + 1, other.smallest); @@ -369,10 +370,10 @@ impl RecvdPackets { if self.ranges.len() > MAX_TRACKED_RANGES { let oldest = self.ranges.pop_back().unwrap(); if oldest.ack_needed { - qwarn!([self], "Dropping unacknowledged ACK range: {}", oldest); + warn!("[{self}] Dropping unacknowledged ACK range: {}", oldest); // TODO(mt) Record some statistics about this so we can tune MAX_TRACKED_RANGES. } else { - qdebug!([self], "Drop ACK range: {}", oldest); + debug!("[{self}] Drop ACK range: {}", oldest); } self.min_tracked = oldest.largest + 1; } @@ -382,7 +383,7 @@ impl RecvdPackets { /// Return true if the packet was the largest received so far. pub fn set_received(&mut self, now: Instant, pn: PacketNumber, ack_eliciting: bool) -> bool { let next_in_order_pn = self.ranges.front().map_or(0, |r| r.largest + 1); - qtrace!([self], "received {}, next: {}", pn, next_in_order_pn); + trace!("[{self}] received {}, next: {}", pn, next_in_order_pn); self.add(pn); self.trim_ranges(); @@ -413,7 +414,7 @@ impl RecvdPackets { // of the change is very small. self.ack_time.unwrap_or_else(|| now + self.ack_delay) }; - qdebug!([self], "Set ACK timer to {:?}", ack_time); + debug!("[{self}] Set ACK timer to {:?}", ack_time); self.ack_time = Some(ack_time); } largest @@ -422,7 +423,7 @@ impl RecvdPackets { /// If we just received a PING frame, we should immediately acknowledge. pub fn immediate_ack(&mut self, now: Instant) { self.ack_time = Some(now); - qdebug!([self], "immediate_ack at {:?}", now); + debug!("[{self}] immediate_ack at {:?}", now); } /// Check if the packet is a duplicate. @@ -601,7 +602,7 @@ impl AckTracker { #[cfg(debug_assertions)] for (space, recvd) in &self.spaces { if let Some(recvd) = recvd { - qtrace!("ack_time for {} = {:?}", space, recvd.ack_time()); + trace!("ack_time for {} = {:?}", space, recvd.ack_time()); } } diff --git a/neqo-transport/src/version.rs b/neqo-transport/src/version.rs index fc6878941c..e6430968b7 100644 --- a/neqo-transport/src/version.rs +++ b/neqo-transport/src/version.rs @@ -4,7 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use neqo_common::qdebug; +use log::debug; use crate::{Error, Res}; @@ -188,10 +188,9 @@ impl VersionConfig { /// Overwrite the initial value; used by the `Server` when handling new connections /// and by the client on resumption. pub(crate) fn set_initial(&mut self, initial: Version) { - qdebug!( + debug!( "Overwrite initial version {:?} ==> {:?}", - self.initial, - initial + self.initial, initial ); assert!(self.all.contains(&initial)); self.initial = initial; diff --git a/neqo-transport/tests/common/mod.rs b/neqo-transport/tests/common/mod.rs index a16c5f2c92..e806a2f33b 100644 --- a/neqo-transport/tests/common/mod.rs +++ b/neqo-transport/tests/common/mod.rs @@ -8,7 +8,8 @@ use std::{cell::RefCell, mem, ops::Range, rc::Rc}; -use neqo_common::{event::Provider, hex_with_len, qtrace, Datagram, Decoder, Role}; +use log::trace; +use neqo_common::{event::Provider, hex_with_len, Datagram, Decoder, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, hkdf, diff --git a/neqo-transport/tests/retry.rs b/neqo-transport/tests/retry.rs index 0dc083859b..cd545b8445 100644 --- a/neqo-transport/tests/retry.rs +++ b/neqo-transport/tests/retry.rs @@ -15,7 +15,8 @@ use std::{ }; use common::{connected_server, default_server, generate_ticket}; -use neqo_common::{hex_with_len, qdebug, qtrace, Datagram, Encoder, Role}; +use log::{debug, trace}; +use neqo_common::{hex_with_len, Datagram, Encoder, Role}; use neqo_crypto::AuthenticationStatus; use neqo_transport::{ server::ValidateAddress, CloseReason, Error, State, StreamType, MIN_INITIAL_PACKET_SIZE, @@ -398,7 +399,7 @@ fn mitm_retry() { .encode_varint(u64::try_from(payload.len()).unwrap()); let pn_offset = enc.len(); let notoken_header = enc.encode_uint(pn_len, pn).as_ref().to_vec(); - qtrace!("notoken_header={}", hex_with_len(¬oken_header)); + trace!("notoken_header={}", hex_with_len(¬oken_header)); // Encrypt. let mut notoken_packet = Encoder::with_capacity(MIN_INITIAL_PACKET_SIZE) @@ -417,7 +418,7 @@ fn mitm_retry() { // All MIN_INITIAL_PACKET_SIZE bytes are needed to reach the minimum datagram size. apply_header_protection(&hp, &mut notoken_packet, pn_offset..(pn_offset + pn_len)); - qtrace!("packet={}", hex_with_len(¬oken_packet)); + trace!("packet={}", hex_with_len(¬oken_packet)); let new_datagram = Datagram::new( client_initial2.source(), @@ -425,7 +426,7 @@ fn mitm_retry() { client_initial2.tos(), notoken_packet, ); - qdebug!("passing modified Initial to the main server"); + debug!("passing modified Initial to the main server"); let dgram = server.process(Some(new_datagram), now()).dgram(); assert!(dgram.is_some()); diff --git a/neqo-transport/tests/server.rs b/neqo-transport/tests/server.rs index 8ff6511e0b..653cfc5c08 100644 --- a/neqo-transport/tests/server.rs +++ b/neqo-transport/tests/server.rs @@ -9,7 +9,8 @@ mod common; use std::{cell::RefCell, mem, net::SocketAddr, rc::Rc, time::Duration}; use common::{connect, connected_server, default_server, find_ticket, generate_ticket, new_server}; -use neqo_common::{qtrace, Datagram, Decoder, Encoder, Role}; +use log::trace; +use neqo_common::{Datagram, Decoder, Encoder, Role}; use neqo_crypto::{ generate_ech_keys, AllowZeroRtt, AuthenticationStatus, ZeroRttCheckResult, ZeroRttChecker, }; @@ -737,7 +738,7 @@ fn closed() { let res = client.process_output(now()); assert!(res.callback() > Duration::new(0, 0)); - qtrace!("60s later"); + trace!("60s later"); let res = server.process_output(now() + Duration::from_secs(60)); assert_eq!(res, Output::None); } diff --git a/neqo-udp/src/lib.rs b/neqo-udp/src/lib.rs index 61f7fa1ca2..1d6d1d6b9f 100644 --- a/neqo-udp/src/lib.rs +++ b/neqo-udp/src/lib.rs @@ -12,7 +12,8 @@ use std::{ slice::{self, Chunks}, }; -use neqo_common::{qdebug, qtrace, Datagram, IpTos}; +use log::{debug, trace}; +use neqo_common::{Datagram, IpTos}; use quinn_udp::{EcnCodepoint, RecvMeta, Transmit, UdpSocketState}; /// Socket receive buffer size. @@ -37,7 +38,7 @@ pub fn send_inner( state.try_send(socket, &transmit)?; - qtrace!( + trace!( "sent {} bytes from {} to {}", d.len(), d.source(), @@ -70,12 +71,9 @@ pub fn recv_inner<'a>( )?; if meta.len == 0 || meta.stride == 0 { - qdebug!( + debug!( "ignoring datagram from {} to {} len {} stride {}", - meta.addr, - local_address, - meta.len, - meta.stride + meta.addr, local_address, meta.len, meta.stride ); continue; } @@ -83,7 +81,7 @@ pub fn recv_inner<'a>( break &recv_buf[..meta.len]; }; - qtrace!( + trace!( "received {} bytes from {} to {} in {} segments", data.len(), meta.addr, diff --git a/test-fixture/src/header_protection.rs b/test-fixture/src/header_protection.rs index 3b7b8b0dc2..fbe209c331 100644 --- a/test-fixture/src/header_protection.rs +++ b/test-fixture/src/header_protection.rs @@ -8,7 +8,8 @@ use std::{cell::RefCell, mem, ops::Range, rc::Rc}; -use neqo_common::{event::Provider, hex_with_len, qtrace, Datagram, Decoder, Role}; +use log::trace; +use neqo_common::{event::Provider, hex_with_len, Datagram, Decoder, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, hkdf, @@ -131,7 +132,7 @@ pub fn apply_header_protection(hp: &HpKey, packet: &mut [u8], pn_bytes: Range (&[u8], Option<&[u8]>) { } else { None }; - qtrace!("split packet: {} {:?}", hex(p1), p2.map(hex)); + trace!("split packet: {} {:?}", hex(p1), p2.map(hex)); (p1, p2) } diff --git a/test-fixture/src/sim/connection.rs b/test-fixture/src/sim/connection.rs index 63fb56ce0b..9e41d3b41b 100644 --- a/test-fixture/src/sim/connection.rs +++ b/test-fixture/src/sim/connection.rs @@ -12,7 +12,8 @@ use std::{ time::Instant, }; -use neqo_common::{event::Provider, qdebug, qinfo, qtrace, Datagram}; +use log::{debug, info, trace}; +use neqo_common::{event::Provider, Datagram}; use neqo_crypto::AuthenticationStatus; use neqo_transport::{ Connection, ConnectionEvent, ConnectionParameters, Output, State, StreamId, StreamType, @@ -145,7 +146,7 @@ impl Node for ConnectionNode { let mut active = false; while let Some(e) = self.c.next_event() { - qtrace!([self.c], "received event {:?}", e); + trace!("[{}] received event {:?}", self.c, e); // Perform authentication automatically. if matches!(e, ConnectionEvent::AuthenticationNeeded) { @@ -160,7 +161,7 @@ impl Node for ConnectionNode { if matches!(res, Output::Datagram(_)) || !active { return res; } - qdebug!([self.c], "no datagram and goal activity, looping"); + debug!("[{}] no datagram and goal activity, looping", self.c); } } @@ -175,7 +176,7 @@ impl Node for ConnectionNode { } fn print_summary(&self, test_name: &str) { - qinfo!("{}: {:?}", test_name, self.c.stats()); + info!("{}: {:?}", test_name, self.c.stats()); } } @@ -233,7 +234,7 @@ impl SendData { fn make_stream(&mut self, c: &mut Connection) { if self.stream_id.is_none() { if let Ok(stream_id) = c.stream_create(StreamType::UniDi) { - qdebug!([c], "made stream {} for sending", stream_id); + debug!("[{c}] made stream {} for sending", stream_id); self.stream_id = Some(stream_id); } } @@ -249,7 +250,7 @@ impl SendData { return status; } self.remaining -= sent; - qtrace!("sent {} remaining {}", sent, self.remaining); + trace!("sent {} remaining {}", sent, self.remaining); if self.remaining == 0 { c.stream_close_send(stream_id).unwrap(); return GoalStatus::Done; @@ -315,7 +316,7 @@ impl ReceiveData { loop { let end = min(self.remaining, buf.len()); let (recvd, _) = c.stream_recv(stream_id, &mut buf[..end]).unwrap(); - qtrace!("received {} remaining {}", recvd, self.remaining); + trace!("received {} remaining {}", recvd, self.remaining); if recvd == 0 { return status; } diff --git a/test-fixture/src/sim/drop.rs b/test-fixture/src/sim/drop.rs index fbecd0536c..8f48a09abc 100644 --- a/test-fixture/src/sim/drop.rs +++ b/test-fixture/src/sim/drop.rs @@ -9,7 +9,8 @@ use std::{ time::Instant, }; -use neqo_common::{qtrace, Datagram}; +use log::trace; +use neqo_common::Datagram; use neqo_transport::Output; use super::{Node, Rng}; @@ -62,7 +63,7 @@ impl Node for Drop { fn process(&mut self, d: Option, _now: Instant) -> Output { d.map_or(Output::None, |dgram| { if self.drop() { - qtrace!("drop {}", dgram.len()); + trace!("drop {}", dgram.len()); Output::None } else { Output::Datagram(dgram) diff --git a/test-fixture/src/sim/mod.rs b/test-fixture/src/sim/mod.rs index 5969d0b282..23774395c8 100644 --- a/test-fixture/src/sim/mod.rs +++ b/test-fixture/src/sim/mod.rs @@ -22,7 +22,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qdebug, qerror, qinfo, qtrace, Datagram, Encoder}; +use log::{debug, error, info, trace}; +use neqo_common::{Datagram, Encoder}; use neqo_transport::Output; use rng::Random; use NodeState::{Active, Idle, Waiting}; @@ -162,12 +163,12 @@ impl Simulator { // variable, if set. if let Ok(dir) = std::env::var("DUMP_SIMULATION_SEEDS") { if create_dir_all(&dir).is_err() { - qerror!("Failed to create directory {dir}"); + error!("Failed to create directory {dir}"); } else { let seed_str = sim.rng.borrow().seed_str(); let path = PathBuf::from(format!("{dir}/{}-{seed_str}", sim.name)); if File::create(&path).is_err() { - qerror!("Failed to write seed to {}", path.to_string_lossy()); + error!("Failed to write seed to {}", path.to_string_lossy()); } } } @@ -199,25 +200,25 @@ impl Simulator { loop { for n in &mut self.nodes { if dgram.is_none() && !n.ready(now) { - qdebug!([self.name], "skipping {:?}", n.node); + debug!("[{}] kipping {:?}", self.name, n.node); continue; } - qdebug!([self.name], "processing {:?}", n.node); + debug!("[{}] processing {:?}", self.name, n.node); let res = n.process(dgram.take(), now); n.state = match res { Output::Datagram(d) => { - qtrace!([self.name], " => datagram {}", d.len()); + trace!("[{}] => datagram {}", self.name, d.len()); dgram = Some(d); Active } Output::Callback(delay) => { - qtrace!([self.name], " => callback {:?}", delay); + trace!("[{}] => callback {:?}", self.name, delay); assert_ne!(delay, Duration::new(0, 0)); Waiting(now + delay) } Output::None => { - qtrace!([self.name], " => nothing"); + trace!("[{}] => nothing", self.name); assert!(n.done(), "nodes should be done when they go idle"); Idle } @@ -231,9 +232,9 @@ impl Simulator { if dgram.is_none() { let next = self.next_time(now); if next > now { - qinfo!( - [self.name], - "advancing time by {:?} to {:?}", + info!( + "[{}] advancing time by {:?} to {:?}", + self.name, next - now, next - start ); @@ -247,7 +248,7 @@ impl Simulator { pub fn setup(mut self) -> ReadySimulator { let start = now(); - qinfo!("{}: seed {}", self.name, self.rng.borrow().seed_str()); + info!("{}: seed {}", self.name, self.rng.borrow().seed_str()); for n in &mut self.nodes { n.init(self.rng.clone(), start); } @@ -255,7 +256,7 @@ impl Simulator { let setup_start = Instant::now(); let now = self.process_loop(start, start); let setup_time = now - start; - qinfo!( + info!( "{t}: Setup took {wall:?} (wall) {setup_time:?} (simulated)", t = self.name, wall = setup_start.elapsed(), @@ -297,7 +298,7 @@ impl ReadySimulator { let real_start = Instant::now(); let end = self.sim.process_loop(self.start, self.now); let sim_time = end - self.now; - qinfo!( + info!( "{t}: Simulation took {wall:?} (wall) {sim_time:?} (simulated)", t = self.sim.name, wall = real_start.elapsed(), diff --git a/test-fixture/src/sim/taildrop.rs b/test-fixture/src/sim/taildrop.rs index e29f458b38..1d7331d90c 100644 --- a/test-fixture/src/sim/taildrop.rs +++ b/test-fixture/src/sim/taildrop.rs @@ -11,7 +11,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qinfo, qtrace, Datagram}; +use log::{info, trace}; +use neqo_common::Datagram; use neqo_transport::Output; use super::Node; @@ -133,7 +134,7 @@ impl TailDrop { self.maxq = max(self.maxq, self.used); self.queue.push_back(d); } else { - qtrace!("taildrop dropping {} bytes", d.len()); + trace!("taildrop dropping {} bytes", d.len()); self.dropped += 1; } } @@ -175,13 +176,9 @@ impl Node for TailDrop { } fn print_summary(&self, test_name: &str) { - qinfo!( + info!( "{}: taildrop: rx {} drop {} tx {} maxq {}", - test_name, - self.received, - self.dropped, - self.delivered, - self.maxq, + test_name, self.received, self.dropped, self.delivered, self.maxq, ); } } From 01319b6e6f54be563572063720efa591e2aba641 Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 10:44:37 +0200 Subject: [PATCH 2/9] Style the output a bit --- Cargo.lock | 12 ++++++++++++ neqo-bin/Cargo.toml | 2 +- neqo-bin/src/lib.rs | 10 ++++++---- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 95020625f9..06d749e46b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -368,7 +368,10 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" dependencies = [ + "is-terminal", "log", + "regex", + "termcolor", ] [[package]] @@ -1209,6 +1212,15 @@ dependencies = [ "syn", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "test-fixture" version = "0.11.0" diff --git a/neqo-bin/Cargo.toml b/neqo-bin/Cargo.toml index 565ddb086b..6e57ccb5fb 100644 --- a/neqo-bin/Cargo.toml +++ b/neqo-bin/Cargo.toml @@ -29,7 +29,7 @@ workspace = true # Not used in Firefox, so we can be liberal with dependency versions clap = { version = "4.4", default-features = false, features = ["std", "help", "usage", "error-context", "suggestions", "derive"] } clap-verbosity-flag = { version = "3.0", default-features = false, features = ["log"] } -env_logger = { version = "0.10", default-features = false } +env_logger = { version = "0.10", default-features = false, features = ["auto-color", "regex"] } futures = { version = "0.3", default-features = false, features = ["alloc"] } hex = { version = "0.4", default-features = false, features = ["std"] } log = { workspace = true } diff --git a/neqo-bin/src/lib.rs b/neqo-bin/src/lib.rs index 66af6ab33a..c3244b46b5 100644 --- a/neqo-bin/src/lib.rs +++ b/neqo-bin/src/lib.rs @@ -257,12 +257,14 @@ pub fn log_init(level_filter: Option) { } builder.format(|buf, record| { let elapsed = since_start(); + let level_style = buf.default_level_style(record.level()); + let mut bold = buf.style(); + bold.set_bold(true); writeln!( buf, - "{}s{:3}ms {} {}", - elapsed.as_secs(), - elapsed.as_millis() % 1000, - record.level(), + "{:.3} {} {}", + bold.value(elapsed.as_secs_f32()), + level_style.value(record.level()), record.args() ) }); From 0d43dea1213b85b77c54e9c39f5bec98665d52d7 Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 11:29:31 +0200 Subject: [PATCH 3/9] Use variables in format strings where possible. Nit: Remove trailing dots to make messages more consistent. --- .clippy.toml | 1 + neqo-bin/src/client/http09.rs | 3 +- neqo-bin/src/client/http3.rs | 4 +- neqo-bin/src/client/mod.rs | 6 +- neqo-bin/src/lib.rs | 3 +- neqo-bin/src/server/http09.rs | 6 +- neqo-bin/src/server/mod.rs | 2 +- neqo-common/src/qlog.rs | 7 +- neqo-crypto/src/agent.rs | 8 +- neqo-crypto/src/agentio.rs | 2 +- neqo-crypto/src/ech.rs | 2 +- neqo-crypto/src/result.rs | 2 +- neqo-crypto/src/secrets.rs | 2 +- neqo-crypto/src/time.rs | 2 +- neqo-http3/src/buffered_send_stream.rs | 2 +- neqo-http3/src/client_events.rs | 4 +- neqo-http3/src/connection.rs | 94 +++++---------- neqo-http3/src/connection_client.rs | 58 +++++----- neqo-http3/src/connection_server.rs | 23 ++-- neqo-http3/src/control_stream_local.rs | 2 +- neqo-http3/src/control_stream_remote.rs | 4 +- .../tests/webtransport/negotiation.rs | 2 +- .../extended_connect/webtransport_session.rs | 8 +- neqo-http3/src/features/mod.rs | 3 +- neqo-http3/src/frames/hframe.rs | 2 +- neqo-http3/src/frames/reader.rs | 9 +- neqo-http3/src/push_controller.rs | 35 +++--- neqo-http3/src/recv_message.rs | 17 ++- neqo-http3/src/send_message.rs | 9 +- neqo-http3/src/server.rs | 6 +- neqo-http3/src/server_events.rs | 20 ++-- neqo-http3/src/stream_type_reader.rs | 6 +- neqo-http3/tests/httpconn.rs | 2 +- neqo-http3/tests/send_message.rs | 2 +- neqo-qpack/src/decoder.rs | 10 +- neqo-qpack/src/decoder_instructions.rs | 4 +- neqo-qpack/src/encoder.rs | 22 ++-- neqo-qpack/src/encoder_instructions.rs | 16 +-- neqo-qpack/src/header_block.rs | 40 +++---- neqo-qpack/src/qpack_send_buf.rs | 2 +- neqo-qpack/src/reader.rs | 4 +- neqo-qpack/src/table.rs | 29 ++--- neqo-transport/src/ackrate.rs | 9 +- neqo-transport/src/addr_valid.rs | 12 +- neqo-transport/src/cc/classic_cc.rs | 22 ++-- neqo-transport/src/connection/dump.rs | 15 +-- neqo-transport/src/connection/mod.rs | 107 ++++++++---------- neqo-transport/src/connection/params.rs | 4 +- neqo-transport/src/connection/tests/cc.rs | 5 +- neqo-transport/src/connection/tests/ecn.rs | 2 +- neqo-transport/src/connection/tests/idle.rs | 4 +- neqo-transport/src/connection/tests/mod.rs | 18 ++- .../src/connection/tests/recovery.rs | 2 +- neqo-transport/src/crypto.rs | 37 +++--- neqo-transport/src/ecn.rs | 13 +-- neqo-transport/src/fc.rs | 5 +- neqo-transport/src/frame.rs | 6 +- neqo-transport/src/lib.rs | 2 +- neqo-transport/src/pace.rs | 4 +- neqo-transport/src/packet/mod.rs | 4 +- neqo-transport/src/packet/retry.rs | 2 +- neqo-transport/src/path.rs | 9 +- neqo-transport/src/pmtud.rs | 8 +- neqo-transport/src/recovery/mod.rs | 39 +++---- neqo-transport/src/recv_stream.rs | 32 ++---- neqo-transport/src/rtt.rs | 2 +- neqo-transport/src/send_stream.rs | 37 ++---- neqo-transport/src/sender.rs | 5 +- neqo-transport/src/server.rs | 6 +- neqo-transport/src/streams.rs | 2 +- neqo-transport/src/tparams.rs | 26 ++--- neqo-transport/src/tracking.rs | 18 +-- neqo-transport/src/version.rs | 4 +- neqo-udp/src/lib.rs | 9 +- test-fixture/src/sim/connection.rs | 10 +- test-fixture/src/sim/mod.rs | 2 +- test-fixture/src/sim/taildrop.rs | 4 +- 77 files changed, 393 insertions(+), 578 deletions(-) diff --git a/.clippy.toml b/.clippy.toml index e928b4be64..1ba78129cb 100644 --- a/.clippy.toml +++ b/.clippy.toml @@ -1,3 +1,4 @@ disallowed-methods = [ { path = "std::slice::from_raw_parts", reason = "see null_safe_slice" } ] +allow-mixed-uninlined-format-args = false diff --git a/neqo-bin/src/client/http09.rs b/neqo-bin/src/client/http09.rs index 7038ed9cc4..36e5343475 100644 --- a/neqo-bin/src/client/http09.rs +++ b/neqo-bin/src/client/http09.rs @@ -302,8 +302,7 @@ impl<'b> Handler<'b> { debug!("READ[{stream_id}]: {} bytes", read_buffer.len()); } else { debug!( - "READ[{}]: {}", - stream_id, + "READ[{stream_id}]: {}", std::str::from_utf8(read_buffer).unwrap() ); } diff --git a/neqo-bin/src/client/http3.rs b/neqo-bin/src/client/http3.rs index d991a67533..74f8b1d20f 100644 --- a/neqo-bin/src/client/http3.rs +++ b/neqo-bin/src/client/http3.rs @@ -303,7 +303,7 @@ impl StreamHandler for DownloadStreamHandler { } else if let Ok(txt) = std::str::from_utf8(data) { debug!("READ[{stream_id}]: {txt}"); } else { - debug!("READ[{}]: 0x{}", stream_id, hex(data)); + debug!("READ[{stream_id}]: 0x{}", hex(data)); } if fin { @@ -345,7 +345,7 @@ impl StreamHandler for UploadStreamHandler { info!("Stream ID: {stream_id:?}, Upload time: {upload_time:?}"); } } else { - panic!("Unexpected data [{}]: 0x{}", stream_id, hex(data)); + panic!("Unexpected data [{stream_id}]: 0x{}", hex(data)); } Ok(true) } diff --git a/neqo-bin/src/client/mod.rs b/neqo-bin/src/client/mod.rs index d057afe1af..82f8994c70 100644 --- a/neqo-bin/src/client/mod.rs +++ b/neqo-bin/src/client/mod.rs @@ -554,7 +554,7 @@ pub async fn client(mut args: Args) -> Res<()> { for ((host, port), mut urls) in urls_by_origin(&args.urls) { if args.resume && urls.len() < 2 { - error!("Resumption to {host} cannot work without at least 2 URLs."); + error!("Resumption to {host} cannot work without at least 2 URLs"); exit(127); } @@ -571,8 +571,8 @@ pub async fn client(mut args: Args) -> Res<()> { let mut socket = crate::udp::Socket::bind(local_addr_for(&remote_addr, 0))?; let real_local = socket.local_addr().unwrap(); info!( - "{} Client connecting: {:?} -> {:?}", - args.shared.alpn, real_local, remote_addr, + "{} Client connecting: {real_local:?} -> {remote_addr:?}", + args.shared.alpn ); let hostname = format!("{host}"); diff --git a/neqo-bin/src/lib.rs b/neqo-bin/src/lib.rs index c3244b46b5..bc9090b5da 100644 --- a/neqo-bin/src/lib.rs +++ b/neqo-bin/src/lib.rs @@ -165,9 +165,8 @@ impl QuicParameters { assert_eq!( opt.is_some(), addr.is_some(), - "unable to resolve '{}' to an {} address", + "unable to resolve '{}' to an {v} address", opt.as_ref().unwrap(), - v, ); addr } diff --git a/neqo-bin/src/server/http09.rs b/neqo-bin/src/server/http09.rs index a1465c50d4..e9d96db403 100644 --- a/neqo-bin/src/server/http09.rs +++ b/neqo-bin/src/server/http09.rs @@ -83,17 +83,17 @@ impl HttpServer { let url_dbg = String::from_utf8(partial.clone()) .unwrap_or_else(|_| format!("", hex(&partial))); if partial.len() < 4096 { - debug!("Saving partial URL: {}", url_dbg); + debug!("Saving partial URL: {url_dbg}"); self.read_state.insert(stream_id, partial); } else { - debug!("Giving up on partial URL {}", url_dbg); + debug!("Giving up on partial URL {url_dbg}"); conn.borrow_mut().stream_stop_sending(stream_id, 0).unwrap(); } } fn stream_readable(&mut self, stream_id: StreamId, conn: &ConnectionRef) { if !stream_id.is_client_initiated() || !stream_id.is_bidi() { - debug!("Stream {} not client-initiated bidi, ignoring", stream_id); + debug!("Stream {stream_id} not client-initiated bidi, ignoring"); return; } let (sz, fin) = conn diff --git a/neqo-bin/src/server/mod.rs b/neqo-bin/src/server/mod.rs index d618de23f0..3095c37e38 100644 --- a/neqo-bin/src/server/mod.rs +++ b/neqo-bin/src/server/mod.rs @@ -361,7 +361,7 @@ pub async fn server(mut args: Args) -> Res<()> { args.shared.quic_parameters.quic_version = vec![Version::Version1]; } } else { - warn!("Both -V and --qns-test were set. Ignoring testcase specific versions."); + warn!("Both -V and --qns-test were set. Ignoring testcase specific versions"); } // These are the default for all tests except http3. diff --git a/neqo-common/src/qlog.rs b/neqo-common/src/qlog.rs index d29a294d16..26507ebf54 100644 --- a/neqo-common/src/qlog.rs +++ b/neqo-common/src/qlog.rs @@ -150,10 +150,7 @@ impl NeqoQlog { { if let Some(inner) = self.inner.borrow_mut().as_mut() { if let Err(e) = f(&mut inner.streamer) { - error!( - "Qlog event generation failed with error {}; closing qlog.", - e - ); + error!("Qlog event generation failed with error {e}; closing qlog"); *self.inner.borrow_mut() = None; } } @@ -169,7 +166,7 @@ impl fmt::Debug for NeqoQlogShared { impl Drop for NeqoQlogShared { fn drop(&mut self) { if let Err(e) = self.streamer.finish_log() { - error!("Error dropping NeqoQlog: {}", e); + error!("Error dropping NeqoQlog: {e}"); } } } diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index 77493536bf..dbdc43b20c 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -108,7 +108,7 @@ fn get_alpn(fd: *mut ssl::PRFileDesc, pre: bool) -> Res> { } _ => None, }; - trace!("[{}] got ALPN {:?}", format!("{fd:p}"), alpn); + trace!("[{}] got ALPN {alpn:?}", format!("{fd:p}")); Ok(alpn) } @@ -434,7 +434,7 @@ impl SecretAgent { /// If NSS can't enable or disable ciphers. pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> { if self.state != HandshakeState::New { - warn!("[{}] Cannot enable ciphers in state {:?}", self, self.state); + warn!("[{self}] Cannot enable ciphers in state {:?}", self.state); return Err(Error::InternalError); } @@ -649,7 +649,7 @@ impl SecretAgent { fn capture_error(&mut self, res: Res) -> Res { if let Err(e) = res { let e = ech::convert_ech_error(self.fd, e); - warn!("[{self}] error: {:?}", e); + warn!("[{self}] error: {e:?}"); self.state = HandshakeState::Failed(e.clone()); Err(e) } else { @@ -734,7 +734,7 @@ impl SecretAgent { if let HandshakeState::Authenticated(ref err) = self.state { let result = secstatus_to_res(unsafe { ssl::SSL_AuthCertificateComplete(self.fd, *err) }); - debug!("[{self}] SSL_AuthCertificateComplete: {:?}", result); + debug!("[{self}] SSL_AuthCertificateComplete: {result:?}"); // This should return SECSuccess, so don't use update_state(). self.capture_error(result)?; } diff --git a/neqo-crypto/src/agentio.rs b/neqo-crypto/src/agentio.rs index 4cdf42acb9..4a89fcbcfd 100644 --- a/neqo-crypto/src/agentio.rs +++ b/neqo-crypto/src/agentio.rs @@ -53,7 +53,7 @@ impl Record { // Shoves this record into the socket, returns true if blocked. pub(crate) fn write(self, fd: *mut ssl::PRFileDesc) -> Res<()> { - trace!("write {:?}", self); + trace!("write {self:?}"); unsafe { ssl::SSL_RecordLayerData( fd, diff --git a/neqo-crypto/src/ech.rs b/neqo-crypto/src/ech.rs index 1be5c3445f..e0635b6ce9 100644 --- a/neqo-crypto/src/ech.rs +++ b/neqo-crypto/src/ech.rs @@ -146,7 +146,7 @@ pub fn generate_keys() -> Res<(PrivateKey, PublicKey)> { assert_eq!(secret_ptr.is_null(), public_ptr.is_null()); let sk = PrivateKey::from_ptr(secret_ptr)?; let pk = PublicKey::from_ptr(public_ptr)?; - trace!("Generated key pair: sk={:?} pk={:?}", sk, pk); + trace!("Generated key pair: sk={sk:?} pk={pk:?}"); Ok((sk, pk)) } diff --git a/neqo-crypto/src/result.rs b/neqo-crypto/src/result.rs index e304fcea7f..4c0c73e6fc 100644 --- a/neqo-crypto/src/result.rs +++ b/neqo-crypto/src/result.rs @@ -83,7 +83,7 @@ mod tests { assert_eq!(code, -12273); assert_eq!( desc, - "SSL received a record with an incorrect Message Authentication Code." + "SSL received a record with an incorrect Message Authentication Code" ); } _ => unreachable!(), diff --git a/neqo-crypto/src/secrets.rs b/neqo-crypto/src/secrets.rs index ac09122f77..fab4a0b8bd 100644 --- a/neqo-crypto/src/secrets.rs +++ b/neqo-crypto/src/secrets.rs @@ -88,7 +88,7 @@ impl Secrets { } fn put(&mut self, dir: SecretDirection, epoch: Epoch, key: SymKey) { - debug!("{:?} secret available for {:?}: {:?}", dir, epoch, key); + debug!("{dir:?} secret available for {epoch:?}: {key:?}"); let keys = match dir { SecretDirection::Read => &mut self.r, SecretDirection::Write => &mut self.w, diff --git a/neqo-crypto/src/time.rs b/neqo-crypto/src/time.rs index 79ddcfbc02..5375833df9 100644 --- a/neqo-crypto/src/time.rs +++ b/neqo-crypto/src/time.rs @@ -233,7 +233,7 @@ mod test { init(); let base = get_base(); let delta_micros = PRTime::try_from(DELTA.as_micros()).unwrap(); - println!("{} - {}", base.prtime, delta_micros); + println!("{} - {delta_micros}", base.prtime); let t = Time::try_from(base.prtime - delta_micros).unwrap(); assert_eq!(Instant::from(t) + DELTA, base.instant); } diff --git a/neqo-http3/src/buffered_send_stream.rs b/neqo-http3/src/buffered_send_stream.rs index 1900920369..f6a824b550 100644 --- a/neqo-http3/src/buffered_send_stream.rs +++ b/neqo-http3/src/buffered_send_stream.rs @@ -69,7 +69,7 @@ impl BufferedStream { if buf.is_empty() { return Ok(0); } - trace!("[{label}] sending data."); + trace!("[{label}] sending data"); let sent = conn.stream_send(*stream_id, &buf[..])?; if sent == 0 { return Ok(0); diff --git a/neqo-http3/src/client_events.rs b/neqo-http3/src/client_events.rs index 61aba8f9f1..994d0e6995 100644 --- a/neqo-http3/src/client_events.rs +++ b/neqo-http3/src/client_events.rs @@ -196,7 +196,7 @@ impl ExtendedConnectEvents for Http3ClientEvents { headers, })); } else { - unreachable!("There is only ExtendedConnectType::WebTransport."); + unreachable!("There is only ExtendedConnectType::WebTransport"); } } @@ -216,7 +216,7 @@ impl ExtendedConnectEvents for Http3ClientEvents { }, )); } else { - unreachable!("There are no other types."); + unreachable!("There are no other types"); } } diff --git a/neqo-http3/src/connection.rs b/neqo-http3/src/connection.rs index 5b0c31466f..175dda6f75 100644 --- a/neqo-http3/src/connection.rs +++ b/neqo-http3/src/connection.rs @@ -353,7 +353,7 @@ impl Http3Connection { /// This function creates and initializes, i.e. send stream type, the control and qpack /// streams. fn initialize_http3_connection(&mut self, conn: &mut Connection) -> Res<()> { - debug!("[{self}] Initialize the http3 connection."); + debug!("[{self}] Initialize the http3 connection"); self.control_stream_local.create(conn)?; self.send_settings(); @@ -362,7 +362,7 @@ impl Http3Connection { } fn send_settings(&mut self) { - debug!("[{self}] Send settings."); + debug!("[{self}] Send settings"); self.control_stream_local.queue_frame(&HFrame::Settings { settings: HSettings::from(&self.local_params), }); @@ -375,7 +375,7 @@ impl Http3Connection { } fn create_qpack_streams(&self, conn: &mut Connection) -> Res<()> { - debug!("[{self}] create_qpack_streams."); + debug!("[{self}] create_qpack_streams"); self.qpack_encoder .borrow_mut() .add_send_stream(conn.stream_create(StreamType::UniDi)?); @@ -459,7 +459,7 @@ impl Http3Connection { /// This is called when a `ConnectionEvent::NewStream` event is received. This register the /// stream with a `NewStreamHeadReader` handler. pub fn add_new_stream(&mut self, stream_id: StreamId) { - trace!("[{self}] A new stream: {}.", stream_id); + trace!("[{self}] A new stream: {stream_id}"); self.recv_streams.insert( stream_id, Box::new(NewStreamHeadReader::new(stream_id, self.role)), @@ -469,7 +469,7 @@ impl Http3Connection { /// The function calls `receive` for a stream. It also deals with the outcome of a read by /// calling `handle_stream_manipulation_output`. fn stream_receive(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res { - trace!("[{self}] Readable stream {}.", stream_id); + trace!("[{self}] Readable stream {stream_id}"); if let Some(recv_stream) = self.recv_streams.get_mut(&stream_id) { let res = recv_stream.receive(conn); @@ -486,7 +486,7 @@ impl Http3Connection { conn: &mut Connection, ) -> Res<()> { for stream_id in unblocked_streams { - debug!("[{self}] Stream {} is unblocked", stream_id); + debug!("[{self}] Stream {stream_id} is unblocked"); if let Some(r) = self.recv_streams.get_mut(&stream_id) { let res = r .http_stream() @@ -552,10 +552,7 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - info!( - "[{self}] Handle a stream reset stream_id={} app_err={}", - stream_id, app_error - ); + info!("[{self}] Handle a stream reset stream_id={stream_id} app_err={app_error}"); self.close_recv(stream_id, CloseType::ResetRemote(app_error), conn) } @@ -566,10 +563,7 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - info!( - "[{self}] Handle stream_stop_sending stream_id={} app_err={}", - stream_id, app_error - ); + info!("[{self}] Handle stream_stop_sending stream_id={stream_id} app_err={app_error}"); if self.send_stream_is_critical(stream_id) { return Err(Error::HttpClosedCriticalStream); @@ -582,7 +576,7 @@ impl Http3Connection { /// This is called when `neqo_transport::Connection` state has been change to take proper /// actions in the HTTP3 layer. pub fn handle_state_change(&mut self, conn: &mut Connection, state: &State) -> Res { - debug!("[{self}] Handle state change {:?}", state); + debug!("[{self}] Handle state change {state:?}"); match state { State::Handshaking => { if self.role == Role::Server @@ -646,7 +640,7 @@ impl Http3Connection { self.recv_streams.clear(); Ok(()) } else { - debug_assert!(false, "Zero rtt rejected in the wrong state."); + debug_assert!(false, "Zero rtt rejected in the wrong state"); Err(Error::HttpInternal(3)) } } @@ -693,13 +687,10 @@ impl Http3Connection { } NewStreamType::Push(push_id) => { - info!( - "[{self}] A new push stream {} push_id:{}.", - stream_id, push_id - ); + info!("[{self}] A new push stream {stream_id} push_id:{push_id}"); } NewStreamType::Decoder => { - debug!("[{self}] A new remote qpack encoder stream {}", stream_id); + debug!("[{self}] A new remote qpack encoder stream {stream_id}"); self.check_stream_exists(Http3StreamType::Decoder)?; self.recv_streams.insert( stream_id, @@ -710,7 +701,7 @@ impl Http3Connection { ); } NewStreamType::Encoder => { - debug!("[{self}] A new remote qpack decoder stream {}", stream_id); + debug!("[{self}] A new remote qpack decoder stream {stream_id}"); self.check_stream_exists(Http3StreamType::Encoder)?; self.recv_streams.insert( stream_id, @@ -721,7 +712,7 @@ impl Http3Connection { ); } NewStreamType::Http(_) => { - info!("[{self}] A new http stream {}.", stream_id); + info!("[{self}] A new http stream {stream_id}"); } NewStreamType::WebTransportStream(session_id) => { let session_exists = self @@ -734,10 +725,7 @@ impl Http3Connection { } // set incoming WebTransport streams to be fair (share bandwidth) conn.stream_fairness(stream_id, true).ok(); - info!( - "[{self}] A new WebTransport stream {} for session {}.", - stream_id, session_id - ); + info!("[{self}] A new WebTransport stream {stream_id} for session {session_id}"); } NewStreamType::Unknown => { conn.stream_stop_sending(stream_id, Error::HttpStreamCreation.code())?; @@ -757,7 +745,7 @@ impl Http3Connection { /// This is called when an application closes the connection. pub fn close(&mut self, error: AppError) { - debug!("[{self}] Close connection error {:?}.", error); + debug!("[{self}] Close connection error {error:?}"); self.state = Http3State::Closing(CloseReason::Application(error)); if (!self.send_streams.is_empty() || !self.recv_streams.is_empty()) && (error == 0) { warn!("close(0) called when streams still active"); @@ -942,7 +930,7 @@ impl Http3Connection { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - debug!("[{self}] read_data from stream {}.", stream_id); + debug!("[{self}] read_data from stream {stream_id}"); let res = self .recv_streams .get_mut(&stream_id) @@ -959,10 +947,7 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - info!( - "[{self}] Reset sending side of stream {} error={}.", - stream_id, error - ); + info!("[{self}] Reset sending side of stream {stream_id} error={error}"); if self.send_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); @@ -979,10 +964,7 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - info!( - "[{self}] Send stop sending for stream {} error={}.", - stream_id, error - ); + info!("[{self}] Send stop sending for stream {stream_id} error={error}"); if self.recv_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); } @@ -1030,7 +1012,7 @@ impl Http3Connection { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] cancel_fetch {} error={}.", stream_id, error); + info!("[{self}] cancel_fetch {stream_id} error={error}"); let send_stream = self.send_streams.get(&stream_id); let recv_stream = self.recv_streams.get(&stream_id); match (send_stream, recv_stream) { @@ -1077,7 +1059,7 @@ impl Http3Connection { /// This is called when an application wants to close the sending side of a stream. pub fn stream_close_send(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { - debug!("[{self}] Close the sending side for stream {}.", stream_id); + debug!("[{self}] Close the sending side for stream {stream_id}"); debug_assert!(self.state.active()); let send_stream = self .send_streams @@ -1145,10 +1127,7 @@ impl Http3Connection { events: Box, accept_res: &WebTransportSessionAcceptAction, ) -> Res<()> { - trace!( - "Respond to WebTransport session with accept={}.", - accept_res - ); + trace!("Respond to WebTransport session with accept={accept_res}"); if !self.webtransport_enabled() { return Err(Error::Unavailable); } @@ -1224,7 +1203,7 @@ impl Http3Connection { error: u32, message: &str, ) -> Res<()> { - trace!("Close WebTransport session {:?}", session_id); + trace!("Close WebTransport session {session_id:?}"); let send_stream = self .send_streams .get_mut(&session_id) @@ -1250,11 +1229,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res { - trace!( - "Create new WebTransport stream session={} type={:?}", - session_id, - stream_type - ); + trace!("Create new WebTransport stream session={session_id} type={stream_type:?}"); let wt = self .recv_streams @@ -1291,11 +1266,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res<()> { - trace!( - "Create new WebTransport stream session={} stream_id={}", - session_id, - stream_id - ); + trace!("Create new WebTransport stream session={session_id} stream_id={stream_id}"); let wt = self .recv_streams @@ -1388,7 +1359,7 @@ impl Http3Connection { /// `PriorityUpdateRequestPush` which handling is specific to the client and server, we must /// give them to the specific client/server handler. fn handle_control_frame(&mut self, f: HFrame) -> Res> { - debug!("[{self}] Handle a control frame {:?}", f); + debug!("[{self}] Handle a control frame {f:?}"); if !matches!(f, HFrame::Settings { .. }) && !matches!( self.settings_state, @@ -1419,7 +1390,7 @@ impl Http3Connection { } fn handle_settings(&mut self, new_settings: HSettings) -> Res<()> { - debug!("[{self}] Handle SETTINGS frame."); + debug!("[{self}] Handle SETTINGS frame"); match &self.settings_state { Http3RemoteSettingsState::NotReceived => { self.set_qpack_settings(&new_settings)?; @@ -1442,10 +1413,7 @@ impl Http3Connection { } if zero_rtt_value > new_value { error!( - "[{self}] The new({}) and the old value({}) of setting {:?} do not match", - new_value, - zero_rtt_value, - st + "[{self}] The new({new_value}) and the old value({zero_rtt_value}) of setting {st:?} do not match" ); return Err(Error::HttpSettings); } @@ -1464,7 +1432,7 @@ impl Http3Connection { } } if qpack_changed { - debug!("[{self}] Settings after zero rtt differ."); + debug!("[{self}] Settings after zero rtt differ"); self.set_qpack_settings(&(new_settings))?; } self.settings_state = Http3RemoteSettingsState::Received(new_settings); @@ -1563,7 +1531,7 @@ impl Http3Connection { let (recv, send) = wt.borrow_mut().take_sub_streams(); for id in recv { - trace!("Remove the extended connect sub receiver stream {}", id); + trace!("Remove the extended connect sub receiver stream {id}"); // Use CloseType::ResetRemote so that an event will be sent. CloseType::LocalError would // have the same effect. if let Some(mut s) = self.recv_streams.remove(&id) { @@ -1572,7 +1540,7 @@ impl Http3Connection { mem::drop(conn.stream_stop_sending(id, Error::HttpRequestCancelled.code())); } for id in send { - trace!("Remove the extended connect sub send stream {}", id); + trace!("Remove the extended connect sub send stream {id}"); if let Some(mut s) = self.send_streams.remove(&id) { s.handle_stop_sending(CloseType::ResetRemote(Error::HttpRequestCancelled.code())); } diff --git a/neqo-http3/src/connection_client.rs b/neqo-http3/src/connection_client.rs index 568b4cb214..7a9d87c2c2 100644 --- a/neqo-http3/src/connection_client.rs +++ b/neqo-http3/src/connection_client.rs @@ -145,7 +145,7 @@ const fn alpn_from_quic_version(version: Version) -> &'static str { /// ); /// } /// Http3ClientEvent::DataReadable { stream_id } => { -/// println!("New data available on stream {}", stream_id); +/// println!("New data available on stream {stream_id}"); /// let mut buf = [0; 100]; /// let (amount, fin) = client.read_data(now(), stream_id, &mut buf).unwrap(); /// println!("Read {:?} bytes from stream {:?} [fin={?}]", @@ -490,7 +490,7 @@ impl Http3Client { where S: AsRef + Display, { - info!("[{self}] Close the connection error={} msg={}.", error, msg); + info!("[{self}] Close the connection error={error} msg={msg}"); if !matches!( self.base_handler.state, Http3State::Closing(_) | Http3State::Closed(_) @@ -578,7 +578,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn cancel_fetch(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - info!("[{self}] reset_stream {} error={}.", stream_id, error); + info!("[{self}] reset_stream {stream_id} error={error}"); self.base_handler .cancel_fetch(stream_id, error, &mut self.conn) } @@ -589,7 +589,7 @@ impl Http3Client { /// /// An error will be return if stream does not exist. pub fn stream_close_send(&mut self, stream_id: StreamId) -> Res<()> { - debug!("[{self}] Close sending side stream={}.", stream_id); + debug!("[{self}] Close sending side stream={stream_id}"); self.base_handler .stream_close_send(&mut self.conn, stream_id) } @@ -598,7 +598,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn stream_reset_send(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - info!("[{self}] stream_reset_send {} error={}.", stream_id, error); + info!("[{self}] stream_reset_send {stream_id} error={error}"); self.base_handler .stream_reset_send(&mut self.conn, stream_id, error) } @@ -607,10 +607,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn stream_stop_sending(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - info!( - "[{self}] stream_stop_sending {} error={}.", - stream_id, error - ); + info!("[{self}] stream_stop_sending {stream_id} error={error}"); self.base_handler .stream_stop_sending(&mut self.conn, stream_id, error) } @@ -629,8 +626,7 @@ impl Http3Client { /// supplied. pub fn send_data(&mut self, stream_id: StreamId, buf: &[u8]) -> Res { info!( - "[{self}] end_data from stream {} sending {} bytes.", - stream_id, + "[{self}] end_data from stream {stream_id} sending {} bytes", buf.len() ); self.base_handler @@ -653,7 +649,7 @@ impl Http3Client { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - debug!("[{self}] read_data from stream {}.", stream_id); + debug!("[{self}] read_data from stream {stream_id}"); let res = self.base_handler.read_data(&mut self.conn, stream_id, buf); if let Err(e) = &res { if e.connection_error() { @@ -778,7 +774,7 @@ impl Http3Client { buf: &[u8], id: impl Into, ) -> Res<()> { - trace!("webtransport_send_datagram session:{:?}", session_id); + trace!("webtransport_send_datagram session:{session_id:?}"); self.base_handler .webtransport_send_datagram(session_id, &mut self.conn, buf, id) } @@ -857,7 +853,7 @@ impl Http3Client { /// This function combines `process_input` and `process_output` function. pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - trace!("[{self}] Process."); + trace!("[{self}] Process"); if let Some(d) = dgram { self.process_input(d, now); } @@ -898,7 +894,7 @@ impl Http3Client { /// the QUC layer and calls `Http3Connection::process_sending` to ensure that HTTP/3 layer /// data, e.g. control frames, are sent. fn process_http3(&mut self, now: Instant) { - trace!("[{self}] Process http3 internal."); + trace!("[{self}] Process http3 internal"); match self.base_handler.state() { Http3State::ZeroRtt | Http3State::Connected | Http3State::GoingAway(..) => { let res = self.check_connection_events(); @@ -947,7 +943,7 @@ impl Http3Client { /// [2]: ../neqo_transport/struct.ConnectionEvents.html /// [3]: ../neqo_transport/struct.Connection.html#method.process_output pub fn process_output(&mut self, now: Instant) -> Output { - trace!("[{self}] Process output."); + trace!("[{self}] Process output"); // Maybe send() stuff on http3-managed streams self.process_http3(now); @@ -965,7 +961,7 @@ impl Http3Client { fn check_result(&mut self, now: Instant, res: &Res) -> bool { match &res { Err(Error::HttpGoaway) => { - info!("[{self}] Connection error: goaway stream_id increased."); + info!("[{self}] Connection error: goaway stream_id increased"); self.close( now, Error::HttpGeneralProtocol.code(), @@ -974,7 +970,7 @@ impl Http3Client { true } Err(e) => { - info!("[{self}] Connection error: {}.", e); + info!("[{self}] Connection error: {e}"); self.close(now, e.code(), format!("{e}")); true } @@ -997,9 +993,9 @@ impl Http3Client { /// [2]: ../neqo_transport/enum.ConnectionEvent.html /// [3]: ../neqo_transport/enum.ConnectionEvent.html#variant.RecvStreamReadable fn check_connection_events(&mut self) -> Res<()> { - trace!("[{self}] Check connection events."); + trace!("[{self}] Check connection events"); while let Some(e) = self.conn.next_event() { - debug!("[{self}] check_connection_events - event {:?}.", e); + debug!("[{self}] check_connection_events - event {e:?}"); match e { ConnectionEvent::NewStream { stream_id } => { // During this event we only add a new stream to the Http3Connection stream @@ -1123,7 +1119,7 @@ impl Http3Client { HFrame::Goaway { stream_id } => self.handle_goaway(stream_id), _ => { unreachable!( - "we should only put MaxPushId, Goaway and PriorityUpdates into control_frames." + "we should only put MaxPushId, Goaway and PriorityUpdates into control_frames" ); } }?; @@ -1181,7 +1177,7 @@ impl Http3Client { } fn handle_goaway(&mut self, goaway_stream_id: StreamId) -> Res<()> { - info!("[{self}] handle_goaway {}", goaway_stream_id); + info!("[{self}] handle_goaway {goaway_stream_id}"); if goaway_stream_id.is_uni() || goaway_stream_id.is_server_initiated() { return Err(Error::HttpId); @@ -1198,7 +1194,7 @@ impl Http3Client { *stream_id = goaway_stream_id; } Http3State::Closing(..) | Http3State::Closed(..) => {} - _ => unreachable!("Should not receive Goaway frame in this state."), + _ => unreachable!("Should not receive Goaway frame in this state"), } // Issue reset events for streams >= goaway stream id @@ -1474,7 +1470,7 @@ mod tests { pub fn create_control_stream(&mut self) { // Create control stream let control = self.conn.stream_create(StreamType::UniDi).unwrap(); - trace!("[TestServer] control stream: {}", control); + trace!("[TestServer] control stream: {control}"); self.control_stream_id = Some(control); // Send stream type on the control stream. assert_eq!( @@ -3116,7 +3112,7 @@ mod tests { stop_sending = true; } Http3ClientEvent::Reset { .. } => { - panic!("We should not get StopSending."); + panic!("We should not get StopSending"); } Http3ClientEvent::HeaderReady { .. } | Http3ClientEvent::DataReadable { .. } => { panic!("We should not get any headers or data"); @@ -3250,7 +3246,7 @@ mod tests { stop_sending = true; } Http3ClientEvent::Reset { .. } => { - panic!("We should not get StopSending."); + panic!("We should not get StopSending"); } Http3ClientEvent::HeaderReady { .. } | Http3ClientEvent::DataReadable { .. } => { header_ready = true; @@ -3297,7 +3293,7 @@ mod tests { while let Some(e) = client.next_event() { match e { Http3ClientEvent::StopSending { .. } => { - panic!("We should not get StopSending."); + panic!("We should not get StopSending"); } Http3ClientEvent::Reset { stream_id, @@ -4158,7 +4154,7 @@ mod tests { assert_eq!(client.state(), Http3State::Initializing); client .enable_resumption(now(), &token) - .expect("Set resumption token."); + .expect("Set resumption token"); assert_eq!(client.state(), Http3State::ZeroRtt); let zerortt_event = |e| matches!(e, Http3ClientEvent::StateChange(Http3State::ZeroRtt)); @@ -4279,7 +4275,7 @@ mod tests { assert_eq!(client.state(), Http3State::Initializing); client .enable_resumption(now(), &token) - .expect("Set resumption token."); + .expect("Set resumption token"); let zerortt_event = |e| matches!(e, Http3ClientEvent::StateChange(Http3State::ZeroRtt)); assert!(client.events().any(zerortt_event)); @@ -4340,7 +4336,7 @@ mod tests { assert_eq!(client.state(), Http3State::Initializing); client .enable_resumption(now(), &token) - .expect("Set resumption token."); + .expect("Set resumption token"); assert_eq!(client.state(), Http3State::ZeroRtt); let out = client.process_output(now()); @@ -7068,7 +7064,7 @@ mod tests { assert_eq!(client.state(), Http3State::Initializing); client .enable_resumption(now(), &token) - .expect("Set resumption token."); + .expect("Set resumption token"); assert_eq!(client.state(), Http3State::ZeroRtt); let zerortt_event = |e| matches!(e, Http3ClientEvent::StateChange(Http3State::ZeroRtt)); diff --git a/neqo-http3/src/connection_server.rs b/neqo-http3/src/connection_server.rs index 0b88bf1200..218606699a 100644 --- a/neqo-http3/src/connection_server.rs +++ b/neqo-http3/src/connection_server.rs @@ -103,7 +103,7 @@ impl Http3ServerHandler { /// /// An error will be returned if stream does not exist. pub fn stream_close_send(&mut self, stream_id: StreamId, conn: &mut Connection) -> Res<()> { - debug!("[{self}] Close sending side stream={}.", stream_id); + debug!("[{self}] Close sending side stream={stream_id}"); self.base_handler.stream_close_send(conn, stream_id)?; self.needs_processing = true; Ok(()) @@ -121,7 +121,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] cancel_fetch {} error={}.", stream_id, error); + info!("[{self}] cancel_fetch {stream_id} error={error}"); self.needs_processing = true; self.base_handler.cancel_fetch(stream_id, error, conn) } @@ -132,10 +132,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!( - "[{self}] stream_stop_sending {} error={}.", - stream_id, error - ); + info!("[{self}] stream_stop_sending {stream_id} error={error}"); self.needs_processing = true; self.base_handler .stream_stop_sending(conn, stream_id, error) @@ -147,7 +144,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] stream_reset_send {} error={}.", stream_id, error); + info!("[{self}] stream_reset_send {stream_id} error={error}"); self.needs_processing = true; self.base_handler.stream_reset_send(conn, stream_id, error) } @@ -219,7 +216,7 @@ impl Http3ServerHandler { /// Process HTTTP3 layer. pub fn process_http3(&mut self, conn: &mut Connection, now: Instant) { - trace!("[{self}] Process http3 internal."); + trace!("[{self}] Process http3 internal"); if matches!(self.base_handler.state(), Http3State::Closed(..)) { return; } @@ -258,7 +255,7 @@ impl Http3ServerHandler { } fn close(&mut self, conn: &mut Connection, now: Instant, err: &Error) { - info!("[{self}] Connection error: {}.", err); + info!("[{self}] Connection error: {err}"); conn.close(now, err.code(), format!("{err}")); self.base_handler.close(err.code()); self.events @@ -267,9 +264,9 @@ impl Http3ServerHandler { // If this return an error the connection must be closed. fn check_connection_events(&mut self, conn: &mut Connection, now: Instant) -> Res<()> { - trace!("[{self}] Check connection events."); + trace!("[{self}] Check connection events"); while let Some(e) = conn.next_event() { - debug!("[{self}] check_connection_events - event {e:?}."); + debug!("[{self}] check_connection_events - event {e:?}"); match e { ConnectionEvent::NewStream { stream_id } => { self.base_handler.add_new_stream(stream_id); @@ -391,7 +388,7 @@ impl Http3ServerHandler { Ok(()) } _ => unreachable!( - "we should only put MaxPushId, Goaway and PriorityUpdates into control_frames." + "we should only put MaxPushId, Goaway and PriorityUpdates into control_frames" ), }?; } @@ -415,7 +412,7 @@ impl Http3ServerHandler { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - debug!("[{self}] read_data from stream {}.", stream_id); + debug!("[{self}] read_data from stream {stream_id}"); let res = self.base_handler.read_data(conn, stream_id, buf); if let Err(e) = &res { if e.connection_error() { diff --git a/neqo-http3/src/control_stream_local.rs b/neqo-http3/src/control_stream_local.rs index a7a591e041..d41f2a09d5 100644 --- a/neqo-http3/src/control_stream_local.rs +++ b/neqo-http3/src/control_stream_local.rs @@ -93,7 +93,7 @@ impl ControlStreamLocal { /// Create a control stream. pub fn create(&mut self, conn: &mut Connection) -> Res<()> { - trace!("[{self}] Create a control stream."); + trace!("[{self}] Create a control stream"); self.stream.init(conn.stream_create(StreamType::UniDi)?); self.stream .buffer(&[u8::try_from(HTTP3_UNI_STREAM_TYPE_CONTROL).unwrap()]); diff --git a/neqo-http3/src/control_stream_remote.rs b/neqo-http3/src/control_stream_remote.rs index 2f0c43e130..8ebb82c307 100644 --- a/neqo-http3/src/control_stream_remote.rs +++ b/neqo-http3/src/control_stream_remote.rs @@ -36,7 +36,7 @@ impl ControlStreamRemote { /// Check if a stream is the control stream and read received data. pub fn receive_single(&mut self, conn: &mut Connection) -> Res> { - debug!("[{self}] Receiving data."); + debug!("[{self}] Receiving data"); match self .frame_reader .receive(&mut StreamReaderConnectionWrapper::new( @@ -45,7 +45,7 @@ impl ControlStreamRemote { ))? { (_, true) => Err(Error::HttpClosedCriticalStream), (s, false) => { - debug!("[{self}] received {:?}", s); + debug!("[{self}] received {s:?}"); Ok(s) } } diff --git a/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs b/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs index 82ec1328a7..fdcc6ba457 100644 --- a/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs +++ b/neqo-http3/src/features/extended_connect/tests/webtransport/negotiation.rs @@ -105,7 +105,7 @@ fn zero_rtt( let mut server = default_http3_server(Http3Parameters::default().webtransport(server_resumed)); client .enable_resumption(now(), &token) - .expect("Set resumption token."); + .expect("Set resumption token"); assert_eq!(client.state(), Http3State::ZeroRtt); exchange_packets(&mut client, &mut server); diff --git a/neqo-http3/src/features/extended_connect/webtransport_session.rs b/neqo-http3/src/features/extended_connect/webtransport_session.rs index d81c0c62f9..f8500e7ce9 100644 --- a/neqo-http3/src/features/extended_connect/webtransport_session.rs +++ b/neqo-http3/src/features/extended_connect/webtransport_session.rs @@ -230,11 +230,7 @@ impl WebTransportSession { if let Some((headers, interim, fin)) = self.stream_event_listener.borrow_mut().get_headers() { - trace!( - "ExtendedConnect response headers {:?}, fin={}", - headers, - fin - ); + trace!("ExtendedConnect response headers {headers:?}, fin={fin}"); if interim { if fin { @@ -347,7 +343,7 @@ impl WebTransportSession { &mut self.control_stream_recv, )) .map_err(|_| Error::HttpGeneralProtocolStream)?; - trace!("[{self}] Received frame: {:?} fin={}", f, fin); + trace!("[{self}] Received frame: {f:?} fin={fin}"); if let Some(WebTransportFrame::CloseSession { error, message }) = f { self.events.session_end( ExtendedConnectType::WebTransport, diff --git a/neqo-http3/src/features/mod.rs b/neqo-http3/src/features/mod.rs index b7924782d7..0bb7d4d7b7 100644 --- a/neqo-http3/src/features/mod.rs +++ b/neqo-http3/src/features/mod.rs @@ -63,8 +63,7 @@ impl NegotiationState { } = self { trace!( - "set_negotiated {:?} to {}", - feature_type, + "set_negotiated {feature_type:?} to {}", settings.get(*feature_type) ); let cb = mem::take(listener); diff --git a/neqo-http3/src/frames/hframe.rs b/neqo-http3/src/frames/hframe.rs index 707242ae48..e32360227b 100644 --- a/neqo-http3/src/frames/hframe.rs +++ b/neqo-http3/src/frames/hframe.rs @@ -172,7 +172,7 @@ impl FrameDecoder for HFrame { } else if let Some(payload) = data { let mut dec = Decoder::from(payload); Ok(match frame_type { - H3_FRAME_TYPE_DATA => unreachable!("DATA frame has been handled already."), + H3_FRAME_TYPE_DATA => unreachable!("DATA frame has been handled already"), H3_FRAME_TYPE_HEADERS => Some(Self::Headers { header_block: dec.decode_remainder().to_vec(), }), diff --git a/neqo-http3/src/frames/reader.rs b/neqo-http3/src/frames/reader.rs index 7fc92b90b0..fc54609c07 100644 --- a/neqo-http3/src/frames/reader.rs +++ b/neqo-http3/src/frames/reader.rs @@ -174,7 +174,7 @@ impl FrameReader { { (0, f) => (None, false, f), (amount, f) => { - trace!("FrameReader::receive: reading {} byte, fin={}", amount, f); + trace!("FrameReader::receive: reading {amount} byte, fin={f}"); (self.consume::(Decoder::from(&buf[..amount]))?, true, f) } }; @@ -204,16 +204,15 @@ impl FrameReader { match &mut self.state { FrameReaderState::GetType { decoder } => { if let Some(v) = decoder.consume(&mut input) { - trace!("FrameReader::receive: read frame type {}", v); + trace!("FrameReader::receive: read frame type {v}"); self.frame_type_decoded::(HFrameType(v))?; } } FrameReaderState::GetLength { decoder } => { if let Some(len) = decoder.consume(&mut input) { trace!( - "FrameReader::receive: frame type {:?} length {}", - self.frame_type, - len + "FrameReader::receive: frame type {:?} length {len}", + self.frame_type ); return self.frame_length_decoded::(len); } diff --git a/neqo-http3/src/push_controller.rs b/neqo-http3/src/push_controller.rs index dc73f5e22e..41774f8436 100644 --- a/neqo-http3/src/push_controller.rs +++ b/neqo-http3/src/push_controller.rs @@ -187,9 +187,7 @@ impl PushController { new_headers: Vec
, ) -> Res<()> { trace!( - "[{self}] New push promise push_id={} headers={:?} max_push={}", - push_id, - new_headers, + "[{self}] New push promise push_id={push_id} headers={new_headers:?} max_push={}", self.max_concurent_push ); @@ -197,7 +195,7 @@ impl PushController { match self.push_streams.get_mut(push_id) { None => { - trace!("Push has been closed already {}.", push_id); + trace!("Push has been closed already {push_id}"); Ok(()) } Some(push_state) => match push_state { @@ -237,17 +235,12 @@ impl PushController { } pub fn add_new_push_stream(&mut self, push_id: u64, stream_id: StreamId) -> Res { - trace!( - "A new push stream with push_id={} stream_id={}", - push_id, - stream_id - ); - + trace!("A new push stream with push_id={push_id} stream_id={stream_id}"); self.check_push_id(push_id)?; self.push_streams.get_mut(push_id).map_or_else( || { - info!("Push has been closed already."); + info!("Push has been closed already"); Ok(false) }, |push_state| match push_state { @@ -269,7 +262,7 @@ impl PushController { // The following state have already have a push stream: // PushState::OnlyPushStream | PushState::Active _ => { - error!("Duplicate push stream."); + error!("Duplicate push stream"); Err(Error::HttpId) } }, @@ -279,7 +272,7 @@ impl PushController { fn check_push_id(&self, push_id: u64) -> Res<()> { // Check if push id is greater than what we allow. if push_id > self.current_max_push_id { - error!("Push id is greater than current_max_push_id."); + error!("Push id is greater than current_max_push_id"); Err(Error::HttpId) } else { Ok(()) @@ -292,13 +285,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - trace!("CANCEL_PUSH frame has been received, push_id={}", push_id); + trace!("CANCEL_PUSH frame has been received, push_id={push_id}"); self.check_push_id(push_id)?; match self.push_streams.close(push_id) { None => { - trace!("Push has already been closed (push_id={}).", push_id); + trace!("Push has already been closed (push_id={push_id})"); Ok(()) } Some(ps) => match ps { @@ -325,7 +318,7 @@ impl PushController { } pub fn close(&mut self, push_id: u64) { - trace!("Push stream has been closed."); + trace!("Push stream has been closed"); if let Some(push_state) = self.push_streams.close(push_id) { debug_assert!(matches!(push_state, PushState::Active { .. })); } else { @@ -339,13 +332,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - trace!("Cancel push_id={}", push_id); + trace!("Cancel push_id={push_id}"); self.check_push_id(push_id)?; match self.push_streams.get(push_id) { None => { - trace!("Push has already been closed."); + trace!("Push has already been closed"); // If we have some events for the push_id in the event queue, the caller still does // not not know that the push has been closed. Otherwise return // InvalidStreamId. @@ -378,7 +371,7 @@ impl PushController { } pub fn push_stream_reset(&mut self, push_id: u64, close_type: CloseType) { - trace!("Push stream has been reset, push_id={}", push_id); + trace!("Push stream has been reset, push_id={push_id}"); if let Some(push_state) = self.push_streams.get(push_id) { match push_state { @@ -397,7 +390,7 @@ impl PushController { _ => { debug_assert!( false, - "Reset cannot actually happen because we do not have a stream." + "Reset cannot actually happen because we do not have a stream" ); } } @@ -438,7 +431,7 @@ impl PushController { pub fn new_stream_event(&mut self, push_id: u64, event: Http3ClientEvent) { match self.push_streams.get_mut(push_id) { None => { - debug_assert!(false, "Push has been closed already."); + debug_assert!(false, "Push has been closed already"); } Some(PushState::OnlyPushStream { events, .. }) => { events.push(event); diff --git a/neqo-http3/src/recv_message.rs b/neqo-http3/src/recv_message.rs index 4ad2fda5ac..8e8180b0c4 100644 --- a/neqo-http3/src/recv_message.rs +++ b/neqo-http3/src/recv_message.rs @@ -127,7 +127,7 @@ impl RecvMessage { RecvMessageState::WaitingForFinAfterTrailers {..} => { return Err(Error::HttpFrameUnexpected); } - _ => unreachable!("This functions is only called in WaitingForResponseHeaders | WaitingForData | WaitingForFinAfterTrailers state.") + _ => unreachable!("This functions is only called in WaitingForResponseHeaders | WaitingForData | WaitingForFinAfterTrailers state") } Ok(()) } @@ -147,13 +147,13 @@ impl RecvMessage { }; } } - _ => unreachable!("This functions is only called in WaitingForResponseHeaders | WaitingForData | WaitingForFinAfterTrailers state.") + _ => unreachable!("This functions is only called in WaitingForResponseHeaders | WaitingForData | WaitingForFinAfterTrailers state") } Ok(()) } fn add_headers(&mut self, mut headers: Vec
, fin: bool) -> Res<()> { - trace!("[{self}] Add new headers fin={}", fin); + trace!("[{self}] Add new headers fin={fin}"); let interim = match self.message_type { MessageType::Request => false, MessageType::Response => is_interim(&headers)?, @@ -216,7 +216,7 @@ impl RecvMessage { self.conn_events.data_readable(self.get_stream_info()); } } - _ => unreachable!("Closing an already closed transaction."), + _ => unreachable!("Closing an already closed transaction"), } if !matches!(self.state, RecvMessageState::Closed) { self.state = RecvMessageState::ClosePending; @@ -255,7 +255,7 @@ impl RecvMessage { fn receive_internal(&mut self, conn: &mut Connection, post_readable_event: bool) -> Res<()> { loop { - debug!("[{self}] state={:?}.", self.state); + debug!("[{self}] state={:?}", self.state); match &mut self.state { // In the following 3 states we need to read frames. RecvMessageState::WaitingForResponseHeaders { frame_reader } @@ -271,8 +271,7 @@ impl RecvMessage { (None, false) => break Ok(()), (Some(frame), fin) => { debug!( - "[{self}] A new frame has been received: {:?}; state={:?} fin={}", - frame, self.state, fin, + "[{self}] A new frame has been received: {frame:?}; state={:?} fin={fin}", self.state, ); match frame { HFrame::Headers { header_block } => { @@ -307,7 +306,7 @@ impl RecvMessage { && !self.blocked_push_promise.is_empty() { info!( - "[{self}] decoding header is blocked waiting for a push_promise header block." + "[{self}] decoding header is blocked waiting for a push_promise header block" ); break Ok(()); } @@ -325,7 +324,7 @@ impl RecvMessage { break Ok(()); } } else { - info!("[{self}] decoding header is blocked."); + info!("[{self}] decoding header is blocked"); break Ok(()); } } diff --git a/neqo-http3/src/send_message.rs b/neqo-http3/src/send_message.rs index a06ab2fc98..ca3522ef50 100644 --- a/neqo-http3/src/send_message.rs +++ b/neqo-http3/src/send_message.rs @@ -120,7 +120,7 @@ impl SendMessage { encoder: Rc>, conn_events: Box, ) -> Self { - debug!("Create a request stream_id={}", stream_id); + debug!("Create a request stream_id={stream_id}"); Self { state: MessageState::WaitingForHeaders, message_type, @@ -201,10 +201,7 @@ impl SendStream for SendMessage { min(buf.len(), available - 9) }; - debug!( - "[{self}] send_request_body: available={} to_send={}.", - available, to_send - ); + debug!("[{self}] send_request_body: available={available} to_send={to_send}"); let data_frame = HFrame::Data { len: to_send as u64, @@ -249,7 +246,7 @@ impl SendStream for SendMessage { fn send(&mut self, conn: &mut Connection) -> Res<()> { let sent = Error::map_error(self.stream.send_buffer(conn), Error::HttpInternal(5))?; - trace!("[{self}] {} bytes sent", sent); + trace!("[{self}] {sent} bytes sent"); if !self.stream.has_buffered_data() { if self.state.done() { Error::map_error( diff --git a/neqo-http3/src/server.rs b/neqo-http3/src/server.rs index 9ba8dd6a52..27db19e8e8 100644 --- a/neqo-http3/src/server.rs +++ b/neqo-http3/src/server.rs @@ -120,13 +120,13 @@ impl Http3Server { } pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - trace!("[{self}] Process."); + trace!("[{self}] Process"); let out = self.server.process(dgram, now); self.process_http3(now); // If we do not that a dgram already try again after process_http3. match out { Output::Datagram(d) => { - trace!("[{self}] Send packet: {:?}", d); + trace!("[{self}] Send packet: {d:?}"); Output::Datagram(d) } _ => self.server.process(Option::::None, now), @@ -135,7 +135,7 @@ impl Http3Server { /// Process HTTP3 layer. fn process_http3(&mut self, now: Instant) { - trace!("[{self}] Process http3 internal."); + trace!("[{self}] Process http3 internal"); // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable // types. #[allow(clippy::mutable_key_type)] diff --git a/neqo-http3/src/server_events.rs b/neqo-http3/src/server_events.rs index cf04364d84..235aab9081 100644 --- a/neqo-http3/src/server_events.rs +++ b/neqo-http3/src/server_events.rs @@ -36,7 +36,7 @@ pub struct StreamHandler { impl ::std::fmt::Display for StreamHandler { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let conn: &Connection = &self.conn.borrow(); - write!(f, "conn={} stream_info={:?}", conn, self.stream_info) + write!(f, "conn={conn} stream_info={:?}", self.stream_info) } } @@ -116,9 +116,8 @@ impl StreamHandler { /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_stop_sending(&self, app_error: AppError) -> Res<()> { debug!( - "[{self}] stop sending stream_id:{} error:{}.", - self.stream_info.stream_id(), - app_error + "[{self}] stop sending stream_id:{} error:{app_error}", + self.stream_info.stream_id() ); self.handler.borrow_mut().stream_stop_sending( self.stream_info.stream_id(), @@ -134,9 +133,8 @@ impl StreamHandler { /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_reset_send(&self, app_error: AppError) -> Res<()> { debug!( - "[{self}] reset send stream_id:{} error:{}.", - self.stream_info.stream_id(), - app_error + "[{self}] reset send stream_id:{} error:{app_error}", + self.stream_info.stream_id() ); self.handler.borrow_mut().stream_reset_send( self.stream_info.stream_id(), @@ -151,7 +149,7 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore pub fn cancel_fetch(&self, app_error: AppError) -> Res<()> { - debug!("[{self}] reset error:{}.", app_error); + debug!("[{self}] reset error:{app_error}"); self.handler.borrow_mut().cancel_fetch( self.stream_info.stream_id(), app_error, @@ -201,7 +199,7 @@ impl Http3OrWebTransportStream { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn send_data(&self, data: &[u8]) -> Res { - debug!("[{self}] Set new response."); + debug!("[{self}] Set new response"); self.stream_handler.send_data(data) } @@ -211,7 +209,7 @@ impl Http3OrWebTransportStream { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_close_send(&self) -> Res<()> { - debug!("[{self}] Set new response."); + debug!("[{self}] Set new response"); self.stream_handler.stream_close_send() } } @@ -282,7 +280,7 @@ impl WebTransportRequest { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn response(&self, accept: &WebTransportSessionAcceptAction) -> Res<()> { - debug!("[{self}] Set a response for a WebTransport session."); + debug!("[{self}] Set a response for a WebTransport session"); self.stream_handler .handler .borrow_mut() diff --git a/neqo-http3/src/stream_type_reader.rs b/neqo-http3/src/stream_type_reader.rs index 89767d6bd7..39889094b1 100644 --- a/neqo-http3/src/stream_type_reader.rs +++ b/neqo-http3/src/stream_type_reader.rs @@ -137,7 +137,7 @@ impl NewStreamHeadReader { return Ok(None); }; - trace!("Decoded uint {}", output); + trace!("Decoded uint {output}"); match self { Self::ReadType { role, stream_id, .. @@ -178,7 +178,7 @@ impl NewStreamHeadReader { Self::ReadId { stream_type, .. } => { let is_push = *stream_type == HTTP3_UNI_STREAM_TYPE_PUSH; *self = Self::Done; - trace!("New Stream stream push_id={}", output); + trace!("New Stream stream push_id={output}"); if fin { return Err(Error::HttpGeneralProtocol); } @@ -204,7 +204,7 @@ impl NewStreamHeadReader { Some(NewStreamType::Http(_)) => Err(Error::HttpFrame), Some(NewStreamType::Unknown) => Ok(decoded), Some(NewStreamType::Push(_) | NewStreamType::WebTransportStream(_)) => { - unreachable!("PushStream and WebTransport are mapped to None at this stage.") + unreachable!("PushStream and WebTransport are mapped to None at this stage") } } } diff --git a/neqo-http3/tests/httpconn.rs b/neqo-http3/tests/httpconn.rs index 17e60ad233..96460f10d1 100644 --- a/neqo-http3/tests/httpconn.rs +++ b/neqo-http3/tests/httpconn.rs @@ -434,7 +434,7 @@ fn zerortt() { let mut hconn_c = default_http3_client(); hconn_c .enable_resumption(now(), &token) - .expect("Set resumption token."); + .expect("Set resumption token"); let mut hconn_s = default_http3_server(); // Create a request. diff --git a/neqo-http3/tests/send_message.rs b/neqo-http3/tests/send_message.rs index 19a47cde7c..e36e5dc982 100644 --- a/neqo-http3/tests/send_message.rs +++ b/neqo-http3/tests/send_message.rs @@ -23,7 +23,7 @@ fn response_header_no_data() -> &'static Vec
{ fn response_header_103() -> &'static Vec
{ static HEADERS: OnceLock> = OnceLock::new(); - HEADERS.get_or_init(|| vec![Header::new(":status", "103"), Header::new("link", "...")]) + HEADERS.get_or_init(|| vec![Header::new(":status", "103"), Header::new("link", "..")]) } fn exchange_packets(client: &mut Http3Client, server: &mut Http3Server) { diff --git a/neqo-qpack/src/decoder.rs b/neqo-qpack/src/decoder.rs index 71e86804fe..cfad900493 100644 --- a/neqo-qpack/src/decoder.rs +++ b/neqo-qpack/src/decoder.rs @@ -41,7 +41,7 @@ impl QPackDecoder { /// If settings include invalid values. #[must_use] pub fn new(qpack_settings: &QpackSettings) -> Self { - debug!("Decoder: creating a new qpack decoder."); + debug!("Decoder: creating a new qpack decoder"); let mut send_buf = QpackData::default(); send_buf.encode_varint(QPACK_UNI_STREAM_TYPE_DECODER); Self { @@ -140,14 +140,14 @@ impl QPackDecoder { self.stats.dynamic_table_inserts += 1; } DecodedEncoderInstruction::NoInstruction => { - unreachable!("This can be call only with an instruction."); + unreachable!("This can be call only with an instruction"); } } Ok(()) } fn set_capacity(&mut self, cap: u64) -> Res<()> { - debug!("[{self}] received instruction capacity cap={}", cap); + debug!("[{self}] received instruction capacity cap={cap}"); if cap > self.max_table_size { return Err(Error::EncoderStream); } @@ -187,7 +187,7 @@ impl QPackDecoder { let r = conn .stream_send(self.local_stream_id.unwrap(), &self.send_buf[..]) .map_err(|_| Error::DecoderStream)?; - debug!("[{self}] {} bytes sent.", r); + debug!("[{self}] {r} bytes sent"); self.send_buf.read(r); } Ok(()) @@ -215,7 +215,7 @@ impl QPackDecoder { buf: &[u8], stream_id: StreamId, ) -> Res>> { - debug!("[{self}] decode header block."); + debug!("[{self}] decode header block"); let mut decoder = HeaderDecoder::new(buf); match decoder.decode_header_block(&self.table, self.max_entries, self.table.base()) { diff --git a/neqo-qpack/src/decoder_instructions.rs b/neqo-qpack/src/decoder_instructions.rs index 3dc009fa6d..b49b99cd87 100644 --- a/neqo-qpack/src/decoder_instructions.rs +++ b/neqo-qpack/src/decoder_instructions.rs @@ -108,7 +108,7 @@ impl DecoderInstructionReader { } DecoderInstructionReaderState::ReadInt { reader } => { let val = reader.read(recv)?; - trace!("[{self}] varint read {}", val); + trace!("[{self}] varint read {val}"); match &mut self.instruction { DecoderInstruction::InsertCountIncrement { increment: v } => { *v = val; @@ -128,7 +128,7 @@ impl DecoderInstructionReader { )); } DecoderInstruction::NoInstruction => { - unreachable!("This instruction cannot be in this state."); + unreachable!("This instruction cannot be in this state"); } } } diff --git a/neqo-qpack/src/encoder.rs b/neqo-qpack/src/encoder.rs index 14a6e2c528..32835d51ed 100644 --- a/neqo-qpack/src/encoder.rs +++ b/neqo-qpack/src/encoder.rs @@ -94,8 +94,7 @@ impl QPackEncoder { } debug!( - "[{self}] Set max capacity to new capacity:{} old:{} max_table_size={}.", - cap, + "[{self}] Set max capacity to new capacity:{cap} old:{} max_table_size={}", self.table.capacity(), self.max_table_size, ); @@ -172,7 +171,7 @@ impl QPackEncoder { } } } else { - debug_assert!(false, "We should have at least one header block."); + debug_assert!(false, "We should have at least one header block"); } if hb_list.is_empty() { self.unacked_header_blocks.remove(&stream_id); @@ -203,7 +202,7 @@ impl QPackEncoder { } fn call_instruction(&mut self, instruction: DecoderInstruction, qlog: &NeqoQlog) -> Res<()> { - debug!("[{self}] call instruction {:?}", instruction); + debug!("[{self}] call instruction {instruction:?}"); match instruction { DecoderInstruction::InsertCountIncrement { increment } => { qlog::qpack_read_insert_count_increment_instruction( @@ -247,7 +246,7 @@ impl QPackEncoder { name: &[u8], value: &[u8], ) -> Res { - debug!("[{self}] insert {:?} {:?}.", name, value); + debug!("[{self}] insert {name:?} {value:?}"); let entry_size = name.len() + value.len() + ADDITIONAL_TABLE_ENTRY_SIZE; @@ -280,7 +279,7 @@ impl QPackEncoder { } fn change_capacity(&mut self, value: u64) { - debug!("[{self}] change capacity: {}", value); + debug!("[{self}] change capacity: {value}"); self.next_capacity = Some(value); } @@ -321,7 +320,7 @@ impl QPackEncoder { pub fn send_encoder_updates(&mut self, conn: &mut Connection) -> Res<()> { match self.local_stream { LocalStreamState::NoStream => { - error!("Send call but there is no stream yet."); + error!("Send call but there is no stream yet"); Ok(()) } LocalStreamState::Uninitialized(stream_id) => { @@ -368,7 +367,7 @@ impl QPackEncoder { h: &[Header], stream_id: StreamId, ) -> HeaderEncoder { - debug!("[{self}] encoding headers."); + debug!("[{self}] encoding headers"); // Try to send capacity instructions if present. // This code doesn't try to deal with errors, it just tries @@ -393,7 +392,7 @@ impl QPackEncoder { for iter in h { let name = iter.name().as_bytes().to_vec(); let value = iter.value().as_bytes().to_vec(); - trace!("encoding {:x?} {:x?}.", name, value); + trace!("encoding {name:x?} {value:x?}"); if let Some(LookupResult { index, @@ -402,9 +401,8 @@ impl QPackEncoder { }) = self.table.lookup(&name, &value, can_block) { trace!( - "[{self}] found a {} entry, value-match={}", - if static_table { "static" } else { "dynamic" }, - value_matches + "[{self}] found a {} entry, value-match={value_matches}", + if static_table { "static" } else { "dynamic" } ); if value_matches { if static_table { diff --git a/neqo-qpack/src/encoder_instructions.rs b/neqo-qpack/src/encoder_instructions.rs index 3a53990c5f..f4e5086975 100644 --- a/neqo-qpack/src/encoder_instructions.rs +++ b/neqo-qpack/src/encoder_instructions.rs @@ -174,7 +174,7 @@ impl EncoderInstructionReader { } else if ENCODER_DUPLICATE.cmp_prefix(b) { DecodedEncoderInstruction::Duplicate { index: 0 } } else { - unreachable!("The above patterns match everything."); + unreachable!("The above patterns match everything"); }; debug!("[{self}] instruction decoded"); } @@ -205,7 +205,7 @@ impl EncoderInstructionReader { } } DecodedEncoderInstruction::NoInstruction => { - unreachable!("We must have instruction at this point."); + unreachable!("We must have instruction at this point"); } } Ok(()) @@ -229,7 +229,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadFirstInt { reader } => { let val = reader.read(recv)?; - trace!("[{self}] First varint read {}", val); + trace!("[{self}] First varint read {val}"); match &mut self.instruction { DecodedEncoderInstruction::Capacity { value: v, .. } | DecodedEncoderInstruction::Duplicate { index: v } => { @@ -243,13 +243,13 @@ impl EncoderInstructionReader { reader: LiteralReader::default(), }; } - _ => unreachable!("This instruction cannot be in this state."), + _ => unreachable!("This instruction cannot be in this state"), } } EncoderInstructionReaderState::ReadFirstLiteral { reader } => { let val = reader.read(recv)?; - trace!("[{self}] first literal read {:?}", val); + trace!("[{self}] first literal read {val:?}"); match &mut self.instruction { DecodedEncoderInstruction::InsertWithNameRefStatic { value, .. } | DecodedEncoderInstruction::InsertWithNameRefDynamic { value, .. } => { @@ -262,19 +262,19 @@ impl EncoderInstructionReader { reader: LiteralReader::default(), }; } - _ => unreachable!("This instruction cannot be in this state."), + _ => unreachable!("This instruction cannot be in this state"), } } EncoderInstructionReaderState::ReadSecondLiteral { reader } => { let val = reader.read(recv)?; - trace!("[{self}] second literal read {:?}", val); + trace!("[{self}] second literal read {val:?}"); match &mut self.instruction { DecodedEncoderInstruction::InsertWithNameLiteral { value, .. } => { *value = val; self.state = EncoderInstructionReaderState::Done; } - _ => unreachable!("This instruction cannot be in this state."), + _ => unreachable!("This instruction cannot be in this state"), } } EncoderInstructionReaderState::Done => {} diff --git a/neqo-qpack/src/header_block.rs b/neqo-qpack/src/header_block.rs index c62b5d71ca..df02ae5b98 100644 --- a/neqo-qpack/src/header_block.rs +++ b/neqo-qpack/src/header_block.rs @@ -61,7 +61,7 @@ impl HeaderEncoder { } pub fn encode_indexed_static(&mut self, index: u64) { - trace!("[{self}] encode static index {}.", index); + trace!("[{self}] encode static index {index}"); self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_STATIC, index); } @@ -77,7 +77,7 @@ impl HeaderEncoder { } pub fn encode_indexed_dynamic(&mut self, index: u64) { - trace!("[{self}] encode dynamic index {}.", index); + trace!("[{self}] encode dynamic index {index}"); if index < self.base { self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_DYNAMIC, self.base - index - 1); @@ -89,12 +89,7 @@ impl HeaderEncoder { } pub fn encode_literal_with_name_ref(&mut self, is_static: bool, index: u64, value: &[u8]) { - trace!( - "[{self}] encode literal with name ref - index={}, static={}, value={:x?}", - index, - is_static, - value - ); + trace!("[{self}] encode literal with name ref - index={index}, static={is_static}, value={value:x?}"); if is_static { self.buf .encode_prefixed_encoded_int(HEADER_FIELD_LITERAL_NAME_REF_STATIC, index); @@ -116,11 +111,7 @@ impl HeaderEncoder { } pub fn encode_literal_with_name_literal(&mut self, name: &[u8], value: &[u8]) { - trace!( - "[{self}] encode literal with name literal - name={:x?}, value={:x?}.", - name, - value - ); + trace!("[{self}] encode literal with name literal - name={name:x?}, value={value:x?}"); self.buf .encode_literal(self.use_huffman, HEADER_FIELD_LITERAL_NAME_LITERAL, name); self.buf.encode_literal(self.use_huffman, NO_PREFIX, value); @@ -147,12 +138,9 @@ impl HeaderEncoder { } }); trace!( - "[{self}] encode header block prefix max_dynamic_index_ref={:?}, base={}, enc_insert_cnt={}, delta={}, prefix={:?}.", + "[{self}] encode header block prefix max_dynamic_index_ref={:?}, base={}, enc_insert_cnt={enc_insert_cnt}, delta={delta}, prefix={prefix:?}", self.max_dynamic_index_ref, - self.base, - enc_insert_cnt, - delta, - prefix + self.base ); self.buf @@ -271,7 +259,7 @@ impl<'a> HeaderDecoder<'a> { } } - trace!("[{self}] done decoding header block."); + trace!("[{self}] done decoding header block"); Ok(HeaderDecoderResult::Headers(h)) } @@ -331,7 +319,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_STATIC.len())?; - trace!("[{self}] decoder static indexed {}.", index); + trace!("[{self}] decoder static indexed {index}"); let entry = HeaderTable::get_static(index)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -343,7 +331,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC.len())?; - trace!("[{self}] decoder dynamic indexed {}.", index); + trace!("[{self}] decoder dynamic indexed {index}"); let entry = table.get_dynamic(index, self.base, false)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -355,7 +343,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC_POST.len())?; - trace!("[{self}] decode post-based {}.", index); + trace!("[{self}] decode post-based {index}"); let entry = table.get_dynamic(index, self.base, true)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -364,7 +352,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_static(&mut self) -> Res
{ - trace!("[{self}] read literal with name reference to the static table."); + trace!("[{self}] read literal with name reference to the static table"); let index = self .buf @@ -377,7 +365,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_dynamic(&mut self, table: &HeaderTable) -> Res
{ - trace!("[{self}] read literal with name reference of the dynamic table."); + trace!("[{self}] read literal with name reference of the dynamic table"); let index = self .buf @@ -390,7 +378,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_dynamic_post(&mut self, table: &HeaderTable) -> Res
{ - trace!("[{self}] decoder literal with post-based index."); + trace!("[{self}] decoder literal with post-based index"); let index = self .buf @@ -403,7 +391,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_literal(&mut self) -> Res
{ - trace!("[{self}] decode literal with name literal."); + trace!("[{self}] decode literal with name literal"); let name = self .buf diff --git a/neqo-qpack/src/qpack_send_buf.rs b/neqo-qpack/src/qpack_send_buf.rs index d5e3e0c2e0..0856c13116 100644 --- a/neqo-qpack/src/qpack_send_buf.rs +++ b/neqo-qpack/src/qpack_send_buf.rs @@ -90,7 +90,7 @@ impl QpackData { pub fn read(&mut self, r: usize) { assert!( r <= self.buf.len(), - "want to set more bytes read than remain in the buffer." + "want to set more bytes read than remain in the buffer" ); self.buf = self.buf.split_off(r); } diff --git a/neqo-qpack/src/reader.rs b/neqo-qpack/src/reader.rs index f564b886a5..ba517c85d5 100644 --- a/neqo-qpack/src/reader.rs +++ b/neqo-qpack/src/reader.rs @@ -164,7 +164,7 @@ impl IntReader { /// When `prefix_len` is 8 or larger. #[must_use] pub fn new(first_byte: u8, prefix_len: u8) -> Self { - debug_assert!(prefix_len < 8, "prefix cannot larger than 7."); + debug_assert!(prefix_len < 8, "prefix cannot larger than 7"); let mask = if prefix_len == 0 { 0xff } else { @@ -315,7 +315,7 @@ impl LiteralReader { break Err(Error::NeedMoreData); } LiteralReaderState::Done => { - panic!("Should not call read() in this state."); + panic!("Should not call read() in this state"); } } } diff --git a/neqo-qpack/src/table.rs b/neqo-qpack/src/table.rs index 9936c4aa7a..23b43dac69 100644 --- a/neqo-qpack/src/table.rs +++ b/neqo-qpack/src/table.rs @@ -116,7 +116,7 @@ impl HeaderTable { /// The table cannot be reduce if there are entries that are referred at the moment or their /// inserts are unacked. pub fn set_capacity(&mut self, cap: u64) -> Res<()> { - trace!("[{self}] set capacity to {}", cap); + trace!("[{self}] set capacity to {cap}"); if !self.evict_to(cap) { return Err(Error::ChangeCapacity); } @@ -181,7 +181,7 @@ impl HeaderTable { /// Remove a reference to a dynamic table entry. pub fn remove_ref(&mut self, index: u64) { - trace!("[{self}] remove reference to entry {}", index); + trace!("[{self}] remove reference to entry {index}"); self.get_dynamic_with_abs_index(index) .expect("we should have the entry") .remove_ref(); @@ -189,7 +189,7 @@ impl HeaderTable { /// Add a reference to a dynamic table entry. pub fn add_ref(&mut self, index: u64) { - trace!("[{self}] add reference to entry {}", index); + trace!("[{self}] add reference to entry {index}"); self.get_dynamic_with_abs_index(index) .expect("we should have the entry") .add_ref(); @@ -199,12 +199,7 @@ impl HeaderTable { /// The function returns `LookupResult`: `index`, `static_table` (if it is a static table entry) /// and `value_matches` (if the header value matches as well not only header name) pub fn lookup(&mut self, name: &[u8], value: &[u8], can_block: bool) -> Option { - trace!( - "[{self}] lookup name:{:?} value {:?} can_block={}", - name, - value, - can_block - ); + trace!("[{self}] lookup name:{name:?} value {value:?} can_block={can_block}",); let mut name_match = None; for iter in HEADER_STATIC_TABLE { if iter.name() == name { @@ -261,10 +256,8 @@ impl HeaderTable { pub fn evict_to_internal(&mut self, reduce: u64, only_check: bool) -> bool { trace!( - "[{self}] reduce table to {}, currently used:{} only_check:{}", - reduce, + "[{self}] reduce table to {reduce}, currently used:{} only_check:{only_check}", self.used, - only_check ); let mut used = self.used; while (!self.dynamic.is_empty()) && used > reduce { @@ -294,7 +287,7 @@ impl HeaderTable { /// `DynamicTableFull` if an entry cannot be added to the table because there is not enough /// space and/or other entry cannot be evicted. pub fn insert(&mut self, name: &[u8], value: &[u8]) -> Res { - trace!("[{self}] insert name={:?} value={:?}", name, value); + trace!("[{self}] insert name={name:?} value={value:?}"); let entry = DynamicTableEntry { name: name.to_vec(), value: value.to_vec(), @@ -327,14 +320,12 @@ impl HeaderTable { value: &[u8], ) -> Res { trace!( - "[{self}] insert with ref to index={} in {} value={:?}", - name_index, + "[{self}] insert with ref to index={name_index} in {} value={value:?}", if name_static_table { "static" } else { "dynamic" }, - value ); let name = if name_static_table { Self::get_static(name_index)?.name().to_vec() @@ -354,7 +345,7 @@ impl HeaderTable { /// space and/or other entry cannot be evicted. /// `HeaderLookup` if the index dos not exits in the static/dynamic table. pub fn duplicate(&mut self, index: u64) -> Res { - trace!("[{self}] duplicate entry={}", index); + trace!("[{self}] duplicate entry={index}"); // need to remember name and value because insert may delete the entry. let name: Vec; let value: Vec; @@ -362,7 +353,7 @@ impl HeaderTable { let entry = self.get_dynamic(index, self.base, false)?; name = entry.name().to_vec(); value = entry.value().to_vec(); - trace!("[{self}] duplicate name={:?} value={:?}", name, value); + trace!("[{self}] duplicate name={name:?} value={value:?}"); } self.insert(&name, &value) } @@ -373,7 +364,7 @@ impl HeaderTable { /// /// `IncrementAck` if ack is greater than actual number of inserts. pub fn increment_acked(&mut self, increment: u64) -> Res<()> { - trace!("[{self}] increment acked by {}", increment); + trace!("[{self}] increment acked by {increment}"); self.acked_inserts_cnt += increment; if self.base < self.acked_inserts_cnt { return Err(Error::IncrementAck); diff --git a/neqo-transport/src/ackrate.rs b/neqo-transport/src/ackrate.rs index 22f2782f31..a82da04678 100644 --- a/neqo-transport/src/ackrate.rs +++ b/neqo-transport/src/ackrate.rs @@ -37,7 +37,7 @@ impl AckRate { let packets = packets.clamp(MIN_PACKETS, MAX_PACKETS) - 1; let delay = rtt * RTT_RATIO / u32::from(ratio); let delay = delay.clamp(minimum, MAX_DELAY); - trace!("AckRate inputs: {}/{}/{}, {:?}", cwnd, mtu, ratio, rtt); + trace!("AckRate inputs: {cwnd}/{mtu}/{ratio}, {rtt:?}"); Self { packets, delay } } @@ -82,12 +82,7 @@ impl FlexibleAckRate { mtu: usize, rtt: Duration, ) -> Self { - trace!( - "FlexibleAckRate: {:?} {:?} {}", - max_ack_delay, - min_ack_delay, - ratio - ); + trace!("FlexibleAckRate: {max_ack_delay:?} {min_ack_delay:?} {ratio}"); let ratio = max(ACK_RATIO_SCALE, ratio); // clamp it Self { current: AckRate { diff --git a/neqo-transport/src/addr_valid.rs b/neqo-transport/src/addr_valid.rs index ac7694b3cc..b5f0f836c2 100644 --- a/neqo-transport/src/addr_valid.rs +++ b/neqo-transport/src/addr_valid.rs @@ -149,7 +149,7 @@ impl AddressValidation { } pub fn set_validation(&mut self, validation: ValidateAddress) { - trace!("AddressValidation {:p}: set to {:?}", self, validation); + trace!("AddressValidation {self:p}: set to {validation:?}"); self.validation = validation; } @@ -171,7 +171,7 @@ impl AddressValidation { Some(d) => { let end = self.start_time + Duration::from_millis(u64::from(d)); if end < now { - trace!("Expired token: {:?} vs. {:?}", end, now); + trace!("Expired token: {end:?} vs. {now:?}"); return None; } } @@ -200,11 +200,7 @@ impl AddressValidation { peer_address: SocketAddr, now: Instant, ) -> AddressValidationResult { - trace!( - "AddressValidation {:p}: validate {:?}", - self, - self.validation - ); + trace!("AddressValidation {self:p}: validate {:?}", self.validation); if token.is_empty() { if self.validation == ValidateAddress::Never { @@ -228,7 +224,7 @@ impl AddressValidation { if retry { // This is from Retry, so we should have an ODCID >= 8. if cid.len() >= 8 { - info!("AddressValidation: valid Retry token for {}", cid); + info!("AddressValidation: valid Retry token for {cid}"); AddressValidationResult::ValidRetry(cid) } else { panic!("AddressValidation: Retry token with small CID {cid}"); diff --git a/neqo-transport/src/cc/classic_cc.rs b/neqo-transport/src/cc/classic_cc.rs index 1f46de65ea..9880c845df 100644 --- a/neqo-transport/src/cc/classic_cc.rs +++ b/neqo-transport/src/cc/classic_cc.rs @@ -193,13 +193,11 @@ impl CongestionControl for ClassicCongestionControl { let mut new_acked = 0; for pkt in acked_pkts { trace!( - "packet_acked this={:p}, pn={}, ps={}, ignored={}, lost={}, rtt_est={:?}", - self, + "packet_acked this={self:p}, pn={}, ps={}, ignored={}, lost={}, rtt_est={rtt_est:?}", pkt.pn(), pkt.len(), i32::from(!pkt.cc_outstanding()), i32::from(pkt.lost()), - rtt_est, ); if !pkt.cc_outstanding() { continue; @@ -227,7 +225,7 @@ impl CongestionControl for ClassicCongestionControl { if is_app_limited { self.cc_algorithm.on_app_limited(); - debug!("on_packets_acked this={:p}, limited=1, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={}", self, self.bytes_in_flight, self.congestion_window, self.state, new_acked); + debug!("on_packets_acked this={self:p}, limited=1, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={new_acked}", self.bytes_in_flight, self.congestion_window, self.state); return; } @@ -237,7 +235,7 @@ impl CongestionControl for ClassicCongestionControl { let increase = min(self.ssthresh - self.congestion_window, self.acked_bytes); self.congestion_window += increase; self.acked_bytes -= increase; - debug!("[{self}] slow start += {}", increase); + debug!("[{self}] slow start += {increase}"); if self.congestion_window == self.ssthresh { // This doesn't look like it is necessary, but it can happen // after persistent congestion. @@ -280,7 +278,7 @@ impl CongestionControl for ClassicCongestionControl { ], now, ); - debug!("[{self}] on_packets_acked this={:p}, limited=0, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={}", self, self.bytes_in_flight, self.congestion_window, self.state, new_acked); + debug!("[{self}] on_packets_acked this={self:p}, limited=0, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={new_acked}", self.bytes_in_flight, self.congestion_window, self.state); } /// Update congestion controller state based on lost packets. @@ -298,8 +296,7 @@ impl CongestionControl for ClassicCongestionControl { for pkt in lost_packets.iter().filter(|pkt| pkt.cc_in_flight()) { debug!( - "packet_lost this={:p}, pn={}, ps={}", - self, + "packet_lost this={self:p}, pn={}, ps={}", pkt.pn(), pkt.len() ); @@ -334,8 +331,8 @@ impl CongestionControl for ClassicCongestionControl { now, ); debug!( - "on_packets_lost this={:p}, bytes_in_flight={}, cwnd={}, state={:?}", - self, self.bytes_in_flight, self.congestion_window, self.state + "on_packets_lost this={self:p}, bytes_in_flight={}, cwnd={}, state={:?}", + self.bytes_in_flight, self.congestion_window, self.state ); congestion || persistent_congestion } @@ -390,8 +387,7 @@ impl CongestionControl for ClassicCongestionControl { self.bytes_in_flight += pkt.len(); debug!( - "packet_sent this={:p}, pn={}, ps={}", - self, + "packet_sent this={self:p}, pn={}, ps={}", pkt.pn(), pkt.len() ); @@ -456,7 +452,7 @@ impl ClassicCongestionControl { fn set_state(&mut self, state: State, now: Instant) { if self.state != state { - debug!("[{self}] state -> {:?}", state); + debug!("[{self}] state -> {state:?}"); let old_state = self.state; self.qlog.add_event_data_with_instant( || { diff --git a/neqo-transport/src/connection/dump.rs b/neqo-transport/src/connection/dump.rs index 071ec692ef..5c0278c192 100644 --- a/neqo-transport/src/connection/dump.rs +++ b/neqo-transport/src/connection/dump.rs @@ -5,7 +5,7 @@ // except according to those terms. // Enable just this file for logging to just see packets. -// e.g. "RUST_LOG=neqo_transport::dump neqo-client ..." +// e.g. "RUST_LOG=neqo_transport::dump neqo-client .." use std::fmt::Write; @@ -38,21 +38,16 @@ pub fn dump_packet( let mut d = Decoder::from(payload); while d.remaining() > 0 { let Ok(f) = Frame::decode(&mut d) else { - s.push_str(" [broken]..."); + s.push_str(" [broken].."); break; }; let x = f.dump(); if !x.is_empty() { - _ = write!(&mut s, "\n {} {}", dir, &x); + _ = write!(&mut s, "\n {dir} {}", &x); } } debug!( - "[{conn}] pn={} type={:?} {} {:?} len {}{}", - pn, - pt, - path.borrow(), - tos, - len, - s + "[{conn}] pn={pn} type={pt:?} {} {tos:?} len {len}{s}", + path.borrow() ); } diff --git a/neqo-transport/src/connection/mod.rs b/neqo-transport/src/connection/mod.rs index 5c796ca374..3f568669cf 100644 --- a/neqo-transport/src/connection/mod.rs +++ b/neqo-transport/src/connection/mod.rs @@ -507,7 +507,7 @@ impl Connection { Ok(()) } else { error!("Current state: {:?}", self.state()); - error!("Cannot set local tparam when not in an initial connection state."); + error!("Cannot set local tparam when not in an initial connection state"); Err(Error::ConnectionState) } } @@ -523,12 +523,7 @@ impl Connection { retry_cid: &ConnectionId, ) { debug_assert_eq!(self.role, Role::Server); - trace!( - "[{self}] Retry CIDs: odcid={} remote={} retry={}", - odcid, - remote_cid, - retry_cid - ); + trace!("[{self}] Retry CIDs: odcid={odcid} remote={remote_cid} retry={retry_cid}"); // We advertise "our" choices in transport parameters. let local_tps = &mut self.tps.borrow_mut().local; local_tps.set_bytes(tparams::ORIGINAL_DESTINATION_CONNECTION_ID, odcid.to_vec()); @@ -733,13 +728,13 @@ impl Connection { dec.decode_uint::() .ok_or(Error::InvalidResumptionToken)?, )?; - trace!("[{self}] version {:?}", version); + trace!("[{self}] version {version:?}"); if !self.conn_params.get_versions().all().contains(&version) { return Err(Error::DisabledVersion); } let rtt = Duration::from_millis(dec.decode_varint().ok_or(Error::InvalidResumptionToken)?); - trace!("[{self}] RTT {:?}", rtt); + trace!("[{self}] RTT {rtt:?}"); let tp_slice = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?; trace!("[{self}] transport parameters {}", hex(tp_slice)); @@ -853,7 +848,7 @@ impl Connection { /// the connection to fail. However, if no packets have been /// exchanged, it's not OK. pub fn authenticated(&mut self, status: AuthenticationStatus, now: Instant) { - debug!("[{self}] Authenticated {:?}", status); + debug!("[{self}] Authenticated {status:?}"); self.crypto.tls.authenticated(status); let res = self.handshake(now, self.version, PacketNumberSpace::Handshake, None); self.absorb_error(now, res); @@ -915,7 +910,7 @@ impl Connection { State::Closing { error: err, .. } | State::Draining { error: err, .. } | State::Closed(err) => { - warn!("[{self}] Closing again after error {:?}", err); + warn!("[{self}] Closing again after error {err:?}"); } State::Init => { // We have not even sent anything just close the connection without sending any @@ -1051,7 +1046,7 @@ impl Connection { /// Get the time that we next need to be called back, relative to `now`. fn next_delay(&mut self, now: Instant, paced: bool) -> Duration { - trace!("[{self}] Get callback delay {:?}", now); + trace!("[{self}] Get callback delay {now:?}"); // Only one timer matters when closing... if let State::Closing { timeout, .. } | State::Draining { timeout, .. } = self.state { @@ -1061,7 +1056,7 @@ impl Connection { let mut delays = SmallVec::<[_; 7]>::new(); if let Some(ack_time) = self.acks.ack_time(now) { - trace!("[{self}] Delayed ACK timer {:?}", ack_time); + trace!("[{self}] Delayed ACK timer {ack_time:?}"); delays.push(ack_time); } @@ -1071,36 +1066,36 @@ impl Connection { let pto = rtt.pto(self.confirmed()); let idle_time = self.idle_timeout.expiry(now, pto); - trace!("[{self}] Idle timer {:?}", idle_time); + trace!("[{self}] Idle timer {idle_time:?}"); delays.push(idle_time); if self.streams.need_keep_alive() { if let Some(keep_alive_time) = self.idle_timeout.next_keep_alive(now, pto) { - trace!("[{self}] Keep alive timer {:?}", keep_alive_time); + trace!("[{self}] Keep alive timer {keep_alive_time:?}"); delays.push(keep_alive_time); } } if let Some(lr_time) = self.loss_recovery.next_timeout(&path) { - trace!("[{self}] Loss recovery timer {:?}", lr_time); + trace!("[{self}] Loss recovery timer {lr_time:?}"); delays.push(lr_time); } if paced { if let Some(pace_time) = path.sender().next_paced(rtt.estimate()) { - trace!("[{self}] Pacing timer {:?}", pace_time); + trace!("[{self}] Pacing timer {pace_time:?}"); delays.push(pace_time); } } if let Some(path_time) = self.paths.next_timeout(pto) { - trace!("[{self}] Path probe timer {:?}", path_time); + trace!("[{self}] Path probe timer {path_time:?}"); delays.push(path_time); } } if let Some(key_update_time) = self.crypto.states.update_time() { - trace!("[{self}] Key update timer {:?}", key_update_time); + trace!("[{self}] Key update timer {key_update_time:?}"); delays.push(key_update_time); } @@ -1114,7 +1109,7 @@ impl Connection { // rather than just clamping to zero here. debug_assert!(earliest > now); let delay = earliest.saturating_duration_since(now); - debug!("[{self}] delay duration {:?}", delay); + debug!("[{self}] delay duration {delay:?}"); self.hrtime.update(delay / 4); delay } @@ -1125,7 +1120,7 @@ impl Connection { /// even if no incoming packets. #[must_use = "Output of the process_output function must be handled"] pub fn process_output(&mut self, now: Instant) -> Output { - trace!("[{self}] process_output {:?} {:?}", self.state, now); + trace!("[{self}] process_output {:?} {now:?}", self.state); match (&self.state, self.role) { (State::Init, Role::Client) => { @@ -1216,9 +1211,8 @@ impl Connection { let retry_scid = ConnectionId::from(packet.scid()); info!( - "[{self}] Valid Retry received, token={} scid={}", - hex(packet.token()), - retry_scid + "[{self}] Valid Retry received, token={} scid={retry_scid}", + hex(packet.token()) ); let lost_packets = self.loss_recovery.retry(&path, now); @@ -1238,7 +1232,7 @@ impl Connection { fn discard_keys(&mut self, space: PacketNumberSpace, now: Instant) { if self.crypto.discard(space) { - debug!("[{self}] Drop packet number space {}", space); + debug!("[{self}] Drop packet number space {space}"); if let Some(path) = self.paths.primary() { self.loss_recovery.discard(&path, space, now); } @@ -1284,7 +1278,7 @@ impl Connection { /// Process any saved datagrams that might be available for processing. fn process_saved(&mut self, now: Instant) { while let Some(cspace) = self.saved_datagrams.available() { - debug!("[{self}] process saved for space {:?}", cspace); + debug!("[{self}] process saved for space {cspace:?}"); debug_assert!(self.crypto.states.rx_hp(self.version, cspace).is_some()); for saved in self.saved_datagrams.take_saved() { trace!("[{self}] input saved @{:?}: {:?}", saved.t, saved.d); @@ -1320,7 +1314,7 @@ impl Connection { if let Some(version) = self.conn_params.get_versions().preferred(supported) { assert_ne!(self.version, version); - info!("[{self}] Version negotiation: trying {:?}", version); + info!("[{self}] Version negotiation: trying {version:?}"); let path = self.paths.primary().ok_or(Error::NoAvailablePath)?; let local_addr = path.borrow().local_address(); let remote_addr = path.borrow().remote_address(); @@ -1350,7 +1344,7 @@ impl Connection { ); Ok(()) } else { - info!("[{self}] Version negotiation: failed with {:?}", supported); + info!("[{self}] Version negotiation: failed with {supported:?}"); // This error goes straight to closed. self.set_state( State::Closed(CloseReason::Transport(Error::VersionNegotiation)), @@ -1575,7 +1569,7 @@ impl Connection { match PublicPacket::decode(slc, self.cid_manager.decoder().as_ref()) { Ok((packet, remainder)) => (packet, remainder), Err(e) => { - info!("[{self}] Garbage packet: {}", e); + info!("[{self}] Garbage packet: {e}"); trace!("[{self}] Garbage packet contents: {}", hex(slc)); self.stats.borrow_mut().pkt_dropped("Garbage packet"); break; @@ -1587,7 +1581,7 @@ impl Connection { PreprocessResult::End => return Ok(()), } - trace!("[{self}] Received unverified packet {:?}", packet); + trace!("[{self}] Received unverified packet {packet:?}"); match packet.decrypt(&mut self.crypto.states, now + pto) { Ok(payload) => { @@ -1618,7 +1612,7 @@ impl Connection { let space = PacketNumberSpace::from(payload.packet_type()); if let Some(space) = self.acks.get_mut(space) { if space.is_duplicate(payload.pn()) { - debug!("Duplicate packet {}-{}", space, payload.pn()); + debug!("Duplicate packet {space}-{}", payload.pn()); self.stats.borrow_mut().dups_rx += 1; } else { match self.process_packet(path, &payload, now) { @@ -1633,8 +1627,7 @@ impl Connection { } } else { debug!( - "[{self}] Received packet {} for untracked space {}", - space, + "[{self}] Received packet {space} for untracked space {}", payload.pn() ); return Err(Error::ProtocolViolation); @@ -1968,12 +1961,12 @@ impl Connection { // Ignore preferred address that move to loopback from non-loopback. // `migrate` doesn't enforce this rule. if !prev.ip().is_loopback() && remote.ip().is_loopback() { - warn!("[{self}] Ignoring a move to a loopback address: {}", remote); + warn!("[{self}] Ignoring a move to a loopback address: {remote}"); return Ok(()); } if self.migrate(None, Some(remote), false, now).is_err() { - warn!("[{self}] Ignoring bad preferred address: {}", remote); + warn!("[{self}] Ignoring bad preferred address: {remote}"); } } else { warn!("[{self}] Unable to migrate to a different address family"); @@ -2010,7 +2003,7 @@ impl Connection { } fn output(&mut self, now: Instant) -> SendOption { - trace!("[{self}] output {:?}", now); + trace!("[{self}] output {now:?}"); let res = match &self.state { State::Init | State::WaitInitial @@ -2062,8 +2055,7 @@ impl Connection { PacketBuilder::short(encoder, tx.key_phase(), path.remote_cid()) } else { debug!( - "Building {:?} dcid {:?} scid {:?}", - pt, + "Building {pt:?} dcid {:?} scid {:?}", path.remote_cid(), path.local_cid(), ); @@ -2377,7 +2369,7 @@ impl Connection { // Determine how we are sending packets (PTO, etc..). let profile = self.loss_recovery.send_profile(&path.borrow(), now); - debug!("[{self}] output_path send_profile {:?}", profile); + debug!("[{self}] output_path send_profile {profile:?}"); // Frames for different epochs must go in different packets, but then these // packets can go in a single datagram @@ -2507,7 +2499,7 @@ impl Connection { } if encoder.is_empty() { - debug!("TX blocked, profile={:?}", profile); + debug!("TX blocked, profile={profile:?}"); Ok(SendOption::No(profile.paced())) } else { // Perform additional padding for Initial packets as necessary. @@ -2715,8 +2707,7 @@ impl Connection { }; if expected != tp.map(ConnectionIdRef::from) { warn!( - "[{self}] RSCID test failed. self cid {:?} != tp cid {:?}", - expected, + "[{self}] RSCID test failed. self cid {expected:?} != tp cid {:?}", tp.map(hex), ); return Err(Error::ProtocolViolation); @@ -2734,10 +2725,8 @@ impl Connection { // We're checking that these match our expectations. if let Some((current, other)) = remote_tps.get_versions() { trace!( - "[{self}] validate_versions: current={:x} chosen={:x} other={:x?}", + "[{self}] validate_versions: current={:x} chosen={current:x} other={other:x?}", self.version.wire_version(), - current, - other, ); if self.role == Role::Server { // 1. A server acts on transport parameters, with validation @@ -2785,7 +2774,7 @@ impl Connection { fn confirm_version(&mut self, v: Version) { if self.version != v { - debug!("[{self}] Compatible upgrade {:?} ==> {:?}", self.version, v); + debug!("[{self}] Compatible upgrade {:?} ==> {v:?}", self.version); } self.crypto.confirm_version(v); self.version = v; @@ -2817,7 +2806,7 @@ impl Connection { space: PacketNumberSpace, data: Option<&[u8]>, ) -> Res<()> { - trace!("[{self}] Handshake space={} data={:0x?}", space, data); + trace!("[{self}] Handshake space={space} data={data:0x?}"); let was_authentication_pending = *self.crypto.tls.state() == HandshakeState::AuthenticationPending; @@ -2888,7 +2877,7 @@ impl Connection { now: Instant, ) -> Res<()> { if !frame.is_allowed(packet_type) { - info!("frame not allowed: {:?} {:?}", frame, packet_type); + info!("frame not allowed: {frame:?} {packet_type:?}"); return Err(Error::ProtocolViolation); } let space = PacketNumberSpace::from(packet_type); @@ -2920,7 +2909,7 @@ impl Connection { // (If we ever start using non-contiguous packet numbers, we need to check all the // packet numbers in the ACKed ranges.) if largest_acknowledged >= next_pn { - warn!("Largest ACKed {} was never sent", largest_acknowledged); + warn!("Largest ACKed {largest_acknowledged} was never sent"); return Err(Error::AckedUnsentPacket); } @@ -2930,9 +2919,7 @@ impl Connection { } Frame::Crypto { offset, data } => { trace!( - "[{self}] Crypto frame on space={} offset={}, data={:0x?}", - space, - offset, + "[{self}] Crypto frame on space={space} offset={offset}, data={:0x?}", &data ); self.stats.borrow_mut().frame_rx.crypto += 1; @@ -2940,7 +2927,7 @@ impl Connection { if self.crypto.streams.data_ready(space) { let mut buf = Vec::new(); let read = self.crypto.streams.read_to_end(space, &mut buf); - debug!("Read {:?} bytes", read); + debug!("Read {read:?} bytes"); self.handshake(now, packet_version, space, Some(&buf))?; self.create_resumption_token(now); } else { @@ -3005,8 +2992,7 @@ impl Connection { } => { self.stats.borrow_mut().frame_rx.connection_close += 1; info!( - "[{self}] ConnectionClose received. Error code: {:?} frame type {:x} reason {}", - error_code, frame_type, reason_phrase + "[{self}] ConnectionClose received. Error code: {error_code:?} frame type {frame_type:x} reason {reason_phrase}" ); let (detail, frame_type) = if let CloseError::Application(_) = error_code { // Use a transport error here because we want to send @@ -3072,7 +3058,7 @@ impl Connection { fn handle_lost_packets(&mut self, lost_packets: &[SentPacket]) { for lost in lost_packets { for token in lost.tokens() { - debug!("[{self}] Lost: {:?}", token); + debug!("[{self}] Lost: {token:?}"); match token { RecoveryToken::Ack(ack_token) => { // If we lost an ACK frame during the handshake, send another one. @@ -3121,7 +3107,7 @@ impl Connection { R: IntoIterator> + Debug, R::IntoIter: ExactSizeIterator, { - debug!("[{self}] Rx ACK space={}, ranges={:?}", space, ack_ranges); + debug!("[{self}] Rx ACK space={space}, ranges={ack_ranges:?}"); let Some(path) = self.paths.primary() else { return; @@ -3186,7 +3172,7 @@ impl Connection { fn set_connected(&mut self, now: Instant) -> Res<()> { debug!("[{self}] TLS connection complete"); if self.crypto.tls.info().map(SecretAgentInfo::alpn).is_none() { - warn!("[{self}] No ALPN. Closing connection."); + warn!("[{self}] No ALPN. Closing connection"); // 120 = no_application_protocol return Err(Error::CryptoAlert(120)); } @@ -3238,7 +3224,7 @@ impl Connection { fn set_state(&mut self, state: State, now: Instant) { if state > self.state { - debug!("[{self}] State change from {:?} -> {:?}", self.state, state); + debug!("[{self}] State change from {:?} -> {state:?}", self.state); self.state = state.clone(); if self.state.closed() { self.streams.clear_streams(); @@ -3364,8 +3350,7 @@ impl Connection { if let Ok(val) = val { debug_assert!( val == 0 || val == data.len(), - "Unexpected value {} when trying to send {} bytes atomically", - val, + "Unexpected value {val} when trying to send {} bytes atomically", data.len() ); } diff --git a/neqo-transport/src/connection/params.rs b/neqo-transport/src/connection/params.rs index ae50b6e124..ce27440543 100644 --- a/neqo-transport/src/connection/params.rs +++ b/neqo-transport/src/connection/params.rs @@ -189,7 +189,7 @@ impl ConnectionParameters { (StreamType::BiDi, false) => self.max_stream_data_bidi_local, (StreamType::BiDi, true) => self.max_stream_data_bidi_remote, (StreamType::UniDi, false) => { - panic!("Can't get receive limit on a stream that can only be sent.") + panic!("Can't get receive limit on a stream that can only be sent") } (StreamType::UniDi, true) => self.max_stream_data_uni, } @@ -212,7 +212,7 @@ impl ConnectionParameters { self.max_stream_data_bidi_remote = v; } (StreamType::UniDi, false) => { - panic!("Can't set receive limit on a stream that can only be sent.") + panic!("Can't set receive limit on a stream that can only be sent") } (StreamType::UniDi, true) => { self.max_stream_data_uni = v; diff --git a/neqo-transport/src/connection/tests/cc.rs b/neqo-transport/src/connection/tests/cc.rs index 92ea4e7e8f..83087b4f93 100644 --- a/neqo-transport/src/connection/tests/cc.rs +++ b/neqo-transport/src/connection/tests/cc.rs @@ -250,12 +250,11 @@ fn cc_cong_avoidance_recovery_period_to_cong_avoidance() { let (mut c_tx_dgrams, next_now) = fill_cwnd(&mut client, stream_id, now); now = next_now; for i in 0..5 { - info!("iteration {}", i); + info!("iteration {i}"); let c_tx_size: usize = c_tx_dgrams.iter().map(Datagram::len).sum(); info!( - "client sending {} bytes into cwnd of {}", - c_tx_size, + "client sending {c_tx_size} bytes into cwnd of {}", cwnd(&client) ); assert_eq!(c_tx_size, expected_cwnd); diff --git a/neqo-transport/src/connection/tests/ecn.rs b/neqo-transport/src/connection/tests/ecn.rs index c4ba07547b..c90acf5c27 100644 --- a/neqo-transport/src/connection/tests/ecn.rs +++ b/neqo-transport/src/connection/tests/ecn.rs @@ -89,7 +89,7 @@ fn handshake_delay_with_ecn_blackhole() { assert_eq!( (finish - start).as_millis() / DEFAULT_RTT.as_millis(), 15, - "expected 6 RTT for client to detect blackhole, 6 RTT for server to detect blackhole and 3 RTT for handshake to be confirmed.", + "expected 6 RTT for client to detect blackhole, 6 RTT for server to detect blackhole and 3 RTT for handshake to be confirmed", ); } diff --git a/neqo-transport/src/connection/tests/idle.rs b/neqo-transport/src/connection/tests/idle.rs index 59d8888923..6fff90f5d7 100644 --- a/neqo-transport/src/connection/tests/idle.rs +++ b/neqo-transport/src/connection/tests/idle.rs @@ -360,7 +360,7 @@ fn create_stream_idle_rtt( ) -> (Instant, StreamId) { let check_idle = |endpoint: &mut Connection, now: Instant| { let delay = endpoint.process_output(now).callback(); - trace!("[{endpoint}] idle timeout {:?}", delay); + trace!("[{endpoint}] idle timeout {delay:?}"); if rtt < default_timeout() / 4 { assert_eq!(default_timeout(), delay); } else { @@ -641,7 +641,7 @@ fn keep_alive_large_rtt() { for endpoint in &mut [client, server] { endpoint.stream_keep_alive(stream, true).unwrap(); let delay = endpoint.process_output(now).callback(); - trace!("[{endpoint}] new delay {:?}", delay); + trace!("[{endpoint}] new delay {delay:?}"); assert!(delay > keep_alive_timeout()); assert!(delay > rtt); } diff --git a/neqo-transport/src/connection/tests/mod.rs b/neqo-transport/src/connection/tests/mod.rs index 550583ab18..f0a8d83677 100644 --- a/neqo-transport/src/connection/tests/mod.rs +++ b/neqo-transport/src/connection/tests/mod.rs @@ -347,7 +347,7 @@ fn connect_rtt_idle_with_modifier( // Drain events from both as well. _ = client.events().count(); _ = server.events().count(); - trace!("----- connected and idle with RTT {:?}", rtt); + trace!("----- connected and idle with RTT {rtt:?}"); now } @@ -371,7 +371,7 @@ fn fill_stream(c: &mut Connection, stream: StreamId) { const BLOCK_SIZE: usize = 4_096; loop { let bytes_sent = c.stream_send(stream, &[0x42; BLOCK_SIZE]).unwrap(); - trace!("fill_cwnd wrote {} bytes", bytes_sent); + trace!("fill_cwnd wrote {bytes_sent} bytes"); if bytes_sent < BLOCK_SIZE { break; } @@ -392,9 +392,8 @@ fn fill_cwnd(c: &mut Connection, stream: StreamId, mut now: Instant) -> (Vec { @@ -473,7 +472,7 @@ where loop { let (bytes_read, _fin) = dest.stream_recv(stream, &mut srv_buf).unwrap(); - trace!("[{dest}] ack_bytes read {} bytes", bytes_read); + trace!("[{dest}] ack_bytes read {bytes_read} bytes"); if bytes_read == 0 { break; } @@ -592,7 +591,7 @@ fn send_something_paced_with_modifier( let stream_id = sender.stream_create(StreamType::UniDi).unwrap(); assert!(sender.stream_send(stream_id, DEFAULT_STREAM_DATA).is_ok()); assert!(sender.stream_close_send(stream_id).is_ok()); - debug!("[{sender}] send_something on {}", stream_id); + debug!("[{sender}] send_something on {stream_id}"); let dgram = match sender.process_output(now) { Output::Callback(t) => { assert!(allow_pacing, "send_something: unexpected delay"); @@ -699,9 +698,8 @@ fn assert_path_challenge_min_len(c: &Connection, d: &Datagram, now: Instant) { } assert!( d.len() >= MIN_INITIAL_PACKET_SIZE, - "{} < {}", - d.len(), - MIN_INITIAL_PACKET_SIZE + "{} < {MIN_INITIAL_PACKET_SIZE}", + d.len() ); } diff --git a/neqo-transport/src/connection/tests/recovery.rs b/neqo-transport/src/connection/tests/recovery.rs index d7279e3bd1..c881eb98a1 100644 --- a/neqo-transport/src/connection/tests/recovery.rs +++ b/neqo-transport/src/connection/tests/recovery.rs @@ -646,7 +646,7 @@ fn trickle(sender: &mut Connection, receiver: &mut Connection, mut count: usize, let id = sender.stream_create(StreamType::UniDi).unwrap(); let mut maybe_ack = None; while count > 0 { - debug!("trickle: remaining={}", count); + debug!("trickle: remaining={count}"); assert_eq!(sender.stream_send(id, &[9]).unwrap(), 1); let dgram = sender.process(maybe_ack, now).dgram(); diff --git a/neqo-transport/src/crypto.rs b/neqo-transport/src/crypto.rs index b282f7799f..4fdc912e18 100644 --- a/neqo-transport/src/crypto.rs +++ b/neqo-transport/src/crypto.rs @@ -191,7 +191,7 @@ impl Crypto { data: Option<&[u8]>, ) -> Res<&HandshakeState> { let input = data.map(|d| { - trace!("Handshake record received {:0x?} ", d); + trace!("Handshake record received {d:0x?} "); let epoch = match space { PacketNumberSpace::Initial => TLS_EPOCH_INITIAL, PacketNumberSpace::Handshake => TLS_EPOCH_HANDSHAKE, @@ -212,7 +212,7 @@ impl Crypto { } Err(CryptoError::EchRetry(v)) => Err(Error::EchRetry(v)), Err(e) => { - info!("Handshake failed {:?}", e); + info!("Handshake failed {e:?}"); Err(self .tls .alert() @@ -316,7 +316,7 @@ impl Crypto { if r.ct != TLS_CT_HANDSHAKE { return Err(Error::ProtocolViolation); } - trace!("[{self}] Adding CRYPTO data {:?}", r); + trace!("[{self}] Adding CRYPTO data {r:?}"); self.streams .send(PacketNumberSpace::from(r.epoch), &r.data)?; } @@ -384,7 +384,7 @@ impl Crypto { ResumptionToken::new(enc.into(), t.expiration_time()) }) } else { - unreachable!("It is a server."); + unreachable!("It is a server"); } } @@ -392,7 +392,7 @@ impl Crypto { if let Agent::Client(c) = &self.tls { c.has_resumption_token() } else { - unreachable!("It is a server."); + unreachable!("It is a server"); } } } @@ -445,10 +445,7 @@ impl CryptoDxState { secret: &SymKey, cipher: Cipher, ) -> Res { - debug!( - "Making {:?} {} CryptoDxState, v={:?} cipher={}", - direction, epoch, version, cipher, - ); + debug!("Making {direction:?} {epoch} CryptoDxState, v={version:?} cipher={cipher}",); let hplabel = String::from(version.label_prefix()) + "hp"; Ok(Self { version, @@ -469,7 +466,7 @@ impl CryptoDxState { label: &str, dcid: &[u8], ) -> Res { - trace!("new_initial {:?} {}", version, ConnectionIdRef::from(dcid)); + trace!("new_initial {version:?} {}", ConnectionIdRef::from(dcid)); let salt = version.initial_salt(); let cipher = TLS_AES_128_GCM_SHA256; let initial_secret = hkdf::extract( @@ -576,8 +573,8 @@ impl CryptoDxState { Ok(()) } else if prev.used_pn.end > self.used_pn.start { debug!( - "[{self}] Found packet with too new packet number {} > {}, compared to {}", - self.used_pn.start, prev.used_pn.end, prev, + "[{self}] Found packet with too new packet number {} > {}, compared to {prev}", + self.used_pn.start, prev.used_pn.end, ); Err(Error::PacketNumberOverlap) } else { @@ -592,8 +589,8 @@ impl CryptoDxState { pub fn used(&mut self, pn: PacketNumber) -> Res<()> { if pn < self.min_pn { debug!( - "[{self}] Found packet with too old packet number: {} < {}", - pn, self.min_pn + "[{self}] Found packet with too old packet number: {pn} < {}", + self.min_pn ); return Err(Error::PacketNumberOverlap); } @@ -634,8 +631,7 @@ impl CryptoDxState { pub fn encrypt(&mut self, pn: PacketNumber, hdr: &[u8], body: &[u8]) -> Res> { debug_assert_eq!(self.direction, CryptoDxDirection::Write); trace!( - "[{self}] encrypt pn={} hdr={} body={}", - pn, + "[{self}] encrypt pn={pn} hdr={} body={}", hex(hdr), hex(body) ); @@ -669,8 +665,7 @@ impl CryptoDxState { pub fn decrypt(&mut self, pn: PacketNumber, hdr: &[u8], body: &[u8]) -> Res> { debug_assert_eq!(self.direction, CryptoDxDirection::Read); trace!( - "[{self}] decrypt pn={} hdr={} body={}", - pn, + "[{self}] decrypt pn={pn} hdr={} body={}", hex(hdr), hex(body) ); @@ -949,9 +944,7 @@ impl CryptoStates { for v in versions { debug!( - "[{self}] Creating initial cipher state v={:?}, role={:?} dcid={}", - v, - role, + "[{self}] Creating initial cipher state v={v:?}, role={role:?} dcid={}", hex(dcid) ); @@ -1526,7 +1519,7 @@ impl CryptoStreams { }; for (offset, length) in written.into_iter().flatten() { cs.tx.mark_as_sent(offset, length); - debug!("CRYPTO for {} offset={}, len={}", space, offset, length); + debug!("CRYPTO for {space} offset={offset}, len={length}"); tokens.push(RecoveryToken::Crypto(CryptoRecoveryToken { space, offset, diff --git a/neqo-transport/src/ecn.rs b/neqo-transport/src/ecn.rs index 6f475a356e..a020af938e 100644 --- a/neqo-transport/src/ecn.rs +++ b/neqo-transport/src/ecn.rs @@ -188,9 +188,9 @@ impl EcnInfo { pub fn on_packet_sent(&mut self, stats: &mut Stats) { if let EcnValidationState::Testing { probes_sent, .. } = &mut self.state { *probes_sent += 1; - debug!("ECN probing: sent {} probes", probes_sent); + debug!("ECN probing: sent {probes_sent} probes"); if *probes_sent == ECN_TEST_COUNT { - debug!("ECN probing concluded with {} probes sent", probes_sent); + debug!("ECN probing concluded with {probes_sent} probes sent"); self.state.set(EcnValidationState::Unknown, stats); } } @@ -231,10 +231,7 @@ impl EcnInfo { // If we have lost all initial probes a bunch of times, we can conclude that the path // is not ECN capable and likely drops all ECN marked packets. if probes_sent == probes_lost && *probes_lost == ECN_TEST_COUNT_INITIAL_PHASE { - debug!( - "ECN validation failed, all {} initial marked packets were lost", - probes_lost - ); + debug!("ECN validation failed, all {probes_lost} initial marked packets were lost"); self.disable_ecn(stats, EcnValidationError::BlackHole); } } @@ -302,9 +299,7 @@ impl EcnInfo { let sum_inc = ecn_diff[IpTosEcn::Ect0] + ecn_diff[IpTosEcn::Ce]; if sum_inc < newly_acked_sent_with_ect0 { warn!( - "ECN validation failed, ACK counted {} new marks, but {} of newly acked packets were sent with ECT(0)", - sum_inc, - newly_acked_sent_with_ect0 + "ECN validation failed, ACK counted {sum_inc} new marks, but {newly_acked_sent_with_ect0} of newly acked packets were sent with ECT(0)" ); self.disable_ecn(stats, EcnValidationError::Bleaching); } else if ecn_diff[IpTosEcn::Ect1] > 0 { diff --git a/neqo-transport/src/fc.rs b/neqo-transport/src/fc.rs index e8deec33eb..43a8f23fd1 100644 --- a/neqo-transport/src/fc.rs +++ b/neqo-transport/src/fc.rs @@ -327,9 +327,8 @@ impl ReceiverFlowControl<()> { pub fn consume(&mut self, count: u64) -> Res<()> { if self.consumed + count > self.max_allowed { trace!( - "Session RX window exceeded: consumed:{} new:{} limit:{}", + "Session RX window exceeded: consumed:{} new:{count} limit:{}", self.consumed, - count, self.max_allowed ); return Err(Error::FlowControlError); @@ -384,7 +383,7 @@ impl ReceiverFlowControl { } if consumed > self.max_allowed { - trace!("Stream RX window exceeded: {}", consumed); + trace!("Stream RX window exceeded: {consumed}"); return Err(Error::FlowControlError); } let new_consumed = consumed - self.consumed; diff --git a/neqo-transport/src/frame.rs b/neqo-transport/src/frame.rs index 1ebe078244..933ef25cc4 100644 --- a/neqo-transport/src/frame.rs +++ b/neqo-transport/src/frame.rs @@ -371,7 +371,7 @@ impl<'a> Frame<'a> { pub fn dump(&self) -> String { match self { Self::Crypto { offset, data } => { - format!("Crypto {{ offset: {}, len: {} }}", offset, data.len()) + format!("Crypto {{ offset: {offset}, len: {} }}", data.len()) } Self::Stream { stream_id, @@ -380,12 +380,10 @@ impl<'a> Frame<'a> { data, fin, } => format!( - "Stream {{ stream_id: {}, offset: {}, len: {}{}, fin: {} }}", + "Stream {{ stream_id: {}, offset: {offset}, len: {}{}, fin: {fin} }}", stream_id.as_u64(), - offset, if *fill { ">>" } else { "" }, data.len(), - fin, ), Self::Padding(length) => format!("Padding {{ len: {length} }}"), Self::Datagram { data, .. } => format!("Datagram {{ len: {} }}", data.len()), diff --git a/neqo-transport/src/lib.rs b/neqo-transport/src/lib.rs index 897d1346c9..9950d6dc52 100644 --- a/neqo-transport/src/lib.rs +++ b/neqo-transport/src/lib.rs @@ -179,7 +179,7 @@ impl Error { impl From for Error { fn from(err: CryptoError) -> Self { - warn!("Crypto operation failed {:?}", err); + warn!("Crypto operation failed {err:?}"); match err { CryptoError::EchRetry(config) => Self::EchRetry(config), _ => Self::CryptoError(err), diff --git a/neqo-transport/src/pace.rs b/neqo-transport/src/pace.rs index eb8991e2e2..c0e6a6a20e 100644 --- a/neqo-transport/src/pace.rs +++ b/neqo-transport/src/pace.rs @@ -108,7 +108,7 @@ impl Pacer { return; } - trace!("[{self}] spend {} over {}, {:?}", count, cwnd, rtt); + trace!("[{self}] spend {count} over {cwnd}, {rtt:?}"); // Increase the capacity by: // `(now - self.t) * PACER_SPEEDUP * cwnd / rtt` // That is, the elapsed fraction of the RTT times rate that data is added. @@ -188,7 +188,7 @@ mod tests { assert_eq!( p.next(SHORT_RTT, CWND), n, - "Expect packet to be sent immediately, instead of being paced below timer granularity." + "Expect packet to be sent immediately, instead of being paced below timer granularity" ); } } diff --git a/neqo-transport/src/packet/mod.rs b/neqo-transport/src/packet/mod.rs index 707d4b04a3..a006d66649 100644 --- a/neqo-transport/src/packet/mod.rs +++ b/neqo-transport/src/packet/mod.rs @@ -857,7 +857,7 @@ impl<'a> PublicPacket<'a> { // fail is if the cryptographic module is bad or the packet is // too small (which is public information). let (key_phase, pn, header, body) = self.decrypt_header(rx)?; - trace!("[{rx}] decoded header: {:?}", header); + trace!("[{rx}] decoded header: {header:?}"); let Some(rx) = crypto.rx(version, cspace, key_phase) else { return Err(Error::DecryptError); }; @@ -878,7 +878,7 @@ impl<'a> PublicPacket<'a> { } else if crypto.rx_pending(cspace) { Err(Error::KeysPending(cspace)) } else { - trace!("keys for {:?} already discarded", cspace); + trace!("keys for {cspace:?} already discarded"); Err(Error::KeysDiscarded(cspace)) } } diff --git a/neqo-transport/src/packet/retry.rs b/neqo-transport/src/packet/retry.rs index 3260916677..53b04dbc50 100644 --- a/neqo-transport/src/packet/retry.rs +++ b/neqo-transport/src/packet/retry.rs @@ -43,7 +43,7 @@ where } .try_with(|aead| f(&aead.borrow())) .map_err(|e| { - error!("Unable to access Retry AEAD: {:?}", e); + error!("Unable to access Retry AEAD: {e:?}"); Error::InternalError })? } diff --git a/neqo-transport/src/path.rs b/neqo-transport/src/path.rs index 9454da935d..cf5486f472 100644 --- a/neqo-transport/src/path.rs +++ b/neqo-transport/src/path.rs @@ -365,8 +365,7 @@ impl Paths { .is_some_and(|target| Rc::ptr_eq(target, p)) { info!( - "[{}] NEW_CONNECTION_ID with Retire Prior To forced migration to fail", - path + "[{path}] NEW_CONNECTION_ID with Retire Prior To forced migration to fail" ); *migration_target = None; } @@ -596,7 +595,7 @@ impl Path { /// Set whether this path is primary. pub(crate) fn set_primary(&mut self, primary: bool, now: Instant) { - trace!("[{self}] Make primary {}", primary); + trace!("[{self}] Make primary {primary}"); debug_assert!(self.remote_cid.is_some()); self.primary = primary; if !primary { @@ -607,7 +606,7 @@ impl Path { /// Set the current path as valid. This updates the time that the path was /// last validated and cancels any path validation. pub fn set_valid(&mut self, now: Instant) { - debug!("[{self}] Path validated {:?}", now); + debug!("[{self}] Path validated {now:?}"); self.state = ProbeState::Valid; self.validated = Some(now); } @@ -778,7 +777,7 @@ impl Path { // Send PATH_CHALLENGE. if let ProbeState::ProbeNeeded { probe_count } = self.state { - trace!("[{self}] Initiating path challenge {}", probe_count); + trace!("[{self}] Initiating path challenge {probe_count}"); let data = random::<8>(); builder.encode_varint(FRAME_TYPE_PATH_CHALLENGE); builder.encode(&data); diff --git a/neqo-transport/src/pmtud.rs b/neqo-transport/src/pmtud.rs index f82a9ea3af..f2d8dfef7e 100644 --- a/neqo-transport/src/pmtud.rs +++ b/neqo-transport/src/pmtud.rs @@ -270,8 +270,8 @@ impl Pmtud { let last_ok = first_failed - 1; debug!( - "Packet of size > {} lost >= {} times", - self.search_table[last_ok], MAX_PROBES + "Packet of size > {} lost >= {MAX_PROBES} times", + self.search_table[last_ok] ); if self.probe_state == Probe::NotNeeded { // We saw multiple losses of packets <= the current MTU outside of PMTU discovery, @@ -457,7 +457,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - debug!("Reducing MTU to {}", smaller_mtu); + debug!("Reducing MTU to {smaller_mtu}"); // Drop packets > smaller_mtu until we need a probe again. while !pmtud.needs_probe() { let pn = prot.next_pn(); @@ -510,7 +510,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - debug!("Increasing MTU to {}", larger_mtu); + debug!("Increasing MTU to {larger_mtu}"); let now = now + PMTU_RAISE_TIMER; pmtud.maybe_fire_raise_timer(now); while pmtud.needs_probe() { diff --git a/neqo-transport/src/recovery/mod.rs b/neqo-transport/src/recovery/mod.rs index 0ed45172d1..64e4325cce 100644 --- a/neqo-transport/src/recovery/mod.rs +++ b/neqo-transport/src/recovery/mod.rs @@ -324,10 +324,8 @@ impl LossRecoverySpace { self.remove_old_lost(now, cleanup_delay); trace!( - "detect lost {}: now={:?} delay={:?}", + "detect lost {}: now={now:?} delay={loss_delay:?}", self.space, - now, - loss_delay, ); self.first_ooo_time = None; @@ -342,17 +340,14 @@ impl LossRecoverySpace { // Packets sent before now - loss_delay are deemed lost. if packet.time_sent() + loss_delay <= now { trace!( - "lost={}, time sent {:?} is before lost_delay {:?}", + "lost={}, time sent {:?} is before lost_delay {loss_delay:?}", packet.pn(), - packet.time_sent(), - loss_delay + packet.time_sent() ); } else if largest_acked >= Some(packet.pn() + PACKET_THRESHOLD) { trace!( - "lost={}, is >= {} from largest acked {:?}", - packet.pn(), - PACKET_THRESHOLD, - largest_acked + "lost={}, is >= {PACKET_THRESHOLD} from largest acked {largest_acked:?}", + packet.pn() ); } else { if largest_acked.is_some() { @@ -552,14 +547,13 @@ impl LossRecovery { pub fn on_packet_sent(&mut self, path: &PathRef, mut sent_packet: SentPacket, now: Instant) { let pn_space = PacketNumberSpace::from(sent_packet.packet_type()); - trace!("[{self}] packet {}-{} sent", pn_space, sent_packet.pn()); + trace!("[{self}] packet {pn_space}-{} sent", sent_packet.pn()); if let Some(space) = self.spaces.get_mut(pn_space) { path.borrow_mut().packet_sent(&mut sent_packet, now); space.on_packet_sent(sent_packet); } else { warn!( - "[{self}] ignoring {}-{} from dropped space", - pn_space, + "[{self}] ignoring {pn_space}-{} from dropped space", sent_packet.pn() ); } @@ -647,8 +641,7 @@ impl LossRecovery { } debug!( - "[{self}] ACK for {} - largest_acked={}", - pn_space, + "[{self}] ACK for {pn_space} - largest_acked={}", largest_acked_pkt.pn() ); @@ -735,7 +728,7 @@ impl LossRecovery { /// Discard state for a given packet number space. pub fn discard(&mut self, primary_path: &PathRef, space: PacketNumberSpace, now: Instant) { - debug!("[{self}] Reset loss recovery state for {}", space); + debug!("[{self}] Reset loss recovery state for {space}"); let mut path = primary_path.borrow_mut(); for p in self.spaces.drop_space(space) { path.discard_packet(&p, now, &mut self.stats.borrow_mut()); @@ -762,11 +755,7 @@ impl LossRecovery { } else { None }; - trace!( - "[{self}] next_timeout loss={:?} pto={:?}", - loss_time, - pto_time - ); + trace!("[{self}] next_timeout loss={loss_time:?} pto={pto_time:?}"); match (loss_time, pto_time) { (Some(loss_time), Some(pto_time)) => Some(min(loss_time, pto_time)), (Some(loss_time), None) => Some(loss_time), @@ -870,7 +859,7 @@ impl LossRecovery { if let Some(t) = self.pto_time(rtt, *pn_space) { allow_probes[*pn_space] = true; if t <= now { - debug!("[{self}] PTO timer fired for {}", pn_space); + debug!("[{self}] PTO timer fired for {pn_space}"); let space = self.spaces.get_mut(*pn_space).unwrap(); lost.extend( space @@ -886,13 +875,13 @@ impl LossRecovery { // This has to happen outside the loop. Increasing the PTO count here causes the // pto_time to increase which might cause PTO for later packet number spaces to not fire. if let Some(pn_space) = pto_space { - trace!("[{self}] PTO {}, probing {:?}", pn_space, allow_probes); + trace!("[{self}] PTO {pn_space}, probing {allow_probes:?}"); self.fire_pto(pn_space, allow_probes, now); } } pub fn timeout(&mut self, primary_path: &PathRef, now: Instant) -> Vec { - trace!("[{self}] timeout {:?}", now); + trace!("[{self}] timeout {now:?}"); let loss_delay = primary_path.borrow().rtt().loss_delay(); let confirmed = self.confirmed(); @@ -926,7 +915,7 @@ impl LossRecovery { /// what the current congestion window is, and what the pacer says. #[allow(clippy::option_if_let_else)] pub fn send_profile(&mut self, path: &Path, now: Instant) -> SendProfile { - trace!("[{self}] get send profile {:?}", now); + trace!("[{self}] get send profile {now:?}"); let sender = path.sender(); let mtu = path.plpmtu(); if let Some(profile) = self diff --git a/neqo-transport/src/recv_stream.rs b/neqo-transport/src/recv_stream.rs index f900cbb165..0162b66d5d 100644 --- a/neqo-transport/src/recv_stream.rs +++ b/neqo-transport/src/recv_stream.rs @@ -133,7 +133,7 @@ impl RxStreamOrderer { /// Only when `u64` values cannot be converted to `usize`, which only /// happens on 32-bit machines that hold far too much data at the same time. pub fn inbound_frame(&mut self, mut new_start: u64, mut new_data: &[u8]) { - trace!("Inbound data offset={} len={}", new_start, new_data.len()); + trace!("Inbound data offset={new_start} len={}", new_data.len()); // Get entry before where new entry would go, so we can see if we already // have the new bytes. @@ -166,12 +166,7 @@ impl RxStreamOrderer { // Add a range containing only new data // (In-order frames will take this path, with no overlap) let overlap = prev_end.saturating_sub(new_start); - trace!( - "New frame {}-{} received, overlap: {}", - new_start, - new_end, - overlap - ); + trace!("New frame {new_start}-{new_end} received, overlap: {overlap}"); new_start += overlap; new_data = &new_data[usize::try_from(overlap).unwrap()..]; // If it is small enough, extend the previous buffer. @@ -183,15 +178,11 @@ impl RxStreamOrderer { // NNNN // NNNN // Do nothing - trace!( - "Dropping frame with already-received range {}-{}", - new_start, - new_end - ); + trace!("Dropping frame with already-received range {new_start}-{new_end}"); return; } } else { - trace!("New frame {}-{} received", new_start, new_end); + trace!("New frame {new_start}-{new_end} received"); false }; @@ -229,21 +220,14 @@ impl RxStreamOrderer { break; } else if next_end >= new_end { trace!( - "New frame {}-{} overlaps with next frame by {}, truncating", - new_start, - new_end, - overlap + "New frame {new_start}-{new_end} overlaps with next frame by {overlap}, truncating" ); let truncate_to = new_data.len() - usize::try_from(overlap).unwrap(); to_add = &new_data[..truncate_to]; break; } trace!( - "New frame {}-{} spans entire next frame {}-{}, replacing", - new_start, - new_end, - next_start, - next_end + "New frame {new_start}-{new_end} spans entire next frame {next_start}-{next_end}, replacing" ); to_remove.push(next_start); // Continue, since we may have more overlaps @@ -1018,7 +1002,7 @@ mod tests { fn recv_ranges(ranges: &[Range], available: usize) { const ZEROES: &[u8] = &[0; 100]; - trace!("recv_ranges {:?}", ranges); + trace!("recv_ranges {ranges:?}"); let mut s = RxStreamOrderer::default(); for r in ranges { @@ -1030,7 +1014,7 @@ mod tests { let mut total_recvd = 0; loop { let recvd = s.read(&mut buf[..]); - trace!("recv_ranges read {}", recvd); + trace!("recv_ranges read {recvd}"); total_recvd += recvd; if recvd == 0 { assert_eq!(total_recvd, available); diff --git a/neqo-transport/src/rtt.rs b/neqo-transport/src/rtt.rs index bc0483b73e..6bbade740f 100644 --- a/neqo-transport/src/rtt.rs +++ b/neqo-transport/src/rtt.rs @@ -75,7 +75,7 @@ impl RttEstimate { } pub fn set_initial(&mut self, rtt: Duration) { - trace!("initial RTT={:?}", rtt); + trace!("initial RTT={rtt:?}"); if rtt >= GRANULARITY { // Ignore if the value is too small. self.init(rtt); diff --git a/neqo-transport/src/send_stream.rs b/neqo-transport/src/send_stream.rs index 8c6fd8dda2..05e50f5dc8 100644 --- a/neqo-transport/src/send_stream.rs +++ b/neqo-transport/src/send_stream.rs @@ -406,7 +406,7 @@ impl RangeTracker { fn unmark_range(&mut self, off: u64, len: usize) { if len == 0 { - debug!("unmark 0-length range at {}", off); + debug!("unmark 0-length range at {off}"); return; } @@ -425,10 +425,7 @@ impl RangeTracker { if *cur_off + *cur_len > off { if *cur_state == RangeState::Acked { debug!( - "Attempted to unmark Acked range {}-{} with unmark_range {}-{}", - cur_off, - cur_len, - off, + "Attempted to unmark Acked range {cur_off}-{cur_len} with unmark_range {off}-{}", off + len ); } else { @@ -440,10 +437,7 @@ impl RangeTracker { if *cur_state == RangeState::Acked { debug!( - "Attempted to unmark Acked range {}-{} with unmark_range {}-{}", - cur_off, - cur_len, - off, + "Attempted to unmark Acked range {cur_off}-{cur_len} with unmark_range {off}-{}", off + len ); continue; @@ -761,7 +755,7 @@ impl SendStream { tokens: &mut Vec, stats: &mut FrameStats, ) { - trace!("write STREAM frames at priority {:?}", priority); + trace!("write STREAM frames at priority {priority:?}"); if !self.write_reset_frame(priority, builder, tokens, stats) { self.write_blocked_frame(priority, builder, tokens, stats); self.write_stream_frame(priority, builder, tokens, stats); @@ -927,7 +921,7 @@ impl SendStream { fn length_and_fill(data_len: usize, space: usize) -> (usize, bool) { if data_len >= space { // More data than space allows, or an exact fit => fast path. - trace!("SendStream::length_and_fill fill {}", space); + trace!("SendStream::length_and_fill fill {space}"); return (space, true); } @@ -940,7 +934,7 @@ impl SendStream { // From here we can always fit `data_len`, but we might as well fill // if there is no space for the length field plus another frame. let fill = data_len + length_len + PacketBuilder::MINIMUM_FRAME_SIZE > space; - trace!("SendStream::length_and_fill {} fill {}", data_len, fill); + trace!("SendStream::length_and_fill {data_len} fill {fill}"); (data_len, fill) } @@ -1086,7 +1080,7 @@ impl SendStream { { fc.frame_lost(limit); } else { - trace!("[{self}] Ignoring lost STREAM_DATA_BLOCKED({})", limit); + trace!("[{self}] Ignoring lost STREAM_DATA_BLOCKED({limit})"); } } @@ -1693,7 +1687,7 @@ impl SendStreams { tokens: &mut Vec, stats: &mut FrameStats, ) { - trace!("write STREAM frames at priority {:?}", priority); + trace!("write STREAM frames at priority {priority:?}"); // WebTransport data (which is Normal) may have a SendOrder // priority attached. The spec states (6.3 write-chunk 6.1): @@ -1730,7 +1724,7 @@ impl SendStreams { trace!("processing streams... unfair:"); for stream in self.map.values_mut() { if !stream.is_fair() { - trace!(" {}", stream); + trace!(" {stream}"); if !stream.write_frames_with_early_return(priority, builder, tokens, stats) { break; } @@ -1746,7 +1740,7 @@ impl SendStreams { for stream_id in stream_ids { let stream = self.map.get_mut(&stream_id).unwrap(); if let Some(order) = stream.sendorder() { - trace!(" {} ({})", stream_id, order); + trace!(" {stream_id} ({order})"); } else { trace!(" None"); } @@ -2943,14 +2937,7 @@ mod tests { fn frame_sent_sid(stream: u64, offset: usize, len: usize, fin: bool, space: usize) -> bool { const BUF: &[u8] = &[0x42; 128]; - trace!( - "frame_sent stream={} offset={} len={} fin={}, space={}", - stream, - offset, - len, - fin, - space - ); + trace!("frame_sent stream={stream} offset={offset} len={len} fin={fin}, space={space}"); let mut s = stream_with_sent(stream, offset); @@ -3058,7 +3045,7 @@ mod tests { fn stream_frame_at_boundary(data: &[u8]) { fn send_with_extra_capacity(data: &[u8], extra: usize, expect_full: bool) -> Vec { - trace!("send_with_extra_capacity {} + {}", data.len(), extra); + trace!("send_with_extra_capacity {} + {extra}", data.len()); let mut s = stream_with_sent(0, 0); s.send(data).unwrap(); s.close(); diff --git a/neqo-transport/src/sender.rs b/neqo-transport/src/sender.rs index bceb40502c..91ce62492f 100644 --- a/neqo-transport/src/sender.rs +++ b/neqo-transport/src/sender.rs @@ -94,9 +94,8 @@ impl PacketSender { let current_mtu = self.pmtud().plpmtu(); if current_mtu != self.pacer.mtu() { debug!( - "PLPMTU changed from {} to {}, updating pacer", - self.pacer.mtu(), - current_mtu + "PLPMTU changed from {} to {current_mtu}, updating pacer", + self.pacer.mtu() ); self.pacer.set_mtu(current_mtu); } diff --git a/neqo-transport/src/server.rs b/neqo-transport/src/server.rs index 6df956f416..1696667f8d 100644 --- a/neqo-transport/src/server.rs +++ b/neqo-transport/src/server.rs @@ -271,7 +271,7 @@ impl Server { format!("server-{odcid}"), ) .unwrap_or_else(|e| { - error!("failed to create NeqoQlog: {}", e); + error!("failed to create NeqoQlog: {e}"); NeqoQlog::disabled() }) }) @@ -354,7 +354,7 @@ impl Server { // All packets in the datagram are routed to the same connection. let res = PublicPacket::decode(&dgram[..], self.cid_generator.borrow().as_decoder()); let Ok((packet, _remainder)) = res else { - trace!("[{self}] Discarding {:?}", dgram); + trace!("[{self}] Discarding {dgram:?}"); return Output::None; }; @@ -431,7 +431,7 @@ impl Server { } PacketType::ZeroRtt => { let dcid = ConnectionId::from(packet.dcid()); - debug!("[{self}] Dropping 0-RTT for unknown connection {}", dcid); + debug!("[{self}] Dropping 0-RTT for unknown connection {dcid}"); Output::None } PacketType::OtherVersion => unreachable!(), diff --git a/neqo-transport/src/streams.rs b/neqo-transport/src/streams.rs index ca3387c19c..c949cc7215 100644 --- a/neqo-transport/src/streams.rs +++ b/neqo-transport/src/streams.rs @@ -184,7 +184,7 @@ impl Streams { } Frame::DataBlocked { data_limit } => { // Should never happen since we set data limit to max - warn!("Received DataBlocked with data limit {}", data_limit); + warn!("Received DataBlocked with data limit {data_limit}"); stats.data_blocked += 1; self.handle_data_blocked(); } diff --git a/neqo-transport/src/tparams.rs b/neqo-transport/src/tparams.rs index 10463e2288..df2a1785f5 100644 --- a/neqo-transport/src/tparams.rs +++ b/neqo-transport/src/tparams.rs @@ -140,7 +140,7 @@ pub enum TransportParameter { impl TransportParameter { fn encode(&self, enc: &mut Encoder, tp: TransportParameterId) { - trace!("TP encoded; type 0x{:02x} val {:?}", tp, self); + trace!("TP encoded; type 0x{tp:02x} val {self:?}"); enc.encode_varint(tp); match self { Self::Bytes(a) => { @@ -251,7 +251,7 @@ impl TransportParameter { fn decode(dec: &mut Decoder) -> Res> { let tp = dec.decode_varint().ok_or(Error::NoMoreData)?; let content = dec.decode_vvec().ok_or(Error::NoMoreData)?; - trace!("TP {:x} length {:x}", tp, content.len()); + trace!("TP {tp:x} length {:x}", content.len()); let mut d = Decoder::from(content); let value = match tp { ORIGINAL_DESTINATION_CONNECTION_ID @@ -310,7 +310,7 @@ impl TransportParameter { if d.remaining() > 0 { return Err(Error::TooMuchData); } - trace!("TP decoded; type 0x{:02x} val {:?}", tp, value); + trace!("TP decoded; type 0x{tp:02x} val {value:?}"); Ok(Some((tp, value))) } } @@ -629,9 +629,7 @@ impl TransportParametersHandler { fn compatible_upgrade(&mut self, remote_tp: &TransportParameters) -> Res<()> { if let Some((current, other)) = remote_tp.get_versions() { trace!( - "Peer versions: {:x} {:x?}; config {:?}", - current, - other, + "Peer versions: {current:x} {other:x?}; config {:?}", self.versions, ); @@ -641,8 +639,7 @@ impl TransportParametersHandler { Ok(()) } else { info!( - "Chosen version {:x} is not compatible with initial version {:x}", - current, + "Chosen version {current:x} is not compatible with initial version {:x}", self.versions.initial().wire_version(), ); Err(Error::TransportParameterError) @@ -650,8 +647,7 @@ impl TransportParametersHandler { } else { if current != self.versions.initial().wire_version() { info!( - "Current version {:x} != own version {:x}", - current, + "Current version {current:x} != own version {:x}", self.versions.initial().wire_version(), ); return Err(Error::TransportParameterError); @@ -660,9 +656,8 @@ impl TransportParametersHandler { if let Some(preferred) = self.versions.preferred_compatible(other) { if preferred != self.versions.initial() { info!( - "Compatible upgrade {:?} ==> {:?}", - self.versions.initial(), - preferred + "Compatible upgrade {:?} ==> {preferred:?}", + self.versions.initial() ); self.versions.set_initial(preferred); self.local.compatible_upgrade(preferred); @@ -685,7 +680,7 @@ impl ExtensionHandler for TransportParametersHandler { return ExtensionWriterResult::Skip; } - debug!("Writing transport parameters, msg={:?}", msg); + debug!("Writing transport parameters, msg={msg:?}"); // TODO(ekr@rtfm.com): Modify to avoid a copy. let mut enc = Encoder::default(); @@ -697,8 +692,7 @@ impl ExtensionHandler for TransportParametersHandler { fn handle(&mut self, msg: HandshakeMessage, d: &[u8]) -> ExtensionHandlerResult { trace!( - "Handling transport parameters, msg={:?} value={}", - msg, + "Handling transport parameters, msg={msg:?} value={}", hex(d), ); diff --git a/neqo-transport/src/tracking.rs b/neqo-transport/src/tracking.rs index ebf83a94f1..00ae5c644c 100644 --- a/neqo-transport/src/tracking.rs +++ b/neqo-transport/src/tracking.rs @@ -181,12 +181,12 @@ impl PacketRange { assert!(!self.contains(pn)); // Only insert if this is adjacent the current range. if (self.largest + 1) == pn { - trace!("[{self}] Adding largest {}", pn); + trace!("[{self}] Adding largest {pn}"); self.largest += 1; self.ack_needed = true; InsertionResult::Largest } else if self.smallest == (pn + 1) { - trace!("[{self}] Adding smallest {}", pn); + trace!("[{self}] Adding smallest {pn}"); self.smallest -= 1; self.ack_needed = true; InsertionResult::Smallest @@ -197,7 +197,7 @@ impl PacketRange { /// Maybe merge a higher-numbered range into this. fn merge_larger(&mut self, other: &Self) { - info!("[{self}] Merging {}", other); + info!("[{self}] Merging {other}"); // This only works if they are immediately adjacent. assert_eq!(self.largest + 1, other.smallest); @@ -370,10 +370,10 @@ impl RecvdPackets { if self.ranges.len() > MAX_TRACKED_RANGES { let oldest = self.ranges.pop_back().unwrap(); if oldest.ack_needed { - warn!("[{self}] Dropping unacknowledged ACK range: {}", oldest); + warn!("[{self}] Dropping unacknowledged ACK range: {oldest}"); // TODO(mt) Record some statistics about this so we can tune MAX_TRACKED_RANGES. } else { - debug!("[{self}] Drop ACK range: {}", oldest); + debug!("[{self}] Drop ACK range: {oldest}"); } self.min_tracked = oldest.largest + 1; } @@ -383,7 +383,7 @@ impl RecvdPackets { /// Return true if the packet was the largest received so far. pub fn set_received(&mut self, now: Instant, pn: PacketNumber, ack_eliciting: bool) -> bool { let next_in_order_pn = self.ranges.front().map_or(0, |r| r.largest + 1); - trace!("[{self}] received {}, next: {}", pn, next_in_order_pn); + trace!("[{self}] received {pn}, next: {next_in_order_pn}"); self.add(pn); self.trim_ranges(); @@ -414,7 +414,7 @@ impl RecvdPackets { // of the change is very small. self.ack_time.unwrap_or_else(|| now + self.ack_delay) }; - debug!("[{self}] Set ACK timer to {:?}", ack_time); + debug!("[{self}] Set ACK timer to {ack_time:?}"); self.ack_time = Some(ack_time); } largest @@ -423,7 +423,7 @@ impl RecvdPackets { /// If we just received a PING frame, we should immediately acknowledge. pub fn immediate_ack(&mut self, now: Instant) { self.ack_time = Some(now); - debug!("[{self}] immediate_ack at {:?}", now); + debug!("[{self}] immediate_ack at {now:?}"); } /// Check if the packet is a duplicate. @@ -602,7 +602,7 @@ impl AckTracker { #[cfg(debug_assertions)] for (space, recvd) in &self.spaces { if let Some(recvd) = recvd { - trace!("ack_time for {} = {:?}", space, recvd.ack_time()); + trace!("ack_time for {space} = {:?}", recvd.ack_time()); } } diff --git a/neqo-transport/src/version.rs b/neqo-transport/src/version.rs index e6430968b7..c3771dda13 100644 --- a/neqo-transport/src/version.rs +++ b/neqo-transport/src/version.rs @@ -189,8 +189,8 @@ impl VersionConfig { /// and by the client on resumption. pub(crate) fn set_initial(&mut self, initial: Version) { debug!( - "Overwrite initial version {:?} ==> {:?}", - self.initial, initial + "Overwrite initial version {:?} ==> {initial:?}", + self.initial ); assert!(self.all.contains(&initial)); self.initial = initial; diff --git a/neqo-udp/src/lib.rs b/neqo-udp/src/lib.rs index 1d6d1d6b9f..827bdae5a0 100644 --- a/neqo-udp/src/lib.rs +++ b/neqo-udp/src/lib.rs @@ -72,8 +72,8 @@ pub fn recv_inner<'a>( if meta.len == 0 || meta.stride == 0 { debug!( - "ignoring datagram from {} to {} len {} stride {}", - meta.addr, local_address, meta.len, meta.stride + "ignoring datagram from {} to {local_address} len {} stride {}", + meta.addr, meta.len, meta.stride ); continue; } @@ -82,10 +82,9 @@ pub fn recv_inner<'a>( }; trace!( - "received {} bytes from {} to {} in {} segments", + "received {} bytes from {} to {local_address} in {} segments", data.len(), meta.addr, - local_address, data.len().div_ceil(meta.stride), ); @@ -267,7 +266,7 @@ mod tests { assert_eq!( SEGMENT_SIZE, d.len(), - "Expect received datagrams to have same length as sent datagrams." + "Expect received datagrams to have same length as sent datagrams" ); num_received += 1; }); diff --git a/test-fixture/src/sim/connection.rs b/test-fixture/src/sim/connection.rs index 9e41d3b41b..4891a1b12f 100644 --- a/test-fixture/src/sim/connection.rs +++ b/test-fixture/src/sim/connection.rs @@ -146,7 +146,7 @@ impl Node for ConnectionNode { let mut active = false; while let Some(e) = self.c.next_event() { - trace!("[{}] received event {:?}", self.c, e); + trace!("[{}] received event {e:?}", self.c); // Perform authentication automatically. if matches!(e, ConnectionEvent::AuthenticationNeeded) { @@ -176,7 +176,7 @@ impl Node for ConnectionNode { } fn print_summary(&self, test_name: &str) { - info!("{}: {:?}", test_name, self.c.stats()); + info!("{test_name}: {:?}", self.c.stats()); } } @@ -234,7 +234,7 @@ impl SendData { fn make_stream(&mut self, c: &mut Connection) { if self.stream_id.is_none() { if let Ok(stream_id) = c.stream_create(StreamType::UniDi) { - debug!("[{c}] made stream {} for sending", stream_id); + debug!("[{c}] made stream {stream_id} for sending"); self.stream_id = Some(stream_id); } } @@ -250,7 +250,7 @@ impl SendData { return status; } self.remaining -= sent; - trace!("sent {} remaining {}", sent, self.remaining); + trace!("sent {sent} remaining {}", self.remaining); if self.remaining == 0 { c.stream_close_send(stream_id).unwrap(); return GoalStatus::Done; @@ -316,7 +316,7 @@ impl ReceiveData { loop { let end = min(self.remaining, buf.len()); let (recvd, _) = c.stream_recv(stream_id, &mut buf[..end]).unwrap(); - trace!("received {} remaining {}", recvd, self.remaining); + trace!("received {recvd} remaining {}", self.remaining); if recvd == 0 { return status; } diff --git a/test-fixture/src/sim/mod.rs b/test-fixture/src/sim/mod.rs index 23774395c8..258946d220 100644 --- a/test-fixture/src/sim/mod.rs +++ b/test-fixture/src/sim/mod.rs @@ -213,7 +213,7 @@ impl Simulator { Active } Output::Callback(delay) => { - trace!("[{}] => callback {:?}", self.name, delay); + trace!("[{}] => callback {delay:?}", self.name); assert_ne!(delay, Duration::new(0, 0)); Waiting(now + delay) } diff --git a/test-fixture/src/sim/taildrop.rs b/test-fixture/src/sim/taildrop.rs index 1d7331d90c..586eda7e55 100644 --- a/test-fixture/src/sim/taildrop.rs +++ b/test-fixture/src/sim/taildrop.rs @@ -177,8 +177,8 @@ impl Node for TailDrop { fn print_summary(&self, test_name: &str) { info!( - "{}: taildrop: rx {} drop {} tx {} maxq {}", - test_name, self.received, self.dropped, self.delivered, self.maxq, + "{test_name}: taildrop: rx {} drop {} tx {} maxq {}", + self.received, self.dropped, self.delivered, self.maxq, ); } } From 649e29ac9713a95dd4264d8881a5c04b169e0aea Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 12:17:25 +0200 Subject: [PATCH 4/9] Remove unneeded `format!` calls --- neqo-crypto/src/agent.rs | 14 +++----------- neqo-crypto/src/cert.rs | 2 +- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index dbdc43b20c..9ebe284d04 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -108,7 +108,7 @@ fn get_alpn(fd: *mut ssl::PRFileDesc, pre: bool) -> Res> { } _ => None, }; - trace!("[{}] got ALPN {alpn:?}", format!("{fd:p}")); + trace!("[{fd:p}] got ALPN {alpn:?}"); Ok(alpn) } @@ -370,11 +370,7 @@ impl SecretAgent { if st.is_none() { *st = Some(alert.description); } else { - warn!( - "[{}] duplicate alert {}", - format!("{fd:p}"), - alert.description - ); + warn!("[{fd:p}] duplicate alert {}", alert.description); } } } @@ -896,11 +892,7 @@ impl Client { let len = usize::try_from(len).unwrap(); let mut v = Vec::with_capacity(len); v.extend_from_slice(null_safe_slice(token, len)); - debug!( - "[{}] Got resumption token {}", - format!("{fd:p}"), - hex_snip_middle(&v) - ); + debug!("[{fd:p}] Got resumption token {}", hex_snip_middle(&v)); if resumption.len() >= MAX_TICKETS { resumption.remove(0); diff --git a/neqo-crypto/src/cert.rs b/neqo-crypto/src/cert.rs index 71842fa38d..0fe936bc19 100644 --- a/neqo-crypto/src/cert.rs +++ b/neqo-crypto/src/cert.rs @@ -46,7 +46,7 @@ fn stapled_ocsp_responses(fd: *mut PRFileDesc) -> Option>> { Some(ocsp_ptr) => { let mut ocsp_helper: Vec> = Vec::new(); let Ok(len) = isize::try_from(unsafe { ocsp_ptr.as_ref().len }) else { - error!("[{}] Received illegal OSCP length", format!("{fd:p}")); + error!("[{fd:p}] Received illegal OSCP length"); return None; }; for idx in 0..len { From 1877d410ecb36a6102f4835235d54f56802e060b Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 12:31:01 +0200 Subject: [PATCH 5/9] Fix bench --- neqo-bin/benches/main.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/neqo-bin/benches/main.rs b/neqo-bin/benches/main.rs index dbdb437709..a9d080e825 100644 --- a/neqo-bin/benches/main.rs +++ b/neqo-bin/benches/main.rs @@ -17,7 +17,6 @@ struct Benchmark { } fn transfer(c: &mut Criterion) { - neqo_common::log::init(Some(log::LevelFilter::Off)); neqo_crypto::init_db(PathBuf::from_str("../test-fixture/db").unwrap()).unwrap(); let done_sender = spawn_server(); From a65dce8a00963baa20645fb070ac16fbbfb33c60 Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 15:32:46 +0200 Subject: [PATCH 6/9] Retain `neqo-common::log` --- Cargo.lock | 2 +- neqo-bin/Cargo.toml | 1 - neqo-bin/src/client/http09.rs | 31 ++- neqo-bin/src/client/http3.rs | 31 ++- neqo-bin/src/client/mod.rs | 35 ++-- neqo-bin/src/lib.rs | 33 +-- neqo-bin/src/server/http09.rs | 23 +- neqo-bin/src/server/http3.rs | 9 +- neqo-bin/src/server/mod.rs | 17 +- neqo-common/Cargo.toml | 1 + neqo-common/src/lib.rs | 1 + neqo-common/src/log.rs | 83 ++++++++ neqo-common/src/qlog.rs | 5 +- neqo-crypto/src/agent.rs | 23 +- neqo-crypto/src/agentio.rs | 15 +- neqo-crypto/src/cert.rs | 4 +- neqo-crypto/src/ech.rs | 4 +- neqo-crypto/src/lib.rs | 4 +- neqo-crypto/src/secrets.rs | 4 +- neqo-crypto/src/selfencrypt.rs | 9 +- neqo-crypto/tests/handshake.rs | 6 +- neqo-http3/src/buffered_send_stream.rs | 4 +- neqo-http3/src/connection.rs | 72 +++---- neqo-http3/src/connection_client.rs | 48 ++--- neqo-http3/src/connection_server.rs | 21 +- neqo-http3/src/control_stream_local.rs | 5 +- neqo-http3/src/control_stream_remote.rs | 6 +- .../extended_connect/webtransport_session.rs | 13 +- neqo-http3/src/features/mod.rs | 4 +- neqo-http3/src/frames/reader.rs | 11 +- neqo-http3/src/push_controller.rs | 27 ++- neqo-http3/src/recv_message.rs | 15 +- neqo-http3/src/send_message.rs | 15 +- neqo-http3/src/server.rs | 9 +- neqo-http3/src/server_events.rs | 15 +- neqo-http3/src/stream_type_reader.rs | 9 +- neqo-http3/tests/httpconn.rs | 13 +- neqo-qpack/src/decoder.rs | 11 +- neqo-qpack/src/decoder_instructions.rs | 6 +- neqo-qpack/src/encoder.rs | 21 +- neqo-qpack/src/encoder_instructions.rs | 12 +- neqo-qpack/src/header_block.rs | 33 ++- neqo-qpack/src/reader.rs | 6 +- neqo-qpack/src/table.rs | 22 +- neqo-transport/src/ackrate.rs | 10 +- neqo-transport/src/addr_valid.rs | 29 ++- neqo-transport/src/cc/classic_cc.rs | 36 ++-- neqo-transport/src/cc/cubic.rs | 4 +- neqo-transport/src/cid.rs | 7 +- neqo-transport/src/connection/dump.rs | 5 +- neqo-transport/src/connection/idle.rs | 4 +- neqo-transport/src/connection/mod.rs | 197 +++++++++--------- neqo-transport/src/connection/saved.rs | 7 +- neqo-transport/src/connection/tests/cc.rs | 15 +- .../src/connection/tests/handshake.rs | 47 ++--- neqo-transport/src/connection/tests/idle.rs | 9 +- neqo-transport/src/connection/tests/keys.rs | 11 +- .../src/connection/tests/migration.rs | 9 +- neqo-transport/src/connection/tests/mod.rs | 29 ++- .../src/connection/tests/recovery.rs | 20 +- neqo-transport/src/connection/tests/stream.rs | 15 +- .../src/connection/tests/zerortt.rs | 5 +- neqo-transport/src/crypto.rs | 80 +++---- neqo-transport/src/ecn.rs | 21 +- neqo-transport/src/fc.rs | 7 +- neqo-transport/src/frame.rs | 11 +- neqo-transport/src/lib.rs | 4 +- neqo-transport/src/pace.rs | 10 +- neqo-transport/src/packet/mod.rs | 17 +- neqo-transport/src/packet/retry.rs | 4 +- neqo-transport/src/path.rs | 35 ++-- neqo-transport/src/pmtud.rs | 26 +-- neqo-transport/src/qlog.rs | 7 +- neqo-transport/src/recovery/mod.rs | 33 ++- neqo-transport/src/recv_stream.rs | 30 ++- neqo-transport/src/rtt.rs | 7 +- neqo-transport/src/send_stream.rs | 72 ++++--- neqo-transport/src/sender.rs | 5 +- neqo-transport/src/server.rs | 46 ++-- neqo-transport/src/shuffle.rs | 5 +- neqo-transport/src/stats.rs | 4 +- neqo-transport/src/streams.rs | 9 +- neqo-transport/src/tparams.rs | 35 ++-- neqo-transport/src/tracking.rs | 21 +- neqo-transport/src/version.rs | 4 +- neqo-transport/tests/common/mod.rs | 3 +- neqo-transport/tests/retry.rs | 9 +- neqo-transport/tests/server.rs | 5 +- neqo-udp/src/lib.rs | 13 +- test-fixture/src/header_protection.rs | 5 +- test-fixture/src/lib.rs | 5 +- test-fixture/src/sim/connection.rs | 15 +- test-fixture/src/sim/drop.rs | 5 +- test-fixture/src/sim/mod.rs | 25 ++- test-fixture/src/sim/taildrop.rs | 12 +- 95 files changed, 895 insertions(+), 893 deletions(-) create mode 100644 neqo-common/src/log.rs diff --git a/Cargo.lock b/Cargo.lock index 06d749e46b..1a1e553639 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -805,7 +805,6 @@ dependencies = [ "clap", "clap-verbosity-flag", "criterion", - "env_logger", "futures", "hex", "log", @@ -828,6 +827,7 @@ version = "0.11.0" dependencies = [ "criterion", "enum-map", + "env_logger", "hex", "log", "neqo-crypto", diff --git a/neqo-bin/Cargo.toml b/neqo-bin/Cargo.toml index 6e57ccb5fb..ce8accbf0a 100644 --- a/neqo-bin/Cargo.toml +++ b/neqo-bin/Cargo.toml @@ -29,7 +29,6 @@ workspace = true # Not used in Firefox, so we can be liberal with dependency versions clap = { version = "4.4", default-features = false, features = ["std", "help", "usage", "error-context", "suggestions", "derive"] } clap-verbosity-flag = { version = "3.0", default-features = false, features = ["log"] } -env_logger = { version = "0.10", default-features = false, features = ["auto-color", "regex"] } futures = { version = "0.3", default-features = false, features = ["alloc"] } hex = { version = "0.4", default-features = false, features = ["std"] } log = { workspace = true } diff --git a/neqo-bin/src/client/http09.rs b/neqo-bin/src/client/http09.rs index 36e5343475..904c8647d0 100644 --- a/neqo-bin/src/client/http09.rs +++ b/neqo-bin/src/client/http09.rs @@ -17,8 +17,7 @@ use std::{ time::Instant, }; -use log::{debug, info, warn}; -use neqo_common::{event::Provider, Datagram}; +use neqo_common::{event::Provider, qdebug, qinfo, qwarn, Datagram}; use neqo_crypto::{AuthenticationStatus, ResumptionToken}; use neqo_transport::{ CloseReason, Connection, ConnectionEvent, ConnectionIdGenerator, EmptyConnectionIdGenerator, @@ -58,7 +57,7 @@ impl super::Handler for Handler<'_> { if self.needs_key_update { match client.initiate_key_update() { Ok(()) => { - debug!("Keys updated"); + qdebug!("Keys updated"); self.needs_key_update = false; self.download_urls(client); } @@ -75,13 +74,13 @@ impl super::Handler for Handler<'_> { self.read(client, stream_id)?; } ConnectionEvent::SendStreamWritable { stream_id } => { - debug!("stream {stream_id} writable"); + qdebug!("stream {stream_id} writable"); } ConnectionEvent::SendStreamComplete { stream_id } => { - debug!("stream {stream_id} complete"); + qdebug!("stream {stream_id} complete"); } ConnectionEvent::SendStreamCreatable { stream_type } => { - debug!("stream {stream_type:?} creatable"); + qdebug!("stream {stream_type:?} creatable"); if stream_type == StreamType::BiDi { self.download_urls(client); } @@ -89,11 +88,11 @@ impl super::Handler for Handler<'_> { ConnectionEvent::StateChange( State::WaitInitial | State::Handshaking | State::Connected, ) => { - debug!("{event:?}"); + qdebug!("{event:?}"); self.download_urls(client); } ConnectionEvent::ZeroRttRejected => { - debug!("{event:?}"); + qdebug!("{event:?}"); // All 0-RTT data was rejected. We need to retransmit it. self.reinit(); self.download_urls(client); @@ -102,7 +101,7 @@ impl super::Handler for Handler<'_> { self.token = Some(token); } _ => { - warn!("Unhandled event {event:?}"); + qwarn!("Unhandled event {event:?}"); } } } @@ -248,7 +247,7 @@ impl<'b> Handler<'b> { fn download_next(&mut self, client: &mut Connection) -> bool { if self.needs_key_update { - debug!("Deferring requests until after first key update"); + qdebug!("Deferring requests until after first key update"); return false; } let url = self @@ -257,7 +256,7 @@ impl<'b> Handler<'b> { .expect("download_next called with empty queue"); match client.stream_create(StreamType::BiDi) { Ok(client_stream_id) => { - info!("Created stream {client_stream_id} for {url}"); + qinfo!("Created stream {client_stream_id} for {url}"); let req = format!("GET {}\r\n", url.path()); _ = client .stream_send(client_stream_id, req.as_bytes()) @@ -270,7 +269,7 @@ impl<'b> Handler<'b> { true } Err(e @ (Error::StreamLimitError | Error::ConnectionState)) => { - warn!("Cannot create stream {e:?}"); + qwarn!("Cannot create stream {e:?}"); self.url_queue.push_front(url); false } @@ -299,9 +298,9 @@ impl<'b> Handler<'b> { if let Some(out_file) = maybe_out_file { out_file.write_all(read_buffer)?; } else if !output_read_data { - debug!("READ[{stream_id}]: {} bytes", read_buffer.len()); + qdebug!("READ[{stream_id}]: {} bytes", read_buffer.len()); } else { - debug!( + qdebug!( "READ[{stream_id}]: {}", std::str::from_utf8(read_buffer).unwrap() ); @@ -315,7 +314,7 @@ impl<'b> Handler<'b> { fn read(&mut self, client: &mut Connection, stream_id: StreamId) -> Res<()> { match self.streams.get_mut(&stream_id) { None => { - warn!("Data on unexpected stream: {stream_id}"); + qwarn!("Data on unexpected stream: {stream_id}"); return Ok(()); } Some(maybe_out_file) => { @@ -331,7 +330,7 @@ impl<'b> Handler<'b> { if let Some(mut out_file) = maybe_out_file.take() { out_file.flush()?; } else { - info!(""); + qinfo!(""); } self.streams.remove(&stream_id); self.download_urls(client); diff --git a/neqo-bin/src/client/http3.rs b/neqo-bin/src/client/http3.rs index 74f8b1d20f..6e8fbaaf73 100644 --- a/neqo-bin/src/client/http3.rs +++ b/neqo-bin/src/client/http3.rs @@ -18,8 +18,7 @@ use std::{ time::Instant, }; -use log::{debug, info, warn}; -use neqo_common::{event::Provider, hex, Datagram, Header}; +use neqo_common::{event::Provider, hex, qdebug, qinfo, qwarn, Datagram, Header}; use neqo_crypto::{AuthenticationStatus, ResumptionToken}; use neqo_http3::{Error, Http3Client, Http3ClientEvent, Http3Parameters, Http3State, Priority}; use neqo_transport::{ @@ -188,7 +187,7 @@ impl super::Handler for Handler<'_> { if let Some(handler) = self.url_handler.stream_handler(stream_id) { handler.process_header_ready(stream_id, fin, headers); } else { - warn!("Data on unexpected stream: {stream_id}"); + qwarn!("Data on unexpected stream: {stream_id}"); } if fin { self.url_handler.on_stream_fin(client, stream_id); @@ -198,7 +197,7 @@ impl super::Handler for Handler<'_> { let mut stream_done = false; match self.url_handler.stream_handler(stream_id) { None => { - warn!("Data on unexpected stream: {stream_id}"); + qwarn!("Data on unexpected stream: {stream_id}"); } Some(handler) => loop { let (sz, fin) = client @@ -230,7 +229,7 @@ impl super::Handler for Handler<'_> { Http3ClientEvent::DataWritable { stream_id } => { match self.url_handler.stream_handler(stream_id) { None => { - warn!("Data on unexpected stream: {stream_id}"); + qwarn!("Data on unexpected stream: {stream_id}"); } Some(handler) => { handler.process_data_writable(client, stream_id); @@ -239,18 +238,18 @@ impl super::Handler for Handler<'_> { } Http3ClientEvent::StateChange(Http3State::Connected) | Http3ClientEvent::RequestsCreatable => { - info!("{event:?}"); + qinfo!("{event:?}"); self.url_handler.process_urls(client); } Http3ClientEvent::ZeroRttRejected => { - info!("{event:?}"); + qinfo!("{event:?}"); // All 0-RTT data was rejected. We need to retransmit it. self.reinit(); self.url_handler.process_urls(client); } Http3ClientEvent::ResumptionToken(t) => self.token = Some(t), _ => { - warn!("Unhandled event {event:?}"); + qwarn!("Unhandled event {event:?}"); } } } @@ -282,7 +281,7 @@ struct DownloadStreamHandler { impl StreamHandler for DownloadStreamHandler { fn process_header_ready(&mut self, stream_id: StreamId, fin: bool, headers: Vec
) { if self.out_file.is_none() { - debug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); + qdebug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); } } @@ -299,18 +298,18 @@ impl StreamHandler for DownloadStreamHandler { } return Ok(true); } else if !output_read_data { - debug!("READ[{stream_id}]: {} bytes", data.len()); + qdebug!("READ[{stream_id}]: {} bytes", data.len()); } else if let Ok(txt) = std::str::from_utf8(data) { - debug!("READ[{stream_id}]: {txt}"); + qdebug!("READ[{stream_id}]: {txt}"); } else { - debug!("READ[{stream_id}]: 0x{}", hex(data)); + qdebug!("READ[{stream_id}]: 0x{}", hex(data)); } if fin { if let Some(mut out_file) = self.out_file.take() { out_file.flush()?; } else { - debug!(""); + qdebug!(""); } } @@ -327,7 +326,7 @@ struct UploadStreamHandler { impl StreamHandler for UploadStreamHandler { fn process_header_ready(&mut self, stream_id: StreamId, fin: bool, headers: Vec
) { - debug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); + qdebug!("READ HEADERS[{stream_id}]: fin={fin} {headers:?}"); } fn process_data_readable( @@ -342,7 +341,7 @@ impl StreamHandler for UploadStreamHandler { let parsed: usize = trimmed_txt.parse().unwrap(); if parsed == self.data.len() { let upload_time = Instant::now().duration_since(self.start); - info!("Stream ID: {stream_id:?}, Upload time: {upload_time:?}"); + qinfo!("Stream ID: {stream_id:?}, Upload time: {upload_time:?}"); } } else { panic!("Unexpected data [{stream_id}]: 0x{}", hex(data)); @@ -400,7 +399,7 @@ impl UrlHandler<'_> { Priority::default(), ) { Ok(client_stream_id) => { - debug!("Successfully created stream id {client_stream_id} for {url}"); + qdebug!("Successfully created stream id {client_stream_id} for {url}"); let handler: Box = match self.args.method.as_str() { "GET" => { diff --git a/neqo-bin/src/client/mod.rs b/neqo-bin/src/client/mod.rs index 82f8994c70..d35d53da7f 100644 --- a/neqo-bin/src/client/mod.rs +++ b/neqo-bin/src/client/mod.rs @@ -23,8 +23,7 @@ use futures::{ future::{select, Either}, FutureExt, TryFutureExt, }; -use log::{debug, error, info, warn}; -use neqo_common::{qlog::NeqoQlog, Datagram, Role}; +use neqo_common::{qdebug, qerror, qinfo, qlog::NeqoQlog, qwarn, Datagram, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256}, init, Cipher, ResumptionToken, @@ -34,7 +33,7 @@ use neqo_transport::{AppError, CloseReason, ConnectionId, Version}; use tokio::time::Sleep; use url::{Host, Origin, Url}; -use crate::{log_init, SharedArgs}; +use crate::SharedArgs; mod http09; mod http3; @@ -227,12 +226,12 @@ impl Args { }; if self.key_update { - error!("internal option key_update set by user"); + qerror!("internal option key_update set by user"); exit(127) } if self.resume { - error!("internal option resume set by user"); + qerror!("internal option resume set by user"); exit(127) } @@ -245,7 +244,7 @@ impl Args { self.shared.alpn = String::from("h3"); if let Some(testcase) = &self.test { if testcase.as_str() != "upload" { - error!("Unsupported test case: {testcase}"); + qerror!("Unsupported test case: {testcase}"); exit(127) } @@ -255,14 +254,14 @@ impl Args { "handshake" | "transfer" | "retry" | "ecn" => {} "resumption" => { if self.urls.len() < 2 { - error!("Warning: resumption test won't work without >1 URL"); + qerror!("Warning: resumption test won't work without >1 URL"); exit(127); } self.resume = true; } "zerortt" => { if self.urls.len() < 2 { - error!("Warning: zerortt test won't work without >1 URL"); + qerror!("Warning: zerortt test won't work without >1 URL"); exit(127); } self.resume = true; @@ -316,11 +315,11 @@ fn get_output_file( out_path.push(url_path); if all_paths.contains(&out_path) { - error!("duplicate path {}", out_path.display()); + qerror!("duplicate path {}", out_path.display()); return None; } - info!("Saving {url} to {out_path:?}"); + qinfo!("Saving {url} to {out_path:?}"); if let Some(parent) = out_path.parent() { create_dir_all(parent).ok()?; @@ -449,7 +448,7 @@ impl<'a, H: Handler> Runner<'a, H> { } if self.args.stats { - info!("{:?}", self.client.stats()); + qinfo!("{:?}", self.client.stats()); } Ok(self.handler.take_token()) @@ -463,12 +462,12 @@ impl<'a, H: Handler> Runner<'a, H> { self.socket.send(&dgram)?; } Output::Callback(new_timeout) => { - debug!("Setting timeout of {:?}", new_timeout); + qdebug!("Setting timeout of {new_timeout:?}"); self.timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); break; } Output::None => { - debug!("Output::None"); + qdebug!("Output::None"); break; } } @@ -533,14 +532,14 @@ fn urls_by_origin(urls: &[Url]) -> impl Iterator Some(((h, p), urls)), Origin::Opaque(x) => { - warn!("Opaque origin {x:?}"); + qwarn!("Opaque origin {x:?}"); None } }) } pub async fn client(mut args: Args) -> Res<()> { - log_init( + neqo_common::log::init( args.shared .verbose .as_ref() @@ -554,7 +553,7 @@ pub async fn client(mut args: Args) -> Res<()> { for ((host, port), mut urls) in urls_by_origin(&args.urls) { if args.resume && urls.len() < 2 { - error!("Resumption to {host} cannot work without at least 2 URLs"); + qerror!("Resumption to {host} cannot work without at least 2 URLs"); exit(127); } @@ -565,12 +564,12 @@ pub async fn client(mut args: Args) -> Res<()> { ) }); let Some(remote_addr) = remote_addr else { - error!("No compatible address found for: {host}"); + qerror!("No compatible address found for: {host}"); exit(1); }; let mut socket = crate::udp::Socket::bind(local_addr_for(&remote_addr, 0))?; let real_local = socket.local_addr().unwrap(); - info!( + qinfo!( "{} Client connecting: {real_local:?} -> {remote_addr:?}", args.shared.alpn ); diff --git a/neqo-bin/src/lib.rs b/neqo-bin/src/lib.rs index bc9090b5da..822be1acc4 100644 --- a/neqo-bin/src/lib.rs +++ b/neqo-bin/src/lib.rs @@ -9,11 +9,9 @@ use std::{ fmt::{self, Display}, - io::Write, net::{SocketAddr, ToSocketAddrs}, path::PathBuf, - sync::OnceLock, - time::{Duration, Instant}, + time::Duration, }; use clap::Parser; @@ -245,35 +243,6 @@ impl QuicParameters { } } -fn since_start() -> Duration { - static START_TIME: OnceLock = OnceLock::new(); - START_TIME.get_or_init(Instant::now).elapsed() -} -pub fn log_init(level_filter: Option) { - let mut builder = env_logger::Builder::from_default_env(); - if let Some(filter) = level_filter { - builder.filter_level(filter); - } - builder.format(|buf, record| { - let elapsed = since_start(); - let level_style = buf.default_level_style(record.level()); - let mut bold = buf.style(); - bold.set_bold(true); - writeln!( - buf, - "{:.3} {} {}", - bold.value(elapsed.as_secs_f32()), - level_style.value(record.level()), - record.args() - ) - }); - if let Err(e) = builder.try_init() { - eprintln!("Logging initialization error {e:?}"); - } else { - log::debug!("Logging initialized"); - } -} - fn from_str(s: &str) -> Result { let v = u32::from_str_radix(s, 16) .map_err(|_| Error::Argument("versions need to be specified in hex"))?; diff --git a/neqo-bin/src/server/http09.rs b/neqo-bin/src/server/http09.rs index e9d96db403..c56412a5fb 100644 --- a/neqo-bin/src/server/http09.rs +++ b/neqo-bin/src/server/http09.rs @@ -6,8 +6,7 @@ use std::{borrow::Cow, cell::RefCell, collections::HashMap, fmt::Display, rc::Rc, time::Instant}; -use log::{debug, error, info, warn}; -use neqo_common::{event::Provider, hex, Datagram}; +use neqo_common::{event::Provider, hex, qdebug, qerror, qinfo, qwarn, Datagram}; use neqo_crypto::{generate_ech_keys, random, AllowZeroRtt, AntiReplay}; use neqo_http3::Error; use neqo_transport::{ @@ -61,7 +60,7 @@ impl HttpServer { .enable_ech(random::<1>()[0], "public.example", &sk, &pk) .expect("enable ECH"); let cfg = server.ech_config(); - info!("ECHConfigList: {}", hex(cfg)); + qinfo!("ECHConfigList: {}", hex(cfg)); } let is_qns_test = args.shared.qns_test.is_some(); @@ -83,17 +82,17 @@ impl HttpServer { let url_dbg = String::from_utf8(partial.clone()) .unwrap_or_else(|_| format!("", hex(&partial))); if partial.len() < 4096 { - debug!("Saving partial URL: {url_dbg}"); + qdebug!("Saving partial URL: {url_dbg}"); self.read_state.insert(stream_id, partial); } else { - debug!("Giving up on partial URL {url_dbg}"); + qdebug!("Giving up on partial URL {url_dbg}"); conn.borrow_mut().stream_stop_sending(stream_id, 0).unwrap(); } } fn stream_readable(&mut self, stream_id: StreamId, conn: &ConnectionRef) { if !stream_id.is_client_initiated() || !stream_id.is_bidi() { - debug!("Stream {stream_id} not client-initiated bidi, ignoring"); + qdebug!("Stream {stream_id} not client-initiated bidi, ignoring"); return; } let (sz, fin) = conn @@ -103,7 +102,7 @@ impl HttpServer { if sz == 0 { if !fin { - debug!("size 0 but !fin"); + qdebug!("size 0 but !fin"); } return; } @@ -130,12 +129,12 @@ impl HttpServer { let resp: SendData = { let path = path.as_str(); - debug!("Path = '{path}'"); + qdebug!("Path = '{path}'"); if self.is_qns_test { match qns_read_response(path) { Ok(data) => data.into(), Err(e) => { - error!("Failed to read {path}: {e}"); + qerror!("Failed to read {path}: {e}"); b"404".to_vec().into() } } @@ -149,7 +148,7 @@ impl HttpServer { match stream_state.data_to_send { None => stream_state.data_to_send = Some(resp), Some(_) => { - debug!("Data already set, doing nothing"); + qdebug!("Data already set, doing nothing"); } } if stream_state.writable { @@ -168,7 +167,7 @@ impl HttpServer { fn stream_writable(&mut self, stream_id: StreamId, conn: &ConnectionRef) { let Some(stream_state) = self.write_state.get_mut(&stream_id) else { - warn!("Unknown stream {stream_id}, ignoring event"); + qwarn!("Unknown stream {stream_id}, ignoring event"); return; }; @@ -221,7 +220,7 @@ impl super::HttpServer for HttpServer { ConnectionEvent::StateChange(_) | ConnectionEvent::SendStreamCreatable { .. } | ConnectionEvent::SendStreamComplete { .. } => (), - e => warn!("unhandled event {e:?}"), + e => qwarn!("unhandled event {e:?}"), } } } diff --git a/neqo-bin/src/server/http3.rs b/neqo-bin/src/server/http3.rs index 54bfa18083..bf5a3592e3 100644 --- a/neqo-bin/src/server/http3.rs +++ b/neqo-bin/src/server/http3.rs @@ -12,8 +12,7 @@ use std::{ time::Instant, }; -use log::{debug, error, info}; -use neqo_common::{header::HeadersExt, hex, Datagram, Header}; +use neqo_common::{header::HeadersExt, hex, qdebug, qerror, qinfo, Datagram, Header}; use neqo_crypto::{generate_ech_keys, random, AntiReplay}; use neqo_http3::{ Http3OrWebTransportStream, Http3Parameters, Http3Server, Http3ServerEvent, StreamId, @@ -63,7 +62,7 @@ impl HttpServer { .enable_ech(random::<1>()[0], "public.example", &sk, &pk) .unwrap(); let cfg = server.ech_config(); - info!("ECHConfigList: {}", hex(cfg)); + qinfo!("ECHConfigList: {}", hex(cfg)); } Self { server, @@ -93,7 +92,7 @@ impl super::HttpServer for HttpServer { headers, fin, } => { - debug!("Headers (request={stream} fin={fin}): {headers:?}"); + qdebug!("Headers (request={stream} fin={fin}): {headers:?}"); if headers.contains_header(":method", "POST") { self.posts.insert(stream, 0); @@ -111,7 +110,7 @@ impl super::HttpServer for HttpServer { match qns_read_response(path.value()) { Ok(data) => SendData::from(data), Err(e) => { - error!("Failed to read {}: {e}", path.value()); + qerror!("Failed to read {}: {e}", path.value()); stream .send_headers(&[Header::new(":status", "404")]) .unwrap(); diff --git a/neqo-bin/src/server/mod.rs b/neqo-bin/src/server/mod.rs index 3095c37e38..ad187f0396 100644 --- a/neqo-bin/src/server/mod.rs +++ b/neqo-bin/src/server/mod.rs @@ -23,8 +23,7 @@ use futures::{ future::{select, select_all, Either}, FutureExt, }; -use log::{debug, error, info, warn}; -use neqo_common::Datagram; +use neqo_common::{qdebug, qerror, qinfo, qwarn, Datagram}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256}, init_db, AntiReplay, Cipher, @@ -32,7 +31,7 @@ use neqo_crypto::{ use neqo_transport::{Output, RandomConnectionIdGenerator, Version}; use tokio::time::Sleep; -use crate::{log_init, SharedArgs}; +use crate::SharedArgs; const ANTI_REPLAY_WINDOW: Duration = Duration::from_secs(10); @@ -252,7 +251,7 @@ impl ServerRunner { socket.send(&dgram)?; } Output::Callback(new_timeout) => { - debug!("Setting timeout of {:?}", new_timeout); + qdebug!("Setting timeout of {new_timeout:?}"); *timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); break; } @@ -342,7 +341,7 @@ enum Ready { } pub async fn server(mut args: Args) -> Res<()> { - log_init( + neqo_common::log::init( args.shared .verbose .as_ref() @@ -361,7 +360,7 @@ pub async fn server(mut args: Args) -> Res<()> { args.shared.quic_parameters.quic_version = vec![Version::Version1]; } } else { - warn!("Both -V and --qns-test were set. Ignoring testcase specific versions"); + qwarn!("Both -V and --qns-test were set. Ignoring testcase specific versions"); } // These are the default for all tests except http3. @@ -375,7 +374,7 @@ pub async fn server(mut args: Args) -> Res<()> { "handshake" | "transfer" | "resumption" | "multiconnect" | "v2" | "ecn" => {} "connectionmigration" => { if args.shared.quic_parameters.preferred_address().is_none() { - error!("No preferred addresses set for connectionmigration test"); + qerror!("No preferred addresses set for connectionmigration test"); exit(127); } } @@ -392,7 +391,7 @@ pub async fn server(mut args: Args) -> Res<()> { let hosts = args.listen_addresses(); if hosts.is_empty() { - error!("No valid hosts defined"); + qerror!("No valid hosts defined"); Err(io::Error::new(io::ErrorKind::InvalidInput, "No hosts"))?; } let sockets = hosts @@ -400,7 +399,7 @@ pub async fn server(mut args: Args) -> Res<()> { .map(|host| { let socket = crate::udp::Socket::bind(host)?; let local_addr = socket.local_addr()?; - info!("Server waiting for connection on: {local_addr:?}"); + qinfo!("Server waiting for connection on: {local_addr:?}"); Ok((host, socket)) }) diff --git a/neqo-common/Cargo.toml b/neqo-common/Cargo.toml index fa9fae130c..80771aafa5 100644 --- a/neqo-common/Cargo.toml +++ b/neqo-common/Cargo.toml @@ -18,6 +18,7 @@ workspace = true [dependencies] # Checked against https://searchfox.org/mozilla-central/source/Cargo.lock 2024-11-11 enum-map = { workspace = true } +env_logger = { version = "0.10", default-features = false, features = ["auto-color", "regex"] } hex = { version = "0.4", default-features = false, features = ["alloc"], optional = true } log = { workspace = true } qlog = { workspace = true } diff --git a/neqo-common/src/lib.rs b/neqo-common/src/lib.rs index 14966c2ad0..5b212f9998 100644 --- a/neqo-common/src/lib.rs +++ b/neqo-common/src/lib.rs @@ -14,6 +14,7 @@ mod fuzz; pub mod header; pub mod hrtime; mod incrdecoder; +pub mod log; pub mod qlog; pub mod tos; diff --git a/neqo-common/src/log.rs b/neqo-common/src/log.rs new file mode 100644 index 0000000000..65556f564f --- /dev/null +++ b/neqo-common/src/log.rs @@ -0,0 +1,83 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(clippy::module_name_repetitions)] + +use std::{ + io::Write, + sync::{Once, OnceLock}, + time::{Duration, Instant}, +}; + +use env_logger::Builder; + +fn since_start() -> Duration { + static START_TIME: OnceLock = OnceLock::new(); + START_TIME.get_or_init(Instant::now).elapsed() +} + +pub fn init(level_filter: Option) { + static INIT_ONCE: Once = Once::new(); + + if ::log::STATIC_MAX_LEVEL == ::log::LevelFilter::Off { + return; + } + + INIT_ONCE.call_once(|| { + let mut builder = Builder::from_env("RUST_LOG"); + if let Some(filter) = level_filter { + builder.filter_level(filter); + } + builder.format(|buf, record| { + let elapsed = since_start(); + let level_style = buf.default_level_style(record.level()); + let mut bold = buf.style(); + bold.set_bold(true); + writeln!( + buf, + "{} {} {}", + bold.value(format!( + "{}.{:03}", + elapsed.as_secs(), + elapsed.as_millis() % 1000 + )), + level_style.value(record.level()), + record.args() + ) + }); + if let Err(e) = builder.try_init() { + eprintln!("Logging initialization error {e:?}"); + } else { + ::log::debug!("Logging initialized"); + } + }); +} + +#[macro_export] +#[clippy::format_args] +macro_rules! qerror { + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::error!($($arg)*); } ); +} +#[macro_export] +#[clippy::format_args] +macro_rules! qwarn { + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::warn!($($arg)*); } ); +} +#[macro_export] +#[clippy::format_args] +macro_rules! qinfo { + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::info!($($arg)*); } ); +} +#[macro_export] +#[clippy::format_args] +macro_rules! qdebug { + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::debug!($($arg)*); } ); +} +#[macro_export] +#[clippy::format_args] +macro_rules! qtrace { + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::trace!($($arg)*); } ); +} diff --git a/neqo-common/src/qlog.rs b/neqo-common/src/qlog.rs index 26507ebf54..0b2b4ad250 100644 --- a/neqo-common/src/qlog.rs +++ b/neqo-common/src/qlog.rs @@ -14,7 +14,6 @@ use std::{ time::{Instant, SystemTime}, }; -use log::error; use qlog::{ streamer::QlogStreamer, CommonFields, Configuration, TraceSeq, VantagePoint, VantagePointType, }; @@ -150,7 +149,7 @@ impl NeqoQlog { { if let Some(inner) = self.inner.borrow_mut().as_mut() { if let Err(e) = f(&mut inner.streamer) { - error!("Qlog event generation failed with error {e}; closing qlog"); + log::error!("Qlog event generation failed with error {e}; closing qlog."); *self.inner.borrow_mut() = None; } } @@ -166,7 +165,7 @@ impl fmt::Debug for NeqoQlogShared { impl Drop for NeqoQlogShared { fn drop(&mut self) { if let Err(e) = self.streamer.finish_log() { - error!("Error dropping NeqoQlog: {e}"); + log::error!("Error dropping NeqoQlog: {e}"); } } } diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index 9ebe284d04..ad351c4cc2 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -16,8 +16,7 @@ use std::{ time::Instant, }; -use log::{debug, trace, warn}; -use neqo_common::{hex_snip_middle, hex_with_len}; +use neqo_common::{hex_snip_middle, hex_with_len, qdebug, qtrace, qwarn}; pub use crate::{ agentio::{as_c_void, Record, RecordList}, @@ -108,7 +107,7 @@ fn get_alpn(fd: *mut ssl::PRFileDesc, pre: bool) -> Res> { } _ => None, }; - trace!("[{fd:p}] got ALPN {alpn:?}"); + qtrace!("[{fd:p}] got ALPN {alpn:?}"); Ok(alpn) } @@ -370,7 +369,7 @@ impl SecretAgent { if st.is_none() { *st = Some(alert.description); } else { - warn!("[{fd:p}] duplicate alert {}", alert.description); + qwarn!("[{fd:p}] duplicate alert {}", alert.description); } } } @@ -430,7 +429,7 @@ impl SecretAgent { /// If NSS can't enable or disable ciphers. pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> { if self.state != HandshakeState::New { - warn!("[{self}] Cannot enable ciphers in state {:?}", self.state); + qwarn!("[{self}] Cannot enable ciphers in state {:?}", self.state); return Err(Error::InternalError); } @@ -645,7 +644,7 @@ impl SecretAgent { fn capture_error(&mut self, res: Res) -> Res { if let Err(e) = res { let e = ech::convert_ech_error(self.fd, e); - warn!("[{self}] error: {e:?}"); + qwarn!("[{self}] error: {e:?}"); self.state = HandshakeState::Failed(e.clone()); Err(e) } else { @@ -670,7 +669,7 @@ impl SecretAgent { let info = self.capture_error(SecretAgentInfo::new(self.fd))?; HandshakeState::Complete(info) }; - debug!("[{self}] state -> {:?}", self.state); + qdebug!("[{self}] state -> {:?}", self.state); Ok(()) } @@ -730,7 +729,7 @@ impl SecretAgent { if let HandshakeState::Authenticated(ref err) = self.state { let result = secstatus_to_res(unsafe { ssl::SSL_AuthCertificateComplete(self.fd, *err) }); - debug!("[{self}] SSL_AuthCertificateComplete: {result:?}"); + qdebug!("[{self}] SSL_AuthCertificateComplete: {result:?}"); // This should return SECSuccess, so don't use update_state(). self.capture_error(result)?; } @@ -892,7 +891,7 @@ impl Client { let len = usize::try_from(len).unwrap(); let mut v = Vec::with_capacity(len); v.extend_from_slice(null_safe_slice(token, len)); - debug!("[{fd:p}] Got resumption token {}", hex_snip_middle(&v)); + qdebug!("[{fd:p}] Got resumption token {}", hex_snip_middle(&v)); if resumption.len() >= MAX_TICKETS { resumption.remove(0); @@ -962,7 +961,7 @@ impl Client { /// Error returned when the configuration is invalid. pub fn enable_ech(&mut self, ech_config_list: impl AsRef<[u8]>) -> Res<()> { let config = ech_config_list.as_ref(); - debug!("[{self}] Enable ECH for a server: {}", hex_with_len(config)); + qdebug!("[{self}] Enable ECH for a server: {}", hex_with_len(config)); self.ech_config = Vec::from(config); if config.is_empty() { unsafe { ech::SSL_EnableTls13GreaseEch(self.agent.fd, PRBool::from(true)) } @@ -1024,7 +1023,7 @@ pub trait ZeroRttChecker: std::fmt::Debug + std::marker::Unpin { pub struct AllowZeroRtt {} impl ZeroRttChecker for AllowZeroRtt { fn check(&self, _token: &[u8]) -> ZeroRttCheckResult { - warn!("AllowZeroRtt accepting 0-RTT"); + qwarn!("AllowZeroRtt accepting 0-RTT"); ZeroRttCheckResult::Accept } } @@ -1172,7 +1171,7 @@ impl Server { pk: &PublicKey, ) -> Res<()> { let cfg = ech::encode_config(config, public_name, pk)?; - debug!("[{self}] Enable ECH for a server: {}", hex_with_len(&cfg)); + qdebug!("[{self}] Enable ECH for a server: {}", hex_with_len(&cfg)); unsafe { ech::SSL_SetServerEchConfigs( self.agent.fd, diff --git a/neqo-crypto/src/agentio.rs b/neqo-crypto/src/agentio.rs index 4a89fcbcfd..7bf14f941b 100644 --- a/neqo-crypto/src/agentio.rs +++ b/neqo-crypto/src/agentio.rs @@ -13,8 +13,7 @@ use std::{ ptr::{null, null_mut}, }; -use log::trace; -use neqo_common::{hex, hex_with_len}; +use neqo_common::{hex, hex_with_len, qtrace}; use crate::{ constants::{ContentType, Epoch}, @@ -53,7 +52,7 @@ impl Record { // Shoves this record into the socket, returns true if blocked. pub(crate) fn write(self, fd: *mut ssl::PRFileDesc) -> Res<()> { - trace!("write {self:?}"); + qtrace!("write {self:?}"); unsafe { ssl::SSL_RecordLayerData( fd, @@ -162,7 +161,7 @@ impl AgentIoInput { assert!(self.input.is_null()); self.input = input.as_ptr(); self.available = input.len(); - trace!("AgentIoInput wrap {:p}", self.input); + qtrace!("AgentIoInput wrap {:p}", self.input); AgentIoInputContext { input: self } } @@ -178,7 +177,7 @@ impl AgentIoInput { #[allow(clippy::disallowed_methods)] // We just checked if this was empty. let src = unsafe { std::slice::from_raw_parts(self.input, amount) }; - trace!("[{self}] read {}", hex(src)); + qtrace!("[{self}] read {}", hex(src)); let dst = unsafe { std::slice::from_raw_parts_mut(buf, amount) }; dst.copy_from_slice(src); self.input = self.input.wrapping_add(amount); @@ -187,7 +186,7 @@ impl AgentIoInput { } fn reset(&mut self) { - trace!("[{self}] reset"); + qtrace!("[{self}] reset"); self.input = null(); self.available = 0; } @@ -231,12 +230,12 @@ impl AgentIo { // Stage output from TLS into the output buffer. fn save_output(&mut self, buf: *const u8, count: usize) { let slice = unsafe { null_safe_slice(buf, count) }; - trace!("[{self}] save output {}", hex(slice)); + qtrace!("[{self}] save output {}", hex(slice)); self.output.extend_from_slice(slice); } pub fn take_output(&mut self) -> Vec { - trace!("[{self}] take output"); + qtrace!("[{self}] take output"); mem::take(&mut self.output) } } diff --git a/neqo-crypto/src/cert.rs b/neqo-crypto/src/cert.rs index 0fe936bc19..73b78173e0 100644 --- a/neqo-crypto/src/cert.rs +++ b/neqo-crypto/src/cert.rs @@ -6,7 +6,7 @@ use std::ptr::NonNull; -use log::error; +use neqo_common::qerror; use crate::{ experimental_api, null_safe_slice, @@ -46,7 +46,7 @@ fn stapled_ocsp_responses(fd: *mut PRFileDesc) -> Option>> { Some(ocsp_ptr) => { let mut ocsp_helper: Vec> = Vec::new(); let Ok(len) = isize::try_from(unsafe { ocsp_ptr.as_ref().len }) else { - error!("[{fd:p}] Received illegal OSCP length"); + qerror!("[{fd:p}] Received illegal OSCP length"); return None; }; for idx in 0..len { diff --git a/neqo-crypto/src/ech.rs b/neqo-crypto/src/ech.rs index e0635b6ce9..29c4d2a370 100644 --- a/neqo-crypto/src/ech.rs +++ b/neqo-crypto/src/ech.rs @@ -10,7 +10,7 @@ use std::{ ptr::{addr_of_mut, null_mut}, }; -use log::trace; +use neqo_common::qtrace; use crate::{ err::{ssl::SSL_ERROR_ECH_RETRY_WITH_ECH, Error, Res}, @@ -146,7 +146,7 @@ pub fn generate_keys() -> Res<(PrivateKey, PublicKey)> { assert_eq!(secret_ptr.is_null(), public_ptr.is_null()); let sk = PrivateKey::from_ptr(secret_ptr)?; let pk = PublicKey::from_ptr(public_ptr)?; - trace!("Generated key pair: sk={sk:?} pk={pk:?}"); + qtrace!("Generated key pair: sk={sk:?} pk={pk:?}"); Ok((sk, pk)) } diff --git a/neqo-crypto/src/lib.rs b/neqo-crypto/src/lib.rs index fed13cc20c..1816440d63 100644 --- a/neqo-crypto/src/lib.rs +++ b/neqo-crypto/src/lib.rs @@ -60,8 +60,8 @@ pub use self::{ }; mod min_version; -use log::error; use min_version::MINIMUM_NSS_VERSION; +use neqo_common::qerror; #[allow(non_upper_case_globals)] mod nss { @@ -94,7 +94,7 @@ static INITIALIZED: OnceLock> = OnceLock::new(); fn version_check() -> Res<()> { let min_ver = CString::new(MINIMUM_NSS_VERSION)?; if unsafe { nss::NSS_VersionCheck(min_ver.as_ptr()) } == 0 { - error!("Minimum NSS version of {MINIMUM_NSS_VERSION} not supported"); + qerror!("Minimum NSS version of {MINIMUM_NSS_VERSION} not supported"); return Err(Error::UnsupportedVersion); } Ok(()) diff --git a/neqo-crypto/src/secrets.rs b/neqo-crypto/src/secrets.rs index fab4a0b8bd..5d17d5fcde 100644 --- a/neqo-crypto/src/secrets.rs +++ b/neqo-crypto/src/secrets.rs @@ -6,7 +6,7 @@ use std::{os::raw::c_void, pin::Pin}; -use log::debug; +use neqo_common::qdebug; use crate::{ agentio::as_c_void, @@ -88,7 +88,7 @@ impl Secrets { } fn put(&mut self, dir: SecretDirection, epoch: Epoch, key: SymKey) { - debug!("{dir:?} secret available for {epoch:?}: {key:?}"); + qdebug!("{dir:?} secret available for {epoch:?}: {key:?}"); let keys = match dir { SecretDirection::Read => &mut self.r, SecretDirection::Write => &mut self.w, diff --git a/neqo-crypto/src/selfencrypt.rs b/neqo-crypto/src/selfencrypt.rs index b8661876fc..7e5c6bb964 100644 --- a/neqo-crypto/src/selfencrypt.rs +++ b/neqo-crypto/src/selfencrypt.rs @@ -6,8 +6,7 @@ use std::mem; -use log::{info, trace}; -use neqo_common::{hex, Encoder}; +use neqo_common::{hex, qinfo, qtrace, Encoder}; use crate::{ constants::{Cipher, Version}, @@ -62,7 +61,7 @@ impl SelfEncrypt { self.old_key = Some(mem::replace(&mut self.key, new_key)); let (kid, _) = self.key_id.overflowing_add(1); self.key_id = kid; - info!("[SelfEncrypt] Rotated keys to {}", self.key_id); + qinfo!("[SelfEncrypt] Rotated keys to {}", self.key_id); Ok(()) } @@ -99,7 +98,7 @@ impl SelfEncrypt { let mut output: Vec = enc.into(); output.resize(encoded_len, 0); cipher.encrypt(0, extended_aad.as_ref(), plaintext, &mut output[offset..])?; - trace!( + qtrace!( "[SelfEncrypt] seal {} {} -> {}", hex(aad), hex(plaintext), @@ -149,7 +148,7 @@ impl SelfEncrypt { aead.decrypt(0, extended_aad.as_ref(), &ciphertext[offset..], &mut output)?; let final_len = decrypted.len(); output.truncate(final_len); - trace!( + qtrace!( "[SelfEncrypt] open {} {} -> {}", hex(aad), hex(ciphertext), diff --git a/neqo-crypto/tests/handshake.rs b/neqo-crypto/tests/handshake.rs index 3e78f430c9..799ccba34e 100644 --- a/neqo-crypto/tests/handshake.rs +++ b/neqo-crypto/tests/handshake.rs @@ -8,7 +8,7 @@ use std::{mem, time::Instant}; -use log::info; +use neqo_common::qinfo; use neqo_crypto::{ AntiReplay, AuthenticationStatus, Client, HandshakeState, RecordList, Res, ResumptionToken, SecretAgent, Server, ZeroRttCheckResult, ZeroRttChecker, @@ -68,8 +68,8 @@ fn handshake(now: Instant, client: &mut SecretAgent, server: &mut SecretAgent) { #[allow(clippy::missing_panics_doc)] pub fn connect_at(now: Instant, client: &mut SecretAgent, server: &mut SecretAgent) { handshake(now, client, server); - info!("client: {:?}", client.state()); - info!("server: {:?}", server.state()); + qinfo!("client: {:?}", client.state()); + qinfo!("server: {:?}", server.state()); assert!(client.state().is_connected()); assert!(server.state().is_connected()); } diff --git a/neqo-http3/src/buffered_send_stream.rs b/neqo-http3/src/buffered_send_stream.rs index f6a824b550..292a1495fe 100644 --- a/neqo-http3/src/buffered_send_stream.rs +++ b/neqo-http3/src/buffered_send_stream.rs @@ -4,7 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use log::trace; +use neqo_common::qtrace; use neqo_transport::{Connection, StreamId}; use crate::{qlog, Res}; @@ -69,7 +69,7 @@ impl BufferedStream { if buf.is_empty() { return Ok(0); } - trace!("[{label}] sending data"); + qtrace!("[{label}] sending data"); let sent = conn.stream_send(*stream_id, &buf[..])?; if sent == 0 { return Ok(0); diff --git a/neqo-http3/src/connection.rs b/neqo-http3/src/connection.rs index 175dda6f75..b098c1b5fc 100644 --- a/neqo-http3/src/connection.rs +++ b/neqo-http3/src/connection.rs @@ -14,8 +14,7 @@ use std::{ rc::Rc, }; -use log::{debug, error, info, trace, warn}; -use neqo_common::{Decoder, Header, MessageType, Role}; +use neqo_common::{qdebug, qerror, qinfo, qtrace, qwarn, Decoder, Header, MessageType, Role}; use neqo_qpack::{decoder::QPackDecoder, encoder::QPackEncoder}; use neqo_transport::{ streams::SendOrder, AppError, CloseReason, Connection, DatagramTracking, State, StreamId, @@ -353,7 +352,7 @@ impl Http3Connection { /// This function creates and initializes, i.e. send stream type, the control and qpack /// streams. fn initialize_http3_connection(&mut self, conn: &mut Connection) -> Res<()> { - debug!("[{self}] Initialize the http3 connection"); + qdebug!("[{self}] Initialize the http3 connection"); self.control_stream_local.create(conn)?; self.send_settings(); @@ -362,7 +361,7 @@ impl Http3Connection { } fn send_settings(&mut self) { - debug!("[{self}] Send settings"); + qdebug!("[{self}] Send settings"); self.control_stream_local.queue_frame(&HFrame::Settings { settings: HSettings::from(&self.local_params), }); @@ -375,7 +374,7 @@ impl Http3Connection { } fn create_qpack_streams(&self, conn: &mut Connection) -> Res<()> { - debug!("[{self}] create_qpack_streams"); + qdebug!("[{self}] create_qpack_streams"); self.qpack_encoder .borrow_mut() .add_send_stream(conn.stream_create(StreamType::UniDi)?); @@ -459,7 +458,7 @@ impl Http3Connection { /// This is called when a `ConnectionEvent::NewStream` event is received. This register the /// stream with a `NewStreamHeadReader` handler. pub fn add_new_stream(&mut self, stream_id: StreamId) { - trace!("[{self}] A new stream: {stream_id}"); + qtrace!("[{self}] A new stream: {stream_id}"); self.recv_streams.insert( stream_id, Box::new(NewStreamHeadReader::new(stream_id, self.role)), @@ -469,7 +468,7 @@ impl Http3Connection { /// The function calls `receive` for a stream. It also deals with the outcome of a read by /// calling `handle_stream_manipulation_output`. fn stream_receive(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res { - trace!("[{self}] Readable stream {stream_id}"); + qtrace!("[{self}] Readable stream {stream_id}"); if let Some(recv_stream) = self.recv_streams.get_mut(&stream_id) { let res = recv_stream.receive(conn); @@ -486,7 +485,7 @@ impl Http3Connection { conn: &mut Connection, ) -> Res<()> { for stream_id in unblocked_streams { - debug!("[{self}] Stream {stream_id} is unblocked"); + qdebug!("[{self}] Stream {stream_id} is unblocked"); if let Some(r) = self.recv_streams.get_mut(&stream_id) { let res = r .http_stream() @@ -552,7 +551,7 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] Handle a stream reset stream_id={stream_id} app_err={app_error}"); + qinfo!("[{self}] Handle a stream reset stream_id={stream_id} app_err={app_error}"); self.close_recv(stream_id, CloseType::ResetRemote(app_error), conn) } @@ -563,7 +562,7 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] Handle stream_stop_sending stream_id={stream_id} app_err={app_error}"); + qinfo!("[{self}] Handle stream_stop_sending stream_id={stream_id} app_err={app_error}"); if self.send_stream_is_critical(stream_id) { return Err(Error::HttpClosedCriticalStream); @@ -576,7 +575,7 @@ impl Http3Connection { /// This is called when `neqo_transport::Connection` state has been change to take proper /// actions in the HTTP3 layer. pub fn handle_state_change(&mut self, conn: &mut Connection, state: &State) -> Res { - debug!("[{self}] Handle state change {state:?}"); + qdebug!("[{self}] Handle state change {state:?}"); match state { State::Handshaking => { if self.role == Role::Server @@ -687,10 +686,10 @@ impl Http3Connection { } NewStreamType::Push(push_id) => { - info!("[{self}] A new push stream {stream_id} push_id:{push_id}"); + qinfo!("[{self}] A new push stream {stream_id} push_id:{push_id}"); } NewStreamType::Decoder => { - debug!("[{self}] A new remote qpack encoder stream {stream_id}"); + qdebug!("[{self}] A new remote qpack encoder stream {stream_id}"); self.check_stream_exists(Http3StreamType::Decoder)?; self.recv_streams.insert( stream_id, @@ -701,7 +700,7 @@ impl Http3Connection { ); } NewStreamType::Encoder => { - debug!("[{self}] A new remote qpack decoder stream {stream_id}"); + qdebug!("[{self}] A new remote qpack decoder stream {stream_id}"); self.check_stream_exists(Http3StreamType::Encoder)?; self.recv_streams.insert( stream_id, @@ -712,7 +711,7 @@ impl Http3Connection { ); } NewStreamType::Http(_) => { - info!("[{self}] A new http stream {stream_id}"); + qinfo!("[{self}] A new http stream {stream_id}"); } NewStreamType::WebTransportStream(session_id) => { let session_exists = self @@ -725,7 +724,7 @@ impl Http3Connection { } // set incoming WebTransport streams to be fair (share bandwidth) conn.stream_fairness(stream_id, true).ok(); - info!("[{self}] A new WebTransport stream {stream_id} for session {session_id}"); + qinfo!("[{self}] A new WebTransport stream {stream_id} for session {session_id}"); } NewStreamType::Unknown => { conn.stream_stop_sending(stream_id, Error::HttpStreamCreation.code())?; @@ -745,10 +744,10 @@ impl Http3Connection { /// This is called when an application closes the connection. pub fn close(&mut self, error: AppError) { - debug!("[{self}] Close connection error {error:?}"); + qdebug!("[{self}] Close connection error {error:?}"); self.state = Http3State::Closing(CloseReason::Application(error)); if (!self.send_streams.is_empty() || !self.recv_streams.is_empty()) && (error == 0) { - warn!("close(0) called when streams still active"); + qwarn!("close(0) called when streams still active"); } self.send_streams.clear(); self.recv_streams.clear(); @@ -830,9 +829,10 @@ impl Http3Connection { where T: AsRequestTarget<'t> + ?Sized + Debug, { - info!( + qinfo!( "[{self}] Fetch method={} target: {:?}", - request.method, request.target, + request.method, + request.target, ); let id = self.create_bidi_transport_stream(conn)?; self.fetch_with_stream(id, conn, send_events, recv_events, push_handler, request)?; @@ -930,7 +930,7 @@ impl Http3Connection { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - debug!("[{self}] read_data from stream {stream_id}"); + qdebug!("[{self}] read_data from stream {stream_id}"); let res = self .recv_streams .get_mut(&stream_id) @@ -947,7 +947,7 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - info!("[{self}] Reset sending side of stream {stream_id} error={error}"); + qinfo!("[{self}] Reset sending side of stream {stream_id} error={error}"); if self.send_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); @@ -964,7 +964,7 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - info!("[{self}] Send stop sending for stream {stream_id} error={error}"); + qinfo!("[{self}] Send stop sending for stream {stream_id} error={error}"); if self.recv_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); } @@ -1012,7 +1012,7 @@ impl Http3Connection { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] cancel_fetch {stream_id} error={error}"); + qinfo!("[{self}] cancel_fetch {stream_id} error={error}"); let send_stream = self.send_streams.get(&stream_id); let recv_stream = self.recv_streams.get(&stream_id); match (send_stream, recv_stream) { @@ -1059,7 +1059,7 @@ impl Http3Connection { /// This is called when an application wants to close the sending side of a stream. pub fn stream_close_send(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { - debug!("[{self}] Close the sending side for stream {stream_id}"); + qdebug!("[{self}] Close the sending side for stream {stream_id}"); debug_assert!(self.state.active()); let send_stream = self .send_streams @@ -1086,7 +1086,7 @@ impl Http3Connection { where T: AsRequestTarget<'x> + ?Sized + Debug, { - info!("[{self}] Create WebTransport"); + qinfo!("[{self}] Create WebTransport"); if !self.webtransport_enabled() { return Err(Error::Unavailable); } @@ -1127,7 +1127,7 @@ impl Http3Connection { events: Box, accept_res: &WebTransportSessionAcceptAction, ) -> Res<()> { - trace!("Respond to WebTransport session with accept={accept_res}"); + qtrace!("Respond to WebTransport session with accept={accept_res}"); if !self.webtransport_enabled() { return Err(Error::Unavailable); } @@ -1203,7 +1203,7 @@ impl Http3Connection { error: u32, message: &str, ) -> Res<()> { - trace!("Close WebTransport session {session_id:?}"); + qtrace!("Close WebTransport session {session_id:?}"); let send_stream = self .send_streams .get_mut(&session_id) @@ -1229,7 +1229,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res { - trace!("Create new WebTransport stream session={session_id} type={stream_type:?}"); + qtrace!("Create new WebTransport stream session={session_id} type={stream_type:?}"); let wt = self .recv_streams @@ -1266,7 +1266,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res<()> { - trace!("Create new WebTransport stream session={session_id} stream_id={stream_id}"); + qtrace!("Create new WebTransport stream session={session_id} stream_id={stream_id}"); let wt = self .recv_streams @@ -1359,7 +1359,7 @@ impl Http3Connection { /// `PriorityUpdateRequestPush` which handling is specific to the client and server, we must /// give them to the specific client/server handler. fn handle_control_frame(&mut self, f: HFrame) -> Res> { - debug!("[{self}] Handle a control frame {f:?}"); + qdebug!("[{self}] Handle a control frame {f:?}"); if !matches!(f, HFrame::Settings { .. }) && !matches!( self.settings_state, @@ -1390,7 +1390,7 @@ impl Http3Connection { } fn handle_settings(&mut self, new_settings: HSettings) -> Res<()> { - debug!("[{self}] Handle SETTINGS frame"); + qdebug!("[{self}] Handle SETTINGS frame"); match &self.settings_state { Http3RemoteSettingsState::NotReceived => { self.set_qpack_settings(&new_settings)?; @@ -1412,7 +1412,7 @@ impl Http3Connection { continue; } if zero_rtt_value > new_value { - error!( + qerror!( "[{self}] The new({new_value}) and the old value({zero_rtt_value}) of setting {st:?} do not match" ); return Err(Error::HttpSettings); @@ -1432,7 +1432,7 @@ impl Http3Connection { } } if qpack_changed { - debug!("[{self}] Settings after zero rtt differ"); + qdebug!("[{self}] Settings after zero rtt differ"); self.set_qpack_settings(&(new_settings))?; } self.settings_state = Http3RemoteSettingsState::Received(new_settings); @@ -1531,7 +1531,7 @@ impl Http3Connection { let (recv, send) = wt.borrow_mut().take_sub_streams(); for id in recv { - trace!("Remove the extended connect sub receiver stream {id}"); + qtrace!("Remove the extended connect sub receiver stream {id}"); // Use CloseType::ResetRemote so that an event will be sent. CloseType::LocalError would // have the same effect. if let Some(mut s) = self.recv_streams.remove(&id) { @@ -1540,7 +1540,7 @@ impl Http3Connection { mem::drop(conn.stream_stop_sending(id, Error::HttpRequestCancelled.code())); } for id in send { - trace!("Remove the extended connect sub send stream {id}"); + qtrace!("Remove the extended connect sub send stream {id}"); if let Some(mut s) = self.send_streams.remove(&id) { s.handle_stop_sending(CloseType::ResetRemote(Error::HttpRequestCancelled.code())); } diff --git a/neqo-http3/src/connection_client.rs b/neqo-http3/src/connection_client.rs index 7a9d87c2c2..3f43e92c0f 100644 --- a/neqo-http3/src/connection_client.rs +++ b/neqo-http3/src/connection_client.rs @@ -13,10 +13,9 @@ use std::{ time::Instant, }; -use log::{debug, info, trace}; use neqo_common::{ - event::Provider as EventProvider, hex, hex_with_len, qlog::NeqoQlog, Datagram, Decoder, - Encoder, Header, MessageType, Role, + event::Provider as EventProvider, hex, hex_with_len, qdebug, qinfo, qlog::NeqoQlog, qtrace, + Datagram, Decoder, Encoder, Header, MessageType, Role, }; use neqo_crypto::{agent::CertificateInfo, AuthenticationStatus, ResumptionToken, SecretAgentInfo}; use neqo_qpack::Stats as QpackStats; @@ -455,7 +454,7 @@ impl Http3Client { let Some(settings_slice) = dec.decode_vvec() else { return Err(Error::InvalidResumptionToken); }; - trace!("[{self}] settings {}", hex_with_len(settings_slice)); + qtrace!("[{self}] settings {}", hex_with_len(settings_slice)); let mut dec_settings = Decoder::from(settings_slice); let mut settings = HSettings::default(); Error::map_error( @@ -463,7 +462,7 @@ impl Http3Client { Error::InvalidResumptionToken, )?; let tok = dec.decode_remainder(); - trace!("[{self}] Transport token {}", hex(tok)); + qtrace!("[{self}] Transport token {}", hex(tok)); self.conn.enable_resumption(now, tok)?; if self.conn.state().closed() { let state = self.conn.state().clone(); @@ -490,7 +489,7 @@ impl Http3Client { where S: AsRef + Display, { - info!("[{self}] Close the connection error={error} msg={msg}"); + qinfo!("[{self}] Close the connection error={error} msg={msg}"); if !matches!( self.base_handler.state, Http3State::Closing(_) | Http3State::Closed(_) @@ -578,7 +577,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn cancel_fetch(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - info!("[{self}] reset_stream {stream_id} error={error}"); + qinfo!("[{self}] reset_stream {stream_id} error={error}"); self.base_handler .cancel_fetch(stream_id, error, &mut self.conn) } @@ -589,7 +588,7 @@ impl Http3Client { /// /// An error will be return if stream does not exist. pub fn stream_close_send(&mut self, stream_id: StreamId) -> Res<()> { - debug!("[{self}] Close sending side stream={stream_id}"); + qdebug!("[{self}] Close sending side stream={stream_id}"); self.base_handler .stream_close_send(&mut self.conn, stream_id) } @@ -598,7 +597,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn stream_reset_send(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - info!("[{self}] stream_reset_send {stream_id} error={error}"); + qinfo!("[{self}] stream_reset_send {stream_id} error={error}"); self.base_handler .stream_reset_send(&mut self.conn, stream_id, error) } @@ -607,7 +606,7 @@ impl Http3Client { /// /// An error will be return if a stream does not exist. pub fn stream_stop_sending(&mut self, stream_id: StreamId, error: AppError) -> Res<()> { - info!("[{self}] stream_stop_sending {stream_id} error={error}"); + qinfo!("[{self}] stream_stop_sending {stream_id} error={error}"); self.base_handler .stream_stop_sending(&mut self.conn, stream_id, error) } @@ -625,7 +624,7 @@ impl Http3Client { /// info that the stream has been closed.) `InvalidInput` if an empty buffer has been /// supplied. pub fn send_data(&mut self, stream_id: StreamId, buf: &[u8]) -> Res { - info!( + qinfo!( "[{self}] end_data from stream {stream_id} sending {} bytes", buf.len() ); @@ -649,7 +648,7 @@ impl Http3Client { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - debug!("[{self}] read_data from stream {stream_id}"); + qdebug!("[{self}] read_data from stream {stream_id}"); let res = self.base_handler.read_data(&mut self.conn, stream_id, buf); if let Err(e) = &res { if e.connection_error() { @@ -774,7 +773,7 @@ impl Http3Client { buf: &[u8], id: impl Into, ) -> Res<()> { - trace!("webtransport_send_datagram session:{session_id:?}"); + qtrace!("webtransport_send_datagram session:{session_id:?}"); self.base_handler .webtransport_send_datagram(session_id, &mut self.conn, buf, id) } @@ -853,7 +852,7 @@ impl Http3Client { /// This function combines `process_input` and `process_output` function. pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - trace!("[{self}] Process"); + qtrace!("[{self}] Process"); if let Some(d) = dgram { self.process_input(d, now); } @@ -880,7 +879,7 @@ impl Http3Client { now: Instant, ) { let mut dgrams = dgrams.into_iter().peekable(); - trace!("[{self}] Process multiple datagrams"); + qtrace!("[{self}] Process multiple datagrams"); if dgrams.peek().is_none() { return; } @@ -894,7 +893,7 @@ impl Http3Client { /// the QUC layer and calls `Http3Connection::process_sending` to ensure that HTTP/3 layer /// data, e.g. control frames, are sent. fn process_http3(&mut self, now: Instant) { - trace!("[{self}] Process http3 internal"); + qtrace!("[{self}] Process http3 internal"); match self.base_handler.state() { Http3State::ZeroRtt | Http3State::Connected | Http3State::GoingAway(..) => { let res = self.check_connection_events(); @@ -943,7 +942,7 @@ impl Http3Client { /// [2]: ../neqo_transport/struct.ConnectionEvents.html /// [3]: ../neqo_transport/struct.Connection.html#method.process_output pub fn process_output(&mut self, now: Instant) -> Output { - trace!("[{self}] Process output"); + qtrace!("[{self}] Process output"); // Maybe send() stuff on http3-managed streams self.process_http3(now); @@ -961,7 +960,7 @@ impl Http3Client { fn check_result(&mut self, now: Instant, res: &Res) -> bool { match &res { Err(Error::HttpGoaway) => { - info!("[{self}] Connection error: goaway stream_id increased"); + qinfo!("[{self}] Connection error: goaway stream_id increased"); self.close( now, Error::HttpGeneralProtocol.code(), @@ -970,7 +969,7 @@ impl Http3Client { true } Err(e) => { - info!("[{self}] Connection error: {e}"); + qinfo!("[{self}] Connection error: {e}"); self.close(now, e.code(), format!("{e}")); true } @@ -993,9 +992,9 @@ impl Http3Client { /// [2]: ../neqo_transport/enum.ConnectionEvent.html /// [3]: ../neqo_transport/enum.ConnectionEvent.html#variant.RecvStreamReadable fn check_connection_events(&mut self) -> Res<()> { - trace!("[{self}] Check connection events"); + qtrace!("[{self}] Check connection events"); while let Some(e) = self.conn.next_event() { - debug!("[{self}] check_connection_events - event {e:?}"); + qdebug!("[{self}] check_connection_events - event {e:?}"); match e { ConnectionEvent::NewStream { stream_id } => { // During this event we only add a new stream to the Http3Connection stream @@ -1177,7 +1176,7 @@ impl Http3Client { } fn handle_goaway(&mut self, goaway_stream_id: StreamId) -> Res<()> { - info!("[{self}] handle_goaway {goaway_stream_id}"); + qinfo!("[{self}] handle_goaway {goaway_stream_id}"); if goaway_stream_id.is_uni() || goaway_stream_id.is_server_initiated() { return Err(Error::HttpId); @@ -1285,8 +1284,7 @@ impl EventProvider for Http3Client { mod tests { use std::{mem, time::Duration}; - use log::trace; - use neqo_common::{event::Provider, Datagram, Decoder, Encoder}; + use neqo_common::{event::Provider, qtrace, Datagram, Decoder, Encoder}; use neqo_crypto::{AllowZeroRtt, AntiReplay, ResumptionToken}; use neqo_qpack::{encoder::QPackEncoder, QpackSettings}; use neqo_transport::{ @@ -1470,7 +1468,7 @@ mod tests { pub fn create_control_stream(&mut self) { // Create control stream let control = self.conn.stream_create(StreamType::UniDi).unwrap(); - trace!("[TestServer] control stream: {control}"); + qtrace!("[TestServer] control stream: {control}"); self.control_stream_id = Some(control); // Send stream type on the control stream. assert_eq!( diff --git a/neqo-http3/src/connection_server.rs b/neqo-http3/src/connection_server.rs index 218606699a..6c0d843f3f 100644 --- a/neqo-http3/src/connection_server.rs +++ b/neqo-http3/src/connection_server.rs @@ -6,8 +6,7 @@ use std::{rc::Rc, time::Instant}; -use log::{debug, info, trace}; -use neqo_common::{event::Provider, Header, MessageType, Role}; +use neqo_common::{event::Provider, qdebug, qinfo, qtrace, Header, MessageType, Role}; use neqo_transport::{ AppError, Connection, ConnectionEvent, DatagramTracking, StreamId, StreamType, }; @@ -103,7 +102,7 @@ impl Http3ServerHandler { /// /// An error will be returned if stream does not exist. pub fn stream_close_send(&mut self, stream_id: StreamId, conn: &mut Connection) -> Res<()> { - debug!("[{self}] Close sending side stream={stream_id}"); + qdebug!("[{self}] Close sending side stream={stream_id}"); self.base_handler.stream_close_send(conn, stream_id)?; self.needs_processing = true; Ok(()) @@ -121,7 +120,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] cancel_fetch {stream_id} error={error}"); + qinfo!("[{self}] cancel_fetch {stream_id} error={error}"); self.needs_processing = true; self.base_handler.cancel_fetch(stream_id, error, conn) } @@ -132,7 +131,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] stream_stop_sending {stream_id} error={error}"); + qinfo!("[{self}] stream_stop_sending {stream_id} error={error}"); self.needs_processing = true; self.base_handler .stream_stop_sending(conn, stream_id, error) @@ -144,7 +143,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - info!("[{self}] stream_reset_send {stream_id} error={error}"); + qinfo!("[{self}] stream_reset_send {stream_id} error={error}"); self.needs_processing = true; self.base_handler.stream_reset_send(conn, stream_id, error) } @@ -216,7 +215,7 @@ impl Http3ServerHandler { /// Process HTTTP3 layer. pub fn process_http3(&mut self, conn: &mut Connection, now: Instant) { - trace!("[{self}] Process http3 internal"); + qtrace!("[{self}] Process http3 internal"); if matches!(self.base_handler.state(), Http3State::Closed(..)) { return; } @@ -255,7 +254,7 @@ impl Http3ServerHandler { } fn close(&mut self, conn: &mut Connection, now: Instant, err: &Error) { - info!("[{self}] Connection error: {err}"); + qinfo!("[{self}] Connection error: {err}"); conn.close(now, err.code(), format!("{err}")); self.base_handler.close(err.code()); self.events @@ -264,9 +263,9 @@ impl Http3ServerHandler { // If this return an error the connection must be closed. fn check_connection_events(&mut self, conn: &mut Connection, now: Instant) -> Res<()> { - trace!("[{self}] Check connection events"); + qtrace!("[{self}] Check connection events"); while let Some(e) = conn.next_event() { - debug!("[{self}] check_connection_events - event {e:?}"); + qdebug!("[{self}] check_connection_events - event {e:?}"); match e { ConnectionEvent::NewStream { stream_id } => { self.base_handler.add_new_stream(stream_id); @@ -412,7 +411,7 @@ impl Http3ServerHandler { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - debug!("[{self}] read_data from stream {stream_id}"); + qdebug!("[{self}] read_data from stream {stream_id}"); let res = self.base_handler.read_data(conn, stream_id, buf); if let Err(e) = &res { if e.connection_error() { diff --git a/neqo-http3/src/control_stream_local.rs b/neqo-http3/src/control_stream_local.rs index d41f2a09d5..db30df1950 100644 --- a/neqo-http3/src/control_stream_local.rs +++ b/neqo-http3/src/control_stream_local.rs @@ -6,8 +6,7 @@ use std::collections::{HashMap, VecDeque}; -use log::trace; -use neqo_common::Encoder; +use neqo_common::{qtrace, Encoder}; use neqo_transport::{Connection, StreamId, StreamType}; use crate::{frames::HFrame, BufferedStream, Http3StreamType, RecvStream, Res}; @@ -93,7 +92,7 @@ impl ControlStreamLocal { /// Create a control stream. pub fn create(&mut self, conn: &mut Connection) -> Res<()> { - trace!("[{self}] Create a control stream"); + qtrace!("[{self}] Create a control stream"); self.stream.init(conn.stream_create(StreamType::UniDi)?); self.stream .buffer(&[u8::try_from(HTTP3_UNI_STREAM_TYPE_CONTROL).unwrap()]); diff --git a/neqo-http3/src/control_stream_remote.rs b/neqo-http3/src/control_stream_remote.rs index 8ebb82c307..644e3b55d8 100644 --- a/neqo-http3/src/control_stream_remote.rs +++ b/neqo-http3/src/control_stream_remote.rs @@ -4,7 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use log::debug; +use neqo_common::qdebug; use neqo_transport::{Connection, StreamId}; use crate::{ @@ -36,7 +36,7 @@ impl ControlStreamRemote { /// Check if a stream is the control stream and read received data. pub fn receive_single(&mut self, conn: &mut Connection) -> Res> { - debug!("[{self}] Receiving data"); + qdebug!("[{self}] Receiving data"); match self .frame_reader .receive(&mut StreamReaderConnectionWrapper::new( @@ -45,7 +45,7 @@ impl ControlStreamRemote { ))? { (_, true) => Err(Error::HttpClosedCriticalStream), (s, false) => { - debug!("[{self}] received {s:?}"); + qdebug!("[{self}] received {s:?}"); Ok(s) } } diff --git a/neqo-http3/src/features/extended_connect/webtransport_session.rs b/neqo-http3/src/features/extended_connect/webtransport_session.rs index f8500e7ce9..a7d7262e75 100644 --- a/neqo-http3/src/features/extended_connect/webtransport_session.rs +++ b/neqo-http3/src/features/extended_connect/webtransport_session.rs @@ -6,8 +6,7 @@ use std::{cell::RefCell, collections::BTreeSet, mem, rc::Rc}; -use log::trace; -use neqo_common::{Encoder, Header, MessageType, Role}; +use neqo_common::{qtrace, Encoder, Header, MessageType, Role}; use neqo_qpack::{QPackDecoder, QPackEncoder}; use neqo_transport::{Connection, DatagramTracking, StreamId}; @@ -147,7 +146,7 @@ impl WebTransportSession { } fn receive(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { - trace!("[{self}] receive control data"); + qtrace!("[{self}] receive control data"); let (out, _) = self.control_stream_recv.receive(conn)?; debug_assert!(out == ReceiveOutput::NoOutput); self.maybe_check_headers(); @@ -208,7 +207,7 @@ impl WebTransportSession { if self.state.closing_state() { return; } - trace!("ExtendedConnect close the session"); + qtrace!("ExtendedConnect close the session"); self.state = SessionState::Done; if !close_type.locally_initiated() { self.events.session_end( @@ -230,7 +229,7 @@ impl WebTransportSession { if let Some((headers, interim, fin)) = self.stream_event_listener.borrow_mut().get_headers() { - trace!("ExtendedConnect response headers {headers:?}, fin={fin}"); + qtrace!("ExtendedConnect response headers {headers:?}, fin={fin}"); if interim { if fin { @@ -343,7 +342,7 @@ impl WebTransportSession { &mut self.control_stream_recv, )) .map_err(|_| Error::HttpGeneralProtocolStream)?; - trace!("[{self}] Received frame: {f:?} fin={fin}"); + qtrace!("[{self}] Received frame: {f:?} fin={fin}"); if let Some(WebTransportFrame::CloseSession { error, message }) = f { self.events.session_end( ExtendedConnectType::WebTransport, @@ -407,7 +406,7 @@ impl WebTransportSession { buf: &[u8], id: impl Into, ) -> Res<()> { - trace!("[{self}] send_datagram state={:?}", self.state); + qtrace!("[{self}] send_datagram state={:?}", self.state); if self.state == SessionState::Active { let mut dgram_data = Encoder::default(); dgram_data.encode_varint(self.session_id.as_u64() / 4); diff --git a/neqo-http3/src/features/mod.rs b/neqo-http3/src/features/mod.rs index 0bb7d4d7b7..e9b41b7b05 100644 --- a/neqo-http3/src/features/mod.rs +++ b/neqo-http3/src/features/mod.rs @@ -6,7 +6,7 @@ use std::{fmt::Debug, mem}; -use log::trace; +use neqo_common::qtrace; use crate::{ client_events::Http3ClientEvents, @@ -62,7 +62,7 @@ impl NegotiationState { listener, } = self { - trace!( + qtrace!( "set_negotiated {feature_type:?} to {}", settings.get(*feature_type) ); diff --git a/neqo-http3/src/frames/reader.rs b/neqo-http3/src/frames/reader.rs index fc54609c07..445988691d 100644 --- a/neqo-http3/src/frames/reader.rs +++ b/neqo-http3/src/frames/reader.rs @@ -8,9 +8,8 @@ use std::fmt::Debug; -use log::trace; use neqo_common::{ - hex_with_len, Decoder, IncrementalDecoderBuffer, IncrementalDecoderIgnore, + hex_with_len, qtrace, Decoder, IncrementalDecoderBuffer, IncrementalDecoderIgnore, IncrementalDecoderUint, }; use neqo_transport::{Connection, StreamId}; @@ -174,7 +173,7 @@ impl FrameReader { { (0, f) => (None, false, f), (amount, f) => { - trace!("FrameReader::receive: reading {amount} byte, fin={f}"); + qtrace!("FrameReader::receive: reading {amount} byte, fin={f}"); (self.consume::(Decoder::from(&buf[..amount]))?, true, f) } }; @@ -204,13 +203,13 @@ impl FrameReader { match &mut self.state { FrameReaderState::GetType { decoder } => { if let Some(v) = decoder.consume(&mut input) { - trace!("FrameReader::receive: read frame type {v}"); + qtrace!("FrameReader::receive: read frame type {v}"); self.frame_type_decoded::(HFrameType(v))?; } } FrameReaderState::GetLength { decoder } => { if let Some(len) = decoder.consume(&mut input) { - trace!( + qtrace!( "FrameReader::receive: frame type {:?} length {len}", self.frame_type ); @@ -219,7 +218,7 @@ impl FrameReader { } FrameReaderState::GetData { decoder } => { if let Some(data) = decoder.consume(&mut input) { - trace!( + qtrace!( "received frame {:?}: {}", self.frame_type, hex_with_len(&data[..]) diff --git a/neqo-http3/src/push_controller.rs b/neqo-http3/src/push_controller.rs index 41774f8436..9537985e7a 100644 --- a/neqo-http3/src/push_controller.rs +++ b/neqo-http3/src/push_controller.rs @@ -13,8 +13,7 @@ use std::{ slice::SliceIndex, }; -use log::{error, info, trace}; -use neqo_common::Header; +use neqo_common::{qerror, qinfo, qtrace, Header}; use neqo_transport::{Connection, StreamId}; use crate::{ @@ -186,7 +185,7 @@ impl PushController { ref_stream_id: StreamId, new_headers: Vec
, ) -> Res<()> { - trace!( + qtrace!( "[{self}] New push promise push_id={push_id} headers={new_headers:?} max_push={}", self.max_concurent_push ); @@ -195,7 +194,7 @@ impl PushController { match self.push_streams.get_mut(push_id) { None => { - trace!("Push has been closed already {push_id}"); + qtrace!("Push has been closed already {push_id}"); Ok(()) } Some(push_state) => match push_state { @@ -235,12 +234,12 @@ impl PushController { } pub fn add_new_push_stream(&mut self, push_id: u64, stream_id: StreamId) -> Res { - trace!("A new push stream with push_id={push_id} stream_id={stream_id}"); + qtrace!("A new push stream with push_id={push_id} stream_id={stream_id}"); self.check_push_id(push_id)?; self.push_streams.get_mut(push_id).map_or_else( || { - info!("Push has been closed already"); + qinfo!("Push has been closed already"); Ok(false) }, |push_state| match push_state { @@ -262,7 +261,7 @@ impl PushController { // The following state have already have a push stream: // PushState::OnlyPushStream | PushState::Active _ => { - error!("Duplicate push stream"); + qerror!("Duplicate push stream"); Err(Error::HttpId) } }, @@ -272,7 +271,7 @@ impl PushController { fn check_push_id(&self, push_id: u64) -> Res<()> { // Check if push id is greater than what we allow. if push_id > self.current_max_push_id { - error!("Push id is greater than current_max_push_id"); + qerror!("Push id is greater than current_max_push_id"); Err(Error::HttpId) } else { Ok(()) @@ -285,13 +284,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - trace!("CANCEL_PUSH frame has been received, push_id={push_id}"); + qtrace!("CANCEL_PUSH frame has been received, push_id={push_id}"); self.check_push_id(push_id)?; match self.push_streams.close(push_id) { None => { - trace!("Push has already been closed (push_id={push_id})"); + qtrace!("Push has already been closed (push_id={push_id})"); Ok(()) } Some(ps) => match ps { @@ -318,7 +317,7 @@ impl PushController { } pub fn close(&mut self, push_id: u64) { - trace!("Push stream has been closed"); + qtrace!("Push stream has been closed"); if let Some(push_state) = self.push_streams.close(push_id) { debug_assert!(matches!(push_state, PushState::Active { .. })); } else { @@ -332,13 +331,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - trace!("Cancel push_id={push_id}"); + qtrace!("Cancel push_id={push_id}"); self.check_push_id(push_id)?; match self.push_streams.get(push_id) { None => { - trace!("Push has already been closed"); + qtrace!("Push has already been closed"); // If we have some events for the push_id in the event queue, the caller still does // not not know that the push has been closed. Otherwise return // InvalidStreamId. @@ -371,7 +370,7 @@ impl PushController { } pub fn push_stream_reset(&mut self, push_id: u64, close_type: CloseType) { - trace!("Push stream has been reset, push_id={push_id}"); + qtrace!("Push stream has been reset, push_id={push_id}"); if let Some(push_state) = self.push_streams.get(push_id) { match push_state { diff --git a/neqo-http3/src/recv_message.rs b/neqo-http3/src/recv_message.rs index 8e8180b0c4..56c3f44705 100644 --- a/neqo-http3/src/recv_message.rs +++ b/neqo-http3/src/recv_message.rs @@ -6,8 +6,7 @@ use std::{cell::RefCell, cmp::min, collections::VecDeque, fmt::Debug, rc::Rc}; -use log::{debug, info, trace}; -use neqo_common::{header::HeadersExt, Header}; +use neqo_common::{header::HeadersExt, qdebug, qinfo, qtrace, Header}; use neqo_qpack::decoder::QPackDecoder; use neqo_transport::{Connection, StreamId}; @@ -153,7 +152,7 @@ impl RecvMessage { } fn add_headers(&mut self, mut headers: Vec
, fin: bool) -> Res<()> { - trace!("[{self}] Add new headers fin={fin}"); + qtrace!("[{self}] Add new headers fin={fin}"); let interim = match self.message_type { MessageType::Request => false, MessageType::Response => is_interim(&headers)?, @@ -200,7 +199,7 @@ impl RecvMessage { fn set_state_to_close_pending(&mut self, post_readable_event: bool) -> Res<()> { // Stream has received fin. Depending on headers state set header_ready // or data_readable event so that app can pick up the fin. - trace!( + qtrace!( "[{self}] set_state_to_close_pending: state={:?}", self.state ); @@ -255,7 +254,7 @@ impl RecvMessage { fn receive_internal(&mut self, conn: &mut Connection, post_readable_event: bool) -> Res<()> { loop { - debug!("[{self}] state={:?}", self.state); + qdebug!("[{self}] state={:?}", self.state); match &mut self.state { // In the following 3 states we need to read frames. RecvMessageState::WaitingForResponseHeaders { frame_reader } @@ -270,7 +269,7 @@ impl RecvMessage { } (None, false) => break Ok(()), (Some(frame), fin) => { - debug!( + qdebug!( "[{self}] A new frame has been received: {frame:?}; state={:?} fin={fin}", self.state, ); match frame { @@ -305,7 +304,7 @@ impl RecvMessage { .refers_dynamic_table(header_block)? && !self.blocked_push_promise.is_empty() { - info!( + qinfo!( "[{self}] decoding header is blocked waiting for a push_promise header block" ); break Ok(()); @@ -324,7 +323,7 @@ impl RecvMessage { break Ok(()); } } else { - info!("[{self}] decoding header is blocked"); + qinfo!("[{self}] decoding header is blocked"); break Ok(()); } } diff --git a/neqo-http3/src/send_message.rs b/neqo-http3/src/send_message.rs index ca3522ef50..3fbaefa5a6 100644 --- a/neqo-http3/src/send_message.rs +++ b/neqo-http3/src/send_message.rs @@ -6,8 +6,7 @@ use std::{cell::RefCell, cmp::min, fmt::Debug, num::NonZeroUsize, rc::Rc}; -use log::{debug, trace}; -use neqo_common::{Encoder, Header, MessageType}; +use neqo_common::{qdebug, qtrace, Encoder, Header, MessageType}; use neqo_qpack::encoder::QPackEncoder; use neqo_transport::{Connection, StreamId}; @@ -120,7 +119,7 @@ impl SendMessage { encoder: Rc>, conn_events: Box, ) -> Self { - debug!("Create a request stream_id={stream_id}"); + qdebug!("Create a request stream_id={stream_id}"); Self { state: MessageState::WaitingForHeaders, message_type, @@ -141,7 +140,7 @@ impl SendMessage { conn: &mut Connection, stream_id: StreamId, ) -> Vec { - debug!("Encoding headers"); + qdebug!("Encoding headers"); let header_block = encoder.encode_header_block(conn, headers, stream_id); let hframe = HFrame::Headers { header_block: header_block.to_vec(), @@ -167,7 +166,7 @@ impl Stream for SendMessage { } impl SendStream for SendMessage { fn send_data(&mut self, conn: &mut Connection, buf: &[u8]) -> Res { - trace!("[{self}] send_body: len={}", buf.len()); + qtrace!("[{self}] send_body: len={}", buf.len()); self.state.new_data()?; @@ -201,7 +200,7 @@ impl SendStream for SendMessage { min(buf.len(), available - 9) }; - debug!("[{self}] send_request_body: available={available} to_send={to_send}"); + qdebug!("[{self}] send_request_body: available={available} to_send={to_send}"); let data_frame = HFrame::Data { len: to_send as u64, @@ -246,14 +245,14 @@ impl SendStream for SendMessage { fn send(&mut self, conn: &mut Connection) -> Res<()> { let sent = Error::map_error(self.stream.send_buffer(conn), Error::HttpInternal(5))?; - trace!("[{self}] {sent} bytes sent"); + qtrace!("[{self}] {sent} bytes sent"); if !self.stream.has_buffered_data() { if self.state.done() { Error::map_error( conn.stream_close_send(self.stream_id()), Error::HttpInternal(6), )?; - trace!("[{self}] done sending request"); + qtrace!("[{self}] done sending request"); } else { // DataWritable is just a signal for an application to try to write more data, // if writing fails it is fine. Therefore we do not need to properly check diff --git a/neqo-http3/src/server.rs b/neqo-http3/src/server.rs index 27db19e8e8..346bc856e6 100644 --- a/neqo-http3/src/server.rs +++ b/neqo-http3/src/server.rs @@ -14,8 +14,7 @@ use std::{ time::Instant, }; -use log::trace; -use neqo_common::Datagram; +use neqo_common::{qtrace, Datagram}; use neqo_crypto::{AntiReplay, Cipher, PrivateKey, PublicKey, ZeroRttChecker}; use neqo_transport::{ server::{ConnectionRef, Server, ValidateAddress}, @@ -120,13 +119,13 @@ impl Http3Server { } pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - trace!("[{self}] Process"); + qtrace!("[{self}] Process"); let out = self.server.process(dgram, now); self.process_http3(now); // If we do not that a dgram already try again after process_http3. match out { Output::Datagram(d) => { - trace!("[{self}] Send packet: {d:?}"); + qtrace!("[{self}] Send packet: {d:?}"); Output::Datagram(d) } _ => self.server.process(Option::::None, now), @@ -135,7 +134,7 @@ impl Http3Server { /// Process HTTP3 layer. fn process_http3(&mut self, now: Instant) { - trace!("[{self}] Process http3 internal"); + qtrace!("[{self}] Process http3 internal"); // `ActiveConnectionRef` `Hash` implementation doesn’t access any of the interior mutable // types. #[allow(clippy::mutable_key_type)] diff --git a/neqo-http3/src/server_events.rs b/neqo-http3/src/server_events.rs index 235aab9081..40ff04a002 100644 --- a/neqo-http3/src/server_events.rs +++ b/neqo-http3/src/server_events.rs @@ -13,8 +13,7 @@ use std::{ rc::Rc, }; -use log::debug; -use neqo_common::{Encoder, Header}; +use neqo_common::{qdebug, Encoder, Header}; use neqo_transport::{ server::ConnectionRef, AppError, Connection, DatagramTracking, StreamId, StreamType, }; @@ -115,7 +114,7 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_stop_sending(&self, app_error: AppError) -> Res<()> { - debug!( + qdebug!( "[{self}] stop sending stream_id:{} error:{app_error}", self.stream_info.stream_id() ); @@ -132,7 +131,7 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_reset_send(&self, app_error: AppError) -> Res<()> { - debug!( + qdebug!( "[{self}] reset send stream_id:{} error:{app_error}", self.stream_info.stream_id() ); @@ -149,7 +148,7 @@ impl StreamHandler { /// /// It may return `InvalidStreamId` if a stream does not exist anymore pub fn cancel_fetch(&self, app_error: AppError) -> Res<()> { - debug!("[{self}] reset error:{app_error}"); + qdebug!("[{self}] reset error:{app_error}"); self.handler.borrow_mut().cancel_fetch( self.stream_info.stream_id(), app_error, @@ -199,7 +198,7 @@ impl Http3OrWebTransportStream { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn send_data(&self, data: &[u8]) -> Res { - debug!("[{self}] Set new response"); + qdebug!("[{self}] Set new response"); self.stream_handler.send_data(data) } @@ -209,7 +208,7 @@ impl Http3OrWebTransportStream { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn stream_close_send(&self) -> Res<()> { - debug!("[{self}] Set new response"); + qdebug!("[{self}] Set new response"); self.stream_handler.stream_close_send() } } @@ -280,7 +279,7 @@ impl WebTransportRequest { /// /// It may return `InvalidStreamId` if a stream does not exist anymore. pub fn response(&self, accept: &WebTransportSessionAcceptAction) -> Res<()> { - debug!("[{self}] Set a response for a WebTransport session"); + qdebug!("[{self}] Set a response for a WebTransport session"); self.stream_handler .handler .borrow_mut() diff --git a/neqo-http3/src/stream_type_reader.rs b/neqo-http3/src/stream_type_reader.rs index 39889094b1..7aa4caed4c 100644 --- a/neqo-http3/src/stream_type_reader.rs +++ b/neqo-http3/src/stream_type_reader.rs @@ -3,8 +3,7 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -use log::trace; -use neqo_common::{Decoder, IncrementalDecoderUint, Role}; +use neqo_common::{qtrace, Decoder, IncrementalDecoderUint, Role}; use neqo_qpack::{decoder::QPACK_UNI_STREAM_TYPE_DECODER, encoder::QPACK_UNI_STREAM_TYPE_ENCODER}; use neqo_transport::{Connection, StreamId, StreamType}; @@ -137,7 +136,7 @@ impl NewStreamHeadReader { return Ok(None); }; - trace!("Decoded uint {output}"); + qtrace!("Decoded uint {output}"); match self { Self::ReadType { role, stream_id, .. @@ -161,7 +160,7 @@ impl NewStreamHeadReader { return Self::map_stream_fin(*t); } (Ok(Some(t)), false) => { - trace!("Decoded stream type {:?}", *t); + qtrace!("Decoded stream type {:?}", *t); *self = Self::Done; return final_type; } @@ -178,7 +177,7 @@ impl NewStreamHeadReader { Self::ReadId { stream_type, .. } => { let is_push = *stream_type == HTTP3_UNI_STREAM_TYPE_PUSH; *self = Self::Done; - trace!("New Stream stream push_id={output}"); + qtrace!("New Stream stream push_id={output}"); if fin { return Err(Error::HttpGeneralProtocol); } diff --git a/neqo-http3/tests/httpconn.rs b/neqo-http3/tests/httpconn.rs index 96460f10d1..e14fdc97fe 100644 --- a/neqo-http3/tests/httpconn.rs +++ b/neqo-http3/tests/httpconn.rs @@ -9,8 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use log::trace; -use neqo_common::{event::Provider, Datagram}; +use neqo_common::{event::Provider, qtrace, Datagram}; use neqo_crypto::{AuthenticationStatus, ResumptionToken}; use neqo_http3::{ Header, Http3Client, Http3ClientEvent, Http3OrWebTransportStream, Http3Parameters, Http3Server, @@ -175,7 +174,7 @@ fn simple_connect() { fn fetch() { let (mut hconn_c, mut hconn_s, dgram) = connect(); - trace!("-----client"); + qtrace!("-----client"); let req = hconn_c .fetch( now(), @@ -188,13 +187,13 @@ fn fetch() { assert_eq!(req, 0); hconn_c.stream_close_send(req).unwrap(); let out = hconn_c.process(dgram, now()); - trace!("-----server"); + qtrace!("-----server"); let out = hconn_s.process(out.dgram(), now()); mem::drop(hconn_c.process(out.dgram(), now())); process_server_events(&hconn_s); let out = hconn_s.process(None::, now()); - trace!("-----client"); + qtrace!("-----client"); mem::drop(hconn_c.process(out.dgram(), now())); let out = hconn_s.process(None::, now()); mem::drop(hconn_c.process(out.dgram(), now())); @@ -502,7 +501,7 @@ fn fetch_noresponse_will_idletimeout() { let (dgram, mut now) = connect_peers_with_network_propagation_delay(&mut hconn_c, &mut hconn_s, 10); - trace!("-----client"); + qtrace!("-----client"); let req = hconn_c .fetch( now, @@ -515,7 +514,7 @@ fn fetch_noresponse_will_idletimeout() { assert_eq!(req, 0); hconn_c.stream_close_send(req).unwrap(); let _out = hconn_c.process(dgram, now); - trace!("-----server"); + qtrace!("-----server"); let mut done = false; while !done { diff --git a/neqo-qpack/src/decoder.rs b/neqo-qpack/src/decoder.rs index cfad900493..fc7a37eab7 100644 --- a/neqo-qpack/src/decoder.rs +++ b/neqo-qpack/src/decoder.rs @@ -4,8 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use log::debug; -use neqo_common::Header; +use neqo_common::{qdebug, Header}; use neqo_transport::{Connection, StreamId}; use crate::{ @@ -41,7 +40,7 @@ impl QPackDecoder { /// If settings include invalid values. #[must_use] pub fn new(qpack_settings: &QpackSettings) -> Self { - debug!("Decoder: creating a new qpack decoder"); + qdebug!("Decoder: creating a new qpack decoder"); let mut send_buf = QpackData::default(); send_buf.encode_varint(QPACK_UNI_STREAM_TYPE_DECODER); Self { @@ -147,7 +146,7 @@ impl QPackDecoder { } fn set_capacity(&mut self, cap: u64) -> Res<()> { - debug!("[{self}] received instruction capacity cap={cap}"); + qdebug!("[{self}] received instruction capacity cap={cap}"); if cap > self.max_table_size { return Err(Error::EncoderStream); } @@ -187,7 +186,7 @@ impl QPackDecoder { let r = conn .stream_send(self.local_stream_id.unwrap(), &self.send_buf[..]) .map_err(|_| Error::DecoderStream)?; - debug!("[{self}] {r} bytes sent"); + qdebug!("[{self}] {r} bytes sent"); self.send_buf.read(r); } Ok(()) @@ -215,7 +214,7 @@ impl QPackDecoder { buf: &[u8], stream_id: StreamId, ) -> Res>> { - debug!("[{self}] decode header block"); + qdebug!("[{self}] decode header block"); let mut decoder = HeaderDecoder::new(buf); match decoder.decode_header_block(&self.table, self.max_entries, self.table.base()) { diff --git a/neqo-qpack/src/decoder_instructions.rs b/neqo-qpack/src/decoder_instructions.rs index b49b99cd87..db9cf5039d 100644 --- a/neqo-qpack/src/decoder_instructions.rs +++ b/neqo-qpack/src/decoder_instructions.rs @@ -6,7 +6,7 @@ use std::mem; -use log::{debug, trace}; +use neqo_common::{qdebug, qtrace}; use neqo_transport::StreamId; use crate::{ @@ -89,7 +89,7 @@ impl DecoderInstructionReader { /// 2) `ClosedCriticalStream` /// 3) other errors will be translated to `DecoderStream` by the caller of this function. pub fn read_instructions(&mut self, recv: &mut R) -> Res { - debug!("[{self}] read a new instruction"); + qdebug!("[{self}] read a new instruction"); loop { match &mut self.state { DecoderInstructionReaderState::ReadInstruction => { @@ -108,7 +108,7 @@ impl DecoderInstructionReader { } DecoderInstructionReaderState::ReadInt { reader } => { let val = reader.read(recv)?; - trace!("[{self}] varint read {val}"); + qtrace!("[{self}] varint read {val}"); match &mut self.instruction { DecoderInstruction::InsertCountIncrement { increment: v } => { *v = val; diff --git a/neqo-qpack/src/encoder.rs b/neqo-qpack/src/encoder.rs index 32835d51ed..7d4f63ee5f 100644 --- a/neqo-qpack/src/encoder.rs +++ b/neqo-qpack/src/encoder.rs @@ -6,8 +6,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; -use log::{debug, error, trace}; -use neqo_common::{qlog::NeqoQlog, Header}; +use neqo_common::{qdebug, qerror, qlog::NeqoQlog, qtrace, Header}; use neqo_transport::{Connection, Error as TransportError, StreamId}; use crate::{ @@ -93,7 +92,7 @@ impl QPackEncoder { return Ok(()); } - debug!( + qdebug!( "[{self}] Set max capacity to new capacity:{cap} old:{} max_table_size={}", self.table.capacity(), self.max_table_size, @@ -128,7 +127,7 @@ impl QPackEncoder { } fn read_instructions(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { - debug!("[{self}] read a new instruction"); + qdebug!("[{self}] read a new instruction"); loop { let mut recv = ReceiverConnWrapper::new(conn, stream_id); match self.instruction_reader.read_instructions(&mut recv) { @@ -202,7 +201,7 @@ impl QPackEncoder { } fn call_instruction(&mut self, instruction: DecoderInstruction, qlog: &NeqoQlog) -> Res<()> { - debug!("[{self}] call instruction {instruction:?}"); + qdebug!("[{self}] call instruction {instruction:?}"); match instruction { DecoderInstruction::InsertCountIncrement { increment } => { qlog::qpack_read_insert_count_increment_instruction( @@ -246,7 +245,7 @@ impl QPackEncoder { name: &[u8], value: &[u8], ) -> Res { - debug!("[{self}] insert {name:?} {value:?}"); + qdebug!("[{self}] insert {name:?} {value:?}"); let entry_size = name.len() + value.len() + ADDITIONAL_TABLE_ENTRY_SIZE; @@ -279,7 +278,7 @@ impl QPackEncoder { } fn change_capacity(&mut self, value: u64) { - debug!("[{self}] change capacity: {value}"); + qdebug!("[{self}] change capacity: {value}"); self.next_capacity = Some(value); } @@ -320,7 +319,7 @@ impl QPackEncoder { pub fn send_encoder_updates(&mut self, conn: &mut Connection) -> Res<()> { match self.local_stream { LocalStreamState::NoStream => { - error!("Send call but there is no stream yet"); + qerror!("Send call but there is no stream yet"); Ok(()) } LocalStreamState::Uninitialized(stream_id) => { @@ -367,7 +366,7 @@ impl QPackEncoder { h: &[Header], stream_id: StreamId, ) -> HeaderEncoder { - debug!("[{self}] encoding headers"); + qdebug!("[{self}] encoding headers"); // Try to send capacity instructions if present. // This code doesn't try to deal with errors, it just tries @@ -392,7 +391,7 @@ impl QPackEncoder { for iter in h { let name = iter.name().as_bytes().to_vec(); let value = iter.value().as_bytes().to_vec(); - trace!("encoding {name:x?} {value:x?}"); + qtrace!("encoding {name:x?} {value:x?}"); if let Some(LookupResult { index, @@ -400,7 +399,7 @@ impl QPackEncoder { value_matches, }) = self.table.lookup(&name, &value, can_block) { - trace!( + qtrace!( "[{self}] found a {} entry, value-match={value_matches}", if static_table { "static" } else { "dynamic" } ); diff --git a/neqo-qpack/src/encoder_instructions.rs b/neqo-qpack/src/encoder_instructions.rs index f4e5086975..55e13cc9e4 100644 --- a/neqo-qpack/src/encoder_instructions.rs +++ b/neqo-qpack/src/encoder_instructions.rs @@ -6,7 +6,7 @@ use std::mem; -use log::{debug, trace}; +use neqo_common::{qdebug, qtrace}; use crate::{ prefix::{ @@ -176,7 +176,7 @@ impl EncoderInstructionReader { } else { unreachable!("The above patterns match everything"); }; - debug!("[{self}] instruction decoded"); + qdebug!("[{self}] instruction decoded"); } fn decode_instruction_type(&mut self, recv: &mut T) -> Res<()> { @@ -220,7 +220,7 @@ impl EncoderInstructionReader { &mut self, recv: &mut T, ) -> Res { - debug!("[{self}] reading instructions"); + qdebug!("[{self}] reading instructions"); loop { match &mut self.state { EncoderInstructionReaderState::ReadInstruction => { @@ -229,7 +229,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadFirstInt { reader } => { let val = reader.read(recv)?; - trace!("[{self}] First varint read {val}"); + qtrace!("[{self}] First varint read {val}"); match &mut self.instruction { DecodedEncoderInstruction::Capacity { value: v, .. } | DecodedEncoderInstruction::Duplicate { index: v } => { @@ -249,7 +249,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadFirstLiteral { reader } => { let val = reader.read(recv)?; - trace!("[{self}] first literal read {val:?}"); + qtrace!("[{self}] first literal read {val:?}"); match &mut self.instruction { DecodedEncoderInstruction::InsertWithNameRefStatic { value, .. } | DecodedEncoderInstruction::InsertWithNameRefDynamic { value, .. } => { @@ -268,7 +268,7 @@ impl EncoderInstructionReader { EncoderInstructionReaderState::ReadSecondLiteral { reader } => { let val = reader.read(recv)?; - trace!("[{self}] second literal read {val:?}"); + qtrace!("[{self}] second literal read {val:?}"); match &mut self.instruction { DecodedEncoderInstruction::InsertWithNameLiteral { value, .. } => { *value = val; diff --git a/neqo-qpack/src/header_block.rs b/neqo-qpack/src/header_block.rs index df02ae5b98..3c3a1ec274 100644 --- a/neqo-qpack/src/header_block.rs +++ b/neqo-qpack/src/header_block.rs @@ -9,8 +9,7 @@ use std::{ ops::{Deref, Div}, }; -use log::trace; -use neqo_common::Header; +use neqo_common::{qtrace, Header}; use crate::{ prefix::{ @@ -61,7 +60,7 @@ impl HeaderEncoder { } pub fn encode_indexed_static(&mut self, index: u64) { - trace!("[{self}] encode static index {index}"); + qtrace!("[{self}] encode static index {index}"); self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_STATIC, index); } @@ -77,7 +76,7 @@ impl HeaderEncoder { } pub fn encode_indexed_dynamic(&mut self, index: u64) { - trace!("[{self}] encode dynamic index {index}"); + qtrace!("[{self}] encode dynamic index {index}"); if index < self.base { self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_DYNAMIC, self.base - index - 1); @@ -89,7 +88,7 @@ impl HeaderEncoder { } pub fn encode_literal_with_name_ref(&mut self, is_static: bool, index: u64, value: &[u8]) { - trace!("[{self}] encode literal with name ref - index={index}, static={is_static}, value={value:x?}"); + qtrace!("[{self}] encode literal with name ref - index={index}, static={is_static}, value={value:x?}"); if is_static { self.buf .encode_prefixed_encoded_int(HEADER_FIELD_LITERAL_NAME_REF_STATIC, index); @@ -111,7 +110,7 @@ impl HeaderEncoder { } pub fn encode_literal_with_name_literal(&mut self, name: &[u8], value: &[u8]) { - trace!("[{self}] encode literal with name literal - name={name:x?}, value={value:x?}"); + qtrace!("[{self}] encode literal with name literal - name={name:x?}, value={value:x?}"); self.buf .encode_literal(self.use_huffman, HEADER_FIELD_LITERAL_NAME_LITERAL, name); self.buf.encode_literal(self.use_huffman, NO_PREFIX, value); @@ -137,7 +136,7 @@ impl HeaderEncoder { ) } }); - trace!( + qtrace!( "[{self}] encode header block prefix max_dynamic_index_ref={:?}, base={}, enc_insert_cnt={enc_insert_cnt}, delta={delta}, prefix={prefix:?}", self.max_dynamic_index_ref, self.base @@ -209,7 +208,7 @@ impl<'a> HeaderDecoder<'a> { )?; if table.base() < self.req_insert_cnt { - trace!( + qtrace!( "[{self}] decoding is blocked, requested inserts count={}", self.req_insert_cnt ); @@ -259,7 +258,7 @@ impl<'a> HeaderDecoder<'a> { } } - trace!("[{self}] done decoding header block"); + qtrace!("[{self}] done decoding header block"); Ok(HeaderDecoderResult::Headers(h)) } @@ -284,7 +283,7 @@ impl<'a> HeaderDecoder<'a> { .checked_add(base_delta) .ok_or(Error::DecompressionFailed)? }; - trace!( + qtrace!( "[{self}] requested inserts count is {} and base is {}", self.req_insert_cnt, self.base @@ -319,7 +318,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_STATIC.len())?; - trace!("[{self}] decoder static indexed {index}"); + qtrace!("[{self}] decoder static indexed {index}"); let entry = HeaderTable::get_static(index)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -331,7 +330,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC.len())?; - trace!("[{self}] decoder dynamic indexed {index}"); + qtrace!("[{self}] decoder dynamic indexed {index}"); let entry = table.get_dynamic(index, self.base, false)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -343,7 +342,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC_POST.len())?; - trace!("[{self}] decode post-based {index}"); + qtrace!("[{self}] decode post-based {index}"); let entry = table.get_dynamic(index, self.base, true)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -352,7 +351,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_static(&mut self) -> Res
{ - trace!("[{self}] read literal with name reference to the static table"); + qtrace!("[{self}] read literal with name reference to the static table"); let index = self .buf @@ -365,7 +364,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_dynamic(&mut self, table: &HeaderTable) -> Res
{ - trace!("[{self}] read literal with name reference of the dynamic table"); + qtrace!("[{self}] read literal with name reference of the dynamic table"); let index = self .buf @@ -378,7 +377,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_ref_dynamic_post(&mut self, table: &HeaderTable) -> Res
{ - trace!("[{self}] decoder literal with post-based index"); + qtrace!("[{self}] decoder literal with post-based index"); let index = self .buf @@ -391,7 +390,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_literal(&mut self) -> Res
{ - trace!("[{self}] decode literal with name literal"); + qtrace!("[{self}] decode literal with name literal"); let name = self .buf diff --git a/neqo-qpack/src/reader.rs b/neqo-qpack/src/reader.rs index ba517c85d5..5d69eb2cdc 100644 --- a/neqo-qpack/src/reader.rs +++ b/neqo-qpack/src/reader.rs @@ -6,7 +6,7 @@ use std::{mem, str}; -use log::{debug, error}; +use neqo_common::{qdebug, qerror}; use neqo_transport::{Connection, StreamId}; use crate::{huffman::decode_huffman, prefix::Prefix, Error, Res}; @@ -207,7 +207,7 @@ impl IntReader { b = s.read_byte()?; if (self.cnt == 63) && (b > 1 || (b == 1 && ((self.value >> 63) == 1))) { - error!("Error decoding prefixed encoded int - IntegerOverflow"); + qerror!("Error decoding prefixed encoded int - IntegerOverflow"); return Err(Error::IntegerOverflow); } self.value += u64::from(b & 0x7f) << self.cnt; @@ -286,7 +286,7 @@ impl LiteralReader { /// When this object is complete. pub fn read(&mut self, s: &mut T) -> Res> { loop { - debug!("state = {:?}", self.state); + qdebug!("state = {:?}", self.state); match &mut self.state { LiteralReaderState::ReadHuffman => { let b = s.read_byte()?; diff --git a/neqo-qpack/src/table.rs b/neqo-qpack/src/table.rs index 23b43dac69..57cfab4ee3 100644 --- a/neqo-qpack/src/table.rs +++ b/neqo-qpack/src/table.rs @@ -6,7 +6,7 @@ use std::collections::VecDeque; -use log::trace; +use neqo_common::qtrace; use crate::{ static_table::{StaticTableEntry, HEADER_STATIC_TABLE}, @@ -116,7 +116,7 @@ impl HeaderTable { /// The table cannot be reduce if there are entries that are referred at the moment or their /// inserts are unacked. pub fn set_capacity(&mut self, cap: u64) -> Res<()> { - trace!("[{self}] set capacity to {cap}"); + qtrace!("[{self}] set capacity to {cap}"); if !self.evict_to(cap) { return Err(Error::ChangeCapacity); } @@ -181,7 +181,7 @@ impl HeaderTable { /// Remove a reference to a dynamic table entry. pub fn remove_ref(&mut self, index: u64) { - trace!("[{self}] remove reference to entry {index}"); + qtrace!("[{self}] remove reference to entry {index}"); self.get_dynamic_with_abs_index(index) .expect("we should have the entry") .remove_ref(); @@ -189,7 +189,7 @@ impl HeaderTable { /// Add a reference to a dynamic table entry. pub fn add_ref(&mut self, index: u64) { - trace!("[{self}] add reference to entry {index}"); + qtrace!("[{self}] add reference to entry {index}"); self.get_dynamic_with_abs_index(index) .expect("we should have the entry") .add_ref(); @@ -199,7 +199,7 @@ impl HeaderTable { /// The function returns `LookupResult`: `index`, `static_table` (if it is a static table entry) /// and `value_matches` (if the header value matches as well not only header name) pub fn lookup(&mut self, name: &[u8], value: &[u8], can_block: bool) -> Option { - trace!("[{self}] lookup name:{name:?} value {value:?} can_block={can_block}",); + qtrace!("[{self}] lookup name:{name:?} value {value:?} can_block={can_block}",); let mut name_match = None; for iter in HEADER_STATIC_TABLE { if iter.name() == name { @@ -255,7 +255,7 @@ impl HeaderTable { } pub fn evict_to_internal(&mut self, reduce: u64, only_check: bool) -> bool { - trace!( + qtrace!( "[{self}] reduce table to {reduce}, currently used:{} only_check:{only_check}", self.used, ); @@ -287,7 +287,7 @@ impl HeaderTable { /// `DynamicTableFull` if an entry cannot be added to the table because there is not enough /// space and/or other entry cannot be evicted. pub fn insert(&mut self, name: &[u8], value: &[u8]) -> Res { - trace!("[{self}] insert name={name:?} value={value:?}"); + qtrace!("[{self}] insert name={name:?} value={value:?}"); let entry = DynamicTableEntry { name: name.to_vec(), value: value.to_vec(), @@ -319,7 +319,7 @@ impl HeaderTable { name_index: u64, value: &[u8], ) -> Res { - trace!( + qtrace!( "[{self}] insert with ref to index={name_index} in {} value={value:?}", if name_static_table { "static" @@ -345,7 +345,7 @@ impl HeaderTable { /// space and/or other entry cannot be evicted. /// `HeaderLookup` if the index dos not exits in the static/dynamic table. pub fn duplicate(&mut self, index: u64) -> Res { - trace!("[{self}] duplicate entry={index}"); + qtrace!("[{self}] duplicate entry={index}"); // need to remember name and value because insert may delete the entry. let name: Vec; let value: Vec; @@ -353,7 +353,7 @@ impl HeaderTable { let entry = self.get_dynamic(index, self.base, false)?; name = entry.name().to_vec(); value = entry.value().to_vec(); - trace!("[{self}] duplicate name={name:?} value={value:?}"); + qtrace!("[{self}] duplicate name={name:?} value={value:?}"); } self.insert(&name, &value) } @@ -364,7 +364,7 @@ impl HeaderTable { /// /// `IncrementAck` if ack is greater than actual number of inserts. pub fn increment_acked(&mut self, increment: u64) -> Res<()> { - trace!("[{self}] increment acked by {increment}"); + qtrace!("[{self}] increment acked by {increment}"); self.acked_inserts_cnt += increment; if self.base < self.acked_inserts_cnt { return Err(Error::IncrementAck); diff --git a/neqo-transport/src/ackrate.rs b/neqo-transport/src/ackrate.rs index a82da04678..000cef1107 100644 --- a/neqo-transport/src/ackrate.rs +++ b/neqo-transport/src/ackrate.rs @@ -8,7 +8,7 @@ use std::{cmp::max, time::Duration}; -use log::trace; +use neqo_common::qtrace; use crate::{ connection::params::ACK_RATIO_SCALE, frame::FRAME_TYPE_ACK_FREQUENCY, packet::PacketBuilder, @@ -37,7 +37,7 @@ impl AckRate { let packets = packets.clamp(MIN_PACKETS, MAX_PACKETS) - 1; let delay = rtt * RTT_RATIO / u32::from(ratio); let delay = delay.clamp(minimum, MAX_DELAY); - trace!("AckRate inputs: {cwnd}/{mtu}/{ratio}, {rtt:?}"); + qtrace!("AckRate inputs: {cwnd}/{mtu}/{ratio}, {rtt:?}"); Self { packets, delay } } @@ -82,7 +82,7 @@ impl FlexibleAckRate { mtu: usize, rtt: Duration, ) -> Self { - trace!("FlexibleAckRate: {max_ack_delay:?} {min_ack_delay:?} {ratio}"); + qtrace!("FlexibleAckRate: {max_ack_delay:?} {min_ack_delay:?} {ratio}"); let ratio = max(ACK_RATIO_SCALE, ratio); // clamp it Self { current: AckRate { @@ -107,7 +107,7 @@ impl FlexibleAckRate { && self.current.needs_update(&self.target) && self.target.write_frame(builder, self.next_frame_seqno) { - trace!("FlexibleAckRate: write frame {:?}", self.target); + qtrace!("FlexibleAckRate: write frame {:?}", self.target); self.frame_outstanding = true; self.next_frame_seqno += 1; tokens.push(RecoveryToken::AckFrequency(self.target.clone())); @@ -126,7 +126,7 @@ impl FlexibleAckRate { fn update(&mut self, cwnd: usize, mtu: usize, rtt: Duration) { self.target = AckRate::new(self.min_ack_delay, self.ratio, cwnd, mtu, rtt); - trace!("FlexibleAckRate: {:?} -> {:?}", self.current, self.target); + qtrace!("FlexibleAckRate: {:?} -> {:?}", self.current, self.target); } fn peer_ack_delay(&self) -> Duration { diff --git a/neqo-transport/src/addr_valid.rs b/neqo-transport/src/addr_valid.rs index b5f0f836c2..d0cfbd69f7 100644 --- a/neqo-transport/src/addr_valid.rs +++ b/neqo-transport/src/addr_valid.rs @@ -11,8 +11,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{info, trace}; -use neqo_common::{Decoder, Encoder, Role}; +use neqo_common::{qinfo, qtrace, Decoder, Encoder, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, selfencrypt::SelfEncrypt, @@ -149,7 +148,7 @@ impl AddressValidation { } pub fn set_validation(&mut self, validation: ValidateAddress) { - trace!("AddressValidation {self:p}: set to {validation:?}"); + qtrace!("AddressValidation {self:p}: set to {validation:?}"); self.validation = validation; } @@ -171,7 +170,7 @@ impl AddressValidation { Some(d) => { let end = self.start_time + Duration::from_millis(u64::from(d)); if end < now { - trace!("Expired token: {end:?} vs. {now:?}"); + qtrace!("Expired token: {end:?} vs. {now:?}"); return None; } } @@ -200,19 +199,19 @@ impl AddressValidation { peer_address: SocketAddr, now: Instant, ) -> AddressValidationResult { - trace!("AddressValidation {self:p}: validate {:?}", self.validation); + qtrace!("AddressValidation {self:p}: validate {:?}", self.validation); if token.is_empty() { if self.validation == ValidateAddress::Never { - info!("AddressValidation: no token; accepting"); + qinfo!("AddressValidation: no token; accepting"); return AddressValidationResult::Pass; } - info!("AddressValidation: no token; validating"); + qinfo!("AddressValidation: no token; validating"); return AddressValidationResult::Validate; } if token.len() <= TOKEN_IDENTIFIER_RETRY.len() { // Treat bad tokens strictly. - info!("AddressValidation: too short token"); + qinfo!("AddressValidation: too short token"); return AddressValidationResult::Invalid; } let retry = Self::is_likely_retry(token); @@ -224,7 +223,7 @@ impl AddressValidation { if retry { // This is from Retry, so we should have an ODCID >= 8. if cid.len() >= 8 { - info!("AddressValidation: valid Retry token for {cid}"); + qinfo!("AddressValidation: valid Retry token for {cid}"); AddressValidationResult::ValidRetry(cid) } else { panic!("AddressValidation: Retry token with small CID {cid}"); @@ -232,10 +231,10 @@ impl AddressValidation { } else if cid.is_empty() { // An empty connection ID means NEW_TOKEN. if self.validation == ValidateAddress::Always { - info!("AddressValidation: valid NEW_TOKEN token; validating again"); + qinfo!("AddressValidation: valid NEW_TOKEN token; validating again"); AddressValidationResult::Validate } else { - info!("AddressValidation: valid NEW_TOKEN token; accepting"); + qinfo!("AddressValidation: valid NEW_TOKEN token; accepting"); AddressValidationResult::Pass } } else { @@ -246,16 +245,16 @@ impl AddressValidation { // We've either lost the keys or we've received junk. if retry { // If this looked like a Retry, treat it as being bad. - info!("AddressValidation: invalid Retry token; rejecting"); + qinfo!("AddressValidation: invalid Retry token; rejecting"); AddressValidationResult::Invalid } else if self.validation == ValidateAddress::Never { // We don't require validation, so OK. - info!("AddressValidation: invalid NEW_TOKEN token; accepting"); + qinfo!("AddressValidation: invalid NEW_TOKEN token; accepting"); AddressValidationResult::Pass } else { // This might be an invalid NEW_TOKEN token, or a valid one // for which we have since lost the keys. Check again. - info!("AddressValidation: invalid NEW_TOKEN token; validating again"); + qinfo!("AddressValidation: invalid NEW_TOKEN token; validating again"); AddressValidationResult::Validate } } @@ -324,7 +323,7 @@ impl NewTokenState { { for t in old.iter().rev().chain(pending.iter().rev()) { if t == &token { - info!("NewTokenState discarding duplicate NEW_TOKEN"); + qinfo!("NewTokenState discarding duplicate NEW_TOKEN"); return; } } diff --git a/neqo-transport/src/cc/classic_cc.rs b/neqo-transport/src/cc/classic_cc.rs index 9880c845df..6a8fbc877a 100644 --- a/neqo-transport/src/cc/classic_cc.rs +++ b/neqo-transport/src/cc/classic_cc.rs @@ -12,7 +12,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{debug, info, trace}; +use neqo_common::{qdebug, qinfo, qtrace}; use super::CongestionControl; use crate::{ @@ -192,7 +192,7 @@ impl CongestionControl for ClassicCongestionControl { let mut is_app_limited = true; let mut new_acked = 0; for pkt in acked_pkts { - trace!( + qtrace!( "packet_acked this={self:p}, pn={}, ps={}, ignored={}, lost={}, rtt_est={rtt_est:?}", pkt.pn(), pkt.len(), @@ -225,7 +225,7 @@ impl CongestionControl for ClassicCongestionControl { if is_app_limited { self.cc_algorithm.on_app_limited(); - debug!("on_packets_acked this={self:p}, limited=1, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={new_acked}", self.bytes_in_flight, self.congestion_window, self.state); + qdebug!("on_packets_acked this={self:p}, limited=1, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={new_acked}", self.bytes_in_flight, self.congestion_window, self.state); return; } @@ -235,7 +235,7 @@ impl CongestionControl for ClassicCongestionControl { let increase = min(self.ssthresh - self.congestion_window, self.acked_bytes); self.congestion_window += increase; self.acked_bytes -= increase; - debug!("[{self}] slow start += {increase}"); + qdebug!("[{self}] slow start += {increase}"); if self.congestion_window == self.ssthresh { // This doesn't look like it is necessary, but it can happen // after persistent congestion. @@ -278,7 +278,7 @@ impl CongestionControl for ClassicCongestionControl { ], now, ); - debug!("[{self}] on_packets_acked this={self:p}, limited=0, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={new_acked}", self.bytes_in_flight, self.congestion_window, self.state); + qdebug!("[{self}] on_packets_acked this={self:p}, limited=0, bytes_in_flight={}, cwnd={}, state={:?}, new_acked={new_acked}", self.bytes_in_flight, self.congestion_window, self.state); } /// Update congestion controller state based on lost packets. @@ -295,7 +295,7 @@ impl CongestionControl for ClassicCongestionControl { } for pkt in lost_packets.iter().filter(|pkt| pkt.cc_in_flight()) { - debug!( + qdebug!( "packet_lost this={self:p}, pn={}, ps={}", pkt.pn(), pkt.len() @@ -330,9 +330,11 @@ impl CongestionControl for ClassicCongestionControl { lost_packets.rev(), now, ); - debug!( + qdebug!( "on_packets_lost this={self:p}, bytes_in_flight={}, cwnd={}, state={:?}", - self.bytes_in_flight, self.congestion_window, self.state + self.bytes_in_flight, + self.congestion_window, + self.state ); congestion || persistent_congestion } @@ -354,7 +356,7 @@ impl CongestionControl for ClassicCongestionControl { &[QlogMetric::BytesInFlight(self.bytes_in_flight)], now, ); - trace!("[{self}] Ignore pkt with size {}", pkt.len()); + qtrace!("[{self}] Ignore pkt with size {}", pkt.len()); } } @@ -386,7 +388,7 @@ impl CongestionControl for ClassicCongestionControl { } self.bytes_in_flight += pkt.len(); - debug!( + qdebug!( "packet_sent this={self:p}, pn={}, ps={}", pkt.pn(), pkt.len() @@ -452,7 +454,7 @@ impl ClassicCongestionControl { fn set_state(&mut self, state: State, now: Instant) { if self.state != state { - debug!("[{self}] state -> {state:?}"); + qdebug!("[{self}] state -> {state:?}"); let old_state = self.state; self.qlog.add_event_data_with_instant( || { @@ -515,7 +517,7 @@ impl ClassicCongestionControl { .checked_duration_since(t) .expect("time is monotonic"); if elapsed > pc_period { - info!("[{self}] persistent congestion"); + qinfo!("[{self}] persistent congestion"); self.congestion_window = self.cwnd_min(); self.acked_bytes = 0; self.set_state(State::PersistentCongestion, now); @@ -561,9 +563,10 @@ impl ClassicCongestionControl { self.congestion_window = max(cwnd, self.cwnd_min()); self.acked_bytes = acked_bytes; self.ssthresh = self.congestion_window; - debug!( + qdebug!( "[{self}] Cong event -> recovery; cwnd {}, ssthresh {}", - self.congestion_window, self.ssthresh + self.congestion_window, + self.ssthresh ); qlog::metrics_updated( &self.qlog, @@ -602,8 +605,7 @@ mod tests { time::{Duration, Instant}, }; - use log::info; - use neqo_common::IpTosEcn; + use neqo_common::{qinfo, IpTosEcn}; use test_fixture::now; use super::{ClassicCongestionControl, WindowAdjustment, PERSISTENT_CONG_THRESH}; @@ -1138,7 +1140,7 @@ mod tests { (ABOVE_APP_LIMIT_PKTS - i - 1) * cc.max_datagram_size() ); // increase acked_bytes with each packet - info!( + qinfo!( "{} {}", cc.congestion_window, cwnd + i * cc.max_datagram_size() diff --git a/neqo-transport/src/cc/cubic.rs b/neqo-transport/src/cc/cubic.rs index 51c78a65fd..aeae74c253 100644 --- a/neqo-transport/src/cc/cubic.rs +++ b/neqo-transport/src/cc/cubic.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use log::trace; +use neqo_common::qtrace; use crate::cc::classic_cc::WindowAdjustment; @@ -119,7 +119,7 @@ impl Cubic { self.w_max = self.last_max_cwnd; self.k = self.calc_k(curr_cwnd_f64, max_datagram_size); } - trace!("[{self}] New epoch"); + qtrace!("[{self}] New epoch"); } } diff --git a/neqo-transport/src/cid.rs b/neqo-transport/src/cid.rs index 5a046b418e..0e3144a707 100644 --- a/neqo-transport/src/cid.rs +++ b/neqo-transport/src/cid.rs @@ -14,8 +14,7 @@ use std::{ rc::Rc, }; -use log::{debug, info}; -use neqo_common::{hex, hex_with_len, Decoder, Encoder}; +use neqo_common::{hex, hex_with_len, qdebug, qinfo, Decoder, Encoder}; use neqo_crypto::{random, randomize}; use smallvec::{smallvec, SmallVec}; @@ -393,7 +392,7 @@ impl ConnectionIdStore<[u8; 16]> { } // It's not OK if any individual piece matches though. if self.cids.iter().any(|c| c.any_part_equal(&entry)) { - info!("ConnectionIdStore found reused part in NEW_CONNECTION_ID"); + qinfo!("ConnectionIdStore found reused part in NEW_CONNECTION_ID"); return Err(Error::ProtocolViolation); } @@ -522,7 +521,7 @@ impl ConnectionIdManager { .iter() .any(|c| c.seqno == seqno && c.cid.is_empty()); if empty_cid { - debug!("Connection ID {seqno} is zero-length, not retiring"); + qdebug!("Connection ID {seqno} is zero-length, not retiring"); } else { self.connection_ids.retire(seqno); self.lost_new_connection_id.retain(|cid| cid.seqno != seqno); diff --git a/neqo-transport/src/connection/dump.rs b/neqo-transport/src/connection/dump.rs index 5c0278c192..82a5b93fd6 100644 --- a/neqo-transport/src/connection/dump.rs +++ b/neqo-transport/src/connection/dump.rs @@ -9,8 +9,7 @@ use std::fmt::Write; -use log::debug; -use neqo_common::{Decoder, IpTos}; +use neqo_common::{qdebug, Decoder, IpTos}; use crate::{ connection::Connection, @@ -46,7 +45,7 @@ pub fn dump_packet( _ = write!(&mut s, "\n {dir} {}", &x); } } - debug!( + qdebug!( "[{conn}] pn={pn} type={pt:?} {} {tos:?} len {len}{s}", path.borrow() ); diff --git a/neqo-transport/src/connection/idle.rs b/neqo-transport/src/connection/idle.rs index f47a9bc7a0..c5b570a09c 100644 --- a/neqo-transport/src/connection/idle.rs +++ b/neqo-transport/src/connection/idle.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use log::trace; +use neqo_common::qtrace; use crate::recovery::RecoveryToken; @@ -56,7 +56,7 @@ impl IdleTimeout { pub fn expiry(&self, now: Instant, pto: Duration) -> Instant { let delay = max(self.timeout, pto * 3); let t = self.start(now) + delay; - trace!("IdleTimeout::expiry@{now:?} pto={pto:?} => {t:?}"); + qtrace!("IdleTimeout::expiry@{now:?} pto={pto:?} => {t:?}"); t } diff --git a/neqo-transport/src/connection/mod.rs b/neqo-transport/src/connection/mod.rs index 3f568669cf..be4a0fb5e0 100644 --- a/neqo-transport/src/connection/mod.rs +++ b/neqo-transport/src/connection/mod.rs @@ -18,10 +18,9 @@ use std::{ time::{Duration, Instant}, }; -use log::{debug, error, info, trace, warn}; use neqo_common::{ - event::Provider as EventProvider, hex, hex_snip_middle, hrtime, qlog::NeqoQlog, Datagram, - Decoder, Encoder, Role, + event::Provider as EventProvider, hex, hex_snip_middle, hrtime, qdebug, qerror, qinfo, + qlog::NeqoQlog, qtrace, qwarn, Datagram, Decoder, Encoder, Role, }; use neqo_crypto::{ agent::CertificateInfo, Agent, AntiReplay, AuthenticationStatus, Cipher, Client, Group, @@ -506,8 +505,8 @@ impl Connection { self.tps.borrow_mut().local.set(tp, value); Ok(()) } else { - error!("Current state: {:?}", self.state()); - error!("Cannot set local tparam when not in an initial connection state"); + qerror!("Current state: {:?}", self.state()); + qerror!("Cannot set local tparam when not in an initial connection state"); Err(Error::ConnectionState) } } @@ -523,7 +522,7 @@ impl Connection { retry_cid: &ConnectionId, ) { debug_assert_eq!(self.role, Role::Server); - trace!("[{self}] Retry CIDs: odcid={odcid} remote={remote_cid} retry={retry_cid}"); + qtrace!("[{self}] Retry CIDs: odcid={odcid} remote={remote_cid} retry={retry_cid}"); // We advertise "our" choices in transport parameters. let local_tps = &mut self.tps.borrow_mut().local; local_tps.set_bytes(tparams::ORIGINAL_DESTINATION_CONNECTION_ID, odcid.to_vec()); @@ -555,7 +554,7 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> { if self.state != State::Init { - error!("[{self}] Cannot enable ciphers in state {:?}", self.state); + qerror!("[{self}] Cannot enable ciphers in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.set_ciphers(ciphers)?; @@ -567,7 +566,7 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn set_groups(&mut self, groups: &[Group]) -> Res<()> { if self.state != State::Init { - error!("[{self}] Cannot enable groups in state {:?}", self.state); + qerror!("[{self}] Cannot enable groups in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.set_groups(groups)?; @@ -579,7 +578,7 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn send_additional_key_shares(&mut self, count: usize) -> Res<()> { if self.state != State::Init { - error!("[{self}] Cannot enable groups in state {:?}", self.state); + qerror!("[{self}] Cannot enable groups in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.send_additional_key_shares(count)?; @@ -643,7 +642,7 @@ impl Connection { return; } - trace!( + qtrace!( "[{self}] Maybe create resumption token: {} {}", self.crypto.has_resumption_token(), self.new_token.has_token() @@ -711,14 +710,14 @@ impl Connection { /// When the operation fails, which is usually due to bad inputs or bad connection state. pub fn enable_resumption(&mut self, now: Instant, token: impl AsRef<[u8]>) -> Res<()> { if self.state != State::Init { - error!("[{self}] set token in state {:?}", self.state); + qerror!("[{self}] set token in state {:?}", self.state); return Err(Error::ConnectionState); } if self.role == Role::Server { return Err(Error::ConnectionState); } - info!( + qinfo!( "[{self}] resumption token {}", hex_snip_middle(token.as_ref()) ); @@ -728,25 +727,25 @@ impl Connection { dec.decode_uint::() .ok_or(Error::InvalidResumptionToken)?, )?; - trace!("[{self}] version {version:?}"); + qtrace!("[{self}] version {version:?}"); if !self.conn_params.get_versions().all().contains(&version) { return Err(Error::DisabledVersion); } let rtt = Duration::from_millis(dec.decode_varint().ok_or(Error::InvalidResumptionToken)?); - trace!("[{self}] RTT {rtt:?}"); + qtrace!("[{self}] RTT {rtt:?}"); let tp_slice = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?; - trace!("[{self}] transport parameters {}", hex(tp_slice)); + qtrace!("[{self}] transport parameters {}", hex(tp_slice)); let mut dec_tp = Decoder::from(tp_slice); let tp = TransportParameters::decode(&mut dec_tp).map_err(|_| Error::InvalidResumptionToken)?; let init_token = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?; - trace!("[{self}] Initial token {}", hex(init_token)); + qtrace!("[{self}] Initial token {}", hex(init_token)); let tok = dec.decode_remainder(); - trace!("[{self}] TLS token {}", hex(tok)); + qtrace!("[{self}] TLS token {}", hex(tok)); match self.crypto.tls { Agent::Client(ref mut c) => { @@ -781,7 +780,7 @@ impl Connection { } pub(crate) fn set_validation(&mut self, validation: &Rc>) { - trace!("[{self}] Enabling NEW_TOKEN"); + qtrace!("[{self}] Enabling NEW_TOKEN"); assert_eq!(self.role, Role::Server); self.address_validation = AddressValidationInfo::Server(Rc::downgrade(validation)); } @@ -802,7 +801,7 @@ impl Connection { }); enc.encode(extra); let records = s.send_ticket(now, enc.as_ref())?; - debug!("[{self}] send session ticket {}", hex(&enc)); + qdebug!("[{self}] send session ticket {}", hex(&enc)); self.crypto.buffer_records(records)?; } else { unreachable!(); @@ -848,7 +847,7 @@ impl Connection { /// the connection to fail. However, if no packets have been /// exchanged, it's not OK. pub fn authenticated(&mut self, status: AuthenticationStatus, now: Instant) { - debug!("[{self}] Authenticated {status:?}"); + qdebug!("[{self}] Authenticated {status:?}"); self.crypto.tls.authenticated(status); let res = self.handshake(now, self.version, PacketNumberSpace::Handshake, None); self.absorb_error(now, res); @@ -910,7 +909,7 @@ impl Connection { State::Closing { error: err, .. } | State::Draining { error: err, .. } | State::Closed(err) => { - warn!("[{self}] Closing again after error {err:?}"); + qwarn!("[{self}] Closing again after error {err:?}"); } State::Init => { // We have not even sent anything just close the connection without sending any @@ -965,12 +964,12 @@ impl Connection { if *timeout <= now { let st = State::Closed(error.clone()); self.set_state(st, now); - info!("Closing timer expired"); + qinfo!("Closing timer expired"); return; } } State::Closed(_) => { - debug!("Timer fired while closed"); + qdebug!("Timer fired while closed"); return; } _ => (), @@ -978,7 +977,7 @@ impl Connection { let pto = self.pto(); if self.idle_timeout.expired(now, pto) { - info!("[{self}] idle timeout expired"); + qinfo!("[{self}] idle timeout expired"); self.set_state( State::Closed(CloseReason::Transport(Error::IdleTimeout)), now, @@ -987,7 +986,7 @@ impl Connection { } if self.state.closing() { - trace!("[{self}] Closing, not processing other timers"); + qtrace!("[{self}] Closing, not processing other timers"); return; } @@ -1010,7 +1009,7 @@ impl Connection { .paths .process_timeout(now, pto, &mut self.stats.borrow_mut()) { - info!("[{self}] last available path failed"); + qinfo!("[{self}] last available path failed"); self.absorb_error::(now, Err(Error::NoAvailablePath)); } } @@ -1046,7 +1045,7 @@ impl Connection { /// Get the time that we next need to be called back, relative to `now`. fn next_delay(&mut self, now: Instant, paced: bool) -> Duration { - trace!("[{self}] Get callback delay {now:?}"); + qtrace!("[{self}] Get callback delay {now:?}"); // Only one timer matters when closing... if let State::Closing { timeout, .. } | State::Draining { timeout, .. } = self.state { @@ -1056,7 +1055,7 @@ impl Connection { let mut delays = SmallVec::<[_; 7]>::new(); if let Some(ack_time) = self.acks.ack_time(now) { - trace!("[{self}] Delayed ACK timer {ack_time:?}"); + qtrace!("[{self}] Delayed ACK timer {ack_time:?}"); delays.push(ack_time); } @@ -1066,36 +1065,36 @@ impl Connection { let pto = rtt.pto(self.confirmed()); let idle_time = self.idle_timeout.expiry(now, pto); - trace!("[{self}] Idle timer {idle_time:?}"); + qtrace!("[{self}] Idle timer {idle_time:?}"); delays.push(idle_time); if self.streams.need_keep_alive() { if let Some(keep_alive_time) = self.idle_timeout.next_keep_alive(now, pto) { - trace!("[{self}] Keep alive timer {keep_alive_time:?}"); + qtrace!("[{self}] Keep alive timer {keep_alive_time:?}"); delays.push(keep_alive_time); } } if let Some(lr_time) = self.loss_recovery.next_timeout(&path) { - trace!("[{self}] Loss recovery timer {lr_time:?}"); + qtrace!("[{self}] Loss recovery timer {lr_time:?}"); delays.push(lr_time); } if paced { if let Some(pace_time) = path.sender().next_paced(rtt.estimate()) { - trace!("[{self}] Pacing timer {pace_time:?}"); + qtrace!("[{self}] Pacing timer {pace_time:?}"); delays.push(pace_time); } } if let Some(path_time) = self.paths.next_timeout(pto) { - trace!("[{self}] Path probe timer {path_time:?}"); + qtrace!("[{self}] Path probe timer {path_time:?}"); delays.push(path_time); } } if let Some(key_update_time) = self.crypto.states.update_time() { - trace!("[{self}] Key update timer {key_update_time:?}"); + qtrace!("[{self}] Key update timer {key_update_time:?}"); delays.push(key_update_time); } @@ -1109,7 +1108,7 @@ impl Connection { // rather than just clamping to zero here. debug_assert!(earliest > now); let delay = earliest.saturating_duration_since(now); - debug!("[{self}] delay duration {delay:?}"); + qdebug!("[{self}] delay duration {delay:?}"); self.hrtime.update(delay / 4); delay } @@ -1120,7 +1119,7 @@ impl Connection { /// even if no incoming packets. #[must_use = "Output of the process_output function must be handled"] pub fn process_output(&mut self, now: Instant) -> Output { - trace!("[{self}] process_output {:?} {now:?}", self.state); + qtrace!("[{self}] process_output {:?} {now:?}", self.state); match (&self.state, self.role) { (State::Init, Role::Client) => { @@ -1179,7 +1178,7 @@ impl Connection { } fn handle_retry(&mut self, packet: &PublicPacket, now: Instant) -> Res<()> { - info!("[{self}] received Retry"); + qinfo!("[{self}] received Retry"); if matches!(self.address_validation, AddressValidationInfo::Retry { .. }) { self.stats.borrow_mut().pkt_dropped("Extra Retry"); return Ok(()); @@ -1210,7 +1209,7 @@ impl Connection { path.borrow_mut().set_remote_cid(packet.scid()); let retry_scid = ConnectionId::from(packet.scid()); - info!( + qinfo!( "[{self}] Valid Retry received, token={} scid={retry_scid}", hex(packet.token()) ); @@ -1232,7 +1231,7 @@ impl Connection { fn discard_keys(&mut self, space: PacketNumberSpace, now: Instant) { if self.crypto.discard(space) { - debug!("[{self}] Drop packet number space {space}"); + qdebug!("[{self}] Drop packet number space {space}"); if let Some(path) = self.paths.primary() { self.loss_recovery.discard(&path, space, now); } @@ -1260,7 +1259,7 @@ impl Connection { if first && self.is_stateless_reset(path, d) { // Failing to process a packet in a datagram might // indicate that there is a stateless reset present. - debug!("[{self}] Stateless reset: {}", hex(&d[d.len() - 16..])); + qdebug!("[{self}] Stateless reset: {}", hex(&d[d.len() - 16..])); self.state_signaling.reset(); self.set_state( State::Draining { @@ -1278,10 +1277,10 @@ impl Connection { /// Process any saved datagrams that might be available for processing. fn process_saved(&mut self, now: Instant) { while let Some(cspace) = self.saved_datagrams.available() { - debug!("[{self}] process saved for space {cspace:?}"); + qdebug!("[{self}] process saved for space {cspace:?}"); debug_assert!(self.crypto.states.rx_hp(self.version, cspace).is_some()); for saved in self.saved_datagrams.take_saved() { - trace!("[{self}] input saved @{:?}: {:?}", saved.t, saved.d); + qtrace!("[{self}] input saved @{:?}: {:?}", saved.t, saved.d); self.input(saved.d, saved.t, now); } } @@ -1314,7 +1313,7 @@ impl Connection { if let Some(version) = self.conn_params.get_versions().preferred(supported) { assert_ne!(self.version, version); - info!("[{self}] Version negotiation: trying {version:?}"); + qinfo!("[{self}] Version negotiation: trying {version:?}"); let path = self.paths.primary().ok_or(Error::NoAvailablePath)?; let local_addr = path.borrow().local_address(); let remote_addr = path.borrow().remote_address(); @@ -1344,7 +1343,7 @@ impl Connection { ); Ok(()) } else { - info!("[{self}] Version negotiation: failed with {supported:?}"); + qinfo!("[{self}] Version negotiation: failed with {supported:?}"); // This error goes straight to closed. self.set_state( State::Closed(CloseReason::Transport(Error::VersionNegotiation)), @@ -1391,7 +1390,7 @@ impl Connection { self.stats.borrow_mut().pkt_dropped("Invalid Initial"); return Ok(PreprocessResult::Next); } - info!( + qinfo!( "[{self}] Received valid Initial packet with scid {:?} dcid {:?}", packet.scid(), packet.dcid() @@ -1515,7 +1514,7 @@ impl Connection { *space_ecn_marks += d.tos().into(); self.stats.borrow_mut().ecn_rx = *space_ecn_marks; } else { - trace!("Not tracking ECN for dropped packet number space"); + qtrace!("Not tracking ECN for dropped packet number space"); } if self.state == State::WaitInitial { @@ -1559,7 +1558,7 @@ impl Connection { let mut slc = d.as_ref(); let mut dcid = None; - trace!("[{self}] {} input {}", path.borrow(), hex(&d)); + qtrace!("[{self}] {} input {}", path.borrow(), hex(&d)); let pto = path.borrow().rtt().pto(self.confirmed()); // Handle each packet in the datagram. @@ -1569,8 +1568,8 @@ impl Connection { match PublicPacket::decode(slc, self.cid_manager.decoder().as_ref()) { Ok((packet, remainder)) => (packet, remainder), Err(e) => { - info!("[{self}] Garbage packet: {e}"); - trace!("[{self}] Garbage packet contents: {}", hex(slc)); + qinfo!("[{self}] Garbage packet: {e}"); + qtrace!("[{self}] Garbage packet contents: {}", hex(slc)); self.stats.borrow_mut().pkt_dropped("Garbage packet"); break; } @@ -1581,7 +1580,7 @@ impl Connection { PreprocessResult::End => return Ok(()), } - trace!("[{self}] Received unverified packet {packet:?}"); + qtrace!("[{self}] Received unverified packet {packet:?}"); match packet.decrypt(&mut self.crypto.states, now + pto) { Ok(payload) => { @@ -1612,7 +1611,7 @@ impl Connection { let space = PacketNumberSpace::from(payload.packet_type()); if let Some(space) = self.acks.get_mut(space) { if space.is_duplicate(payload.pn()) { - debug!("Duplicate packet {space}-{}", payload.pn()); + qdebug!("Duplicate packet {space}-{}", payload.pn()); self.stats.borrow_mut().dups_rx += 1; } else { match self.process_packet(path, &payload, now) { @@ -1626,7 +1625,7 @@ impl Connection { } } } else { - debug!( + qdebug!( "[{self}] Received packet {space} for untracked space {}", payload.pn() ); @@ -1726,7 +1725,7 @@ impl Connection { { space.set_received(now, packet.pn(), ack_eliciting) } else { - debug!( + qdebug!( "[{self}] processed a {:?} packet without tracking it", packet.packet_type(), ); @@ -1784,11 +1783,11 @@ impl Connection { .make_permanent(path, None, ConnectionIdEntry::empty_remote(), now); Ok(()) } else { - trace!("[{self}] Unable to make path permanent: {}", path.borrow()); + qtrace!("[{self}] Unable to make path permanent: {}", path.borrow()); Err(Error::InvalidMigration) } } else { - trace!("[{self}] Unable to make path permanent: {}", path.borrow()); + qtrace!("[{self}] Unable to make path permanent: {}", path.borrow()); Err(Error::InvalidMigration) } } else { @@ -1814,7 +1813,7 @@ impl Connection { } fn start_handshake(&mut self, path: &PathRef, packet: &PublicPacket, now: Instant) { - trace!("[{self}] starting handshake"); + qtrace!("[{self}] starting handshake"); debug_assert_eq!(packet.packet_type(), PacketType::Initial); self.remote_initial_source_cid = Some(ConnectionId::from(packet.scid())); @@ -1825,17 +1824,17 @@ impl Connection { self.setup_handshake_path(path, now); self.zero_rtt_state = if self.crypto.enable_0rtt(self.version, self.role) == Ok(true) { - debug!("[{self}] Accepted 0-RTT"); + qdebug!("[{self}] Accepted 0-RTT"); ZeroRttState::AcceptedServer } else { - trace!("[{self}] Rejected 0-RTT"); + qtrace!("[{self}] Rejected 0-RTT"); ZeroRttState::Rejected }; // The server knows the final version if it has remote transport parameters. self.tps.borrow().remote.is_some() } else { - debug!("[{self}] Changing to use Server CID={}", packet.scid()); + qdebug!("[{self}] Changing to use Server CID={}", packet.scid()); debug_assert!(path.borrow().is_primary()); path.borrow_mut().set_remote_cid(packet.scid()); @@ -1914,7 +1913,7 @@ impl Connection { now, ); self.ensure_permanent(&path, now)?; - info!( + qinfo!( "[{self}] Migrate to {} probe {}", path.borrow(), if force { "now" } else { "after" } @@ -1933,7 +1932,7 @@ impl Connection { self.conn_params.get_preferred_address(), PreferredAddressConfig::Disabled ) { - debug!("[{self}] Preferred address is disabled"); + qdebug!("[{self}] Preferred address is disabled"); None } else { self.tps.borrow_mut().remote().get_preferred_address() @@ -1961,18 +1960,18 @@ impl Connection { // Ignore preferred address that move to loopback from non-loopback. // `migrate` doesn't enforce this rule. if !prev.ip().is_loopback() && remote.ip().is_loopback() { - warn!("[{self}] Ignoring a move to a loopback address: {remote}"); + qwarn!("[{self}] Ignoring a move to a loopback address: {remote}"); return Ok(()); } if self.migrate(None, Some(remote), false, now).is_err() { - warn!("[{self}] Ignoring bad preferred address: {remote}"); + qwarn!("[{self}] Ignoring bad preferred address: {remote}"); } } else { - warn!("[{self}] Unable to migrate to a different address family"); + qwarn!("[{self}] Unable to migrate to a different address family"); } } else { - debug!("[{self}] No preferred address to migrate to"); + qdebug!("[{self}] No preferred address to migrate to"); } Ok(()) } @@ -1995,7 +1994,7 @@ impl Connection { self.paths .handle_migration(path, d.source(), now, &mut self.stats.borrow_mut()); } else { - info!( + qinfo!( "[{self}] {} Peer migrated, but no connection ID available", path.borrow() ); @@ -2003,7 +2002,7 @@ impl Connection { } fn output(&mut self, now: Instant) -> SendOption { - trace!("[{self}] output {now:?}"); + qtrace!("[{self}] output {now:?}"); let res = match &self.state { State::Init | State::WaitInitial @@ -2027,7 +2026,7 @@ impl Connection { // a packet on a new path, we avoid sending (and the privacy risk) rather // than reuse a connection ID. let res = if path.borrow().is_temporary() { - error!("[{self}] Attempting to close with a temporary path"); + qerror!("[{self}] Attempting to close with a temporary path"); Err(Error::InternalError) } else { self.output_path(&path, now, Some(&details)) @@ -2051,10 +2050,10 @@ impl Connection { ) -> (PacketType, PacketBuilder) { let pt = PacketType::from(cspace); let mut builder = if pt == PacketType::Short { - debug!("Building Short dcid {:?}", path.remote_cid()); + qdebug!("Building Short dcid {:?}", path.remote_cid()); PacketBuilder::short(encoder, tx.key_phase(), path.remote_cid()) } else { - debug!( + qdebug!( "Building {pt:?} dcid {:?} scid {:?}", path.remote_cid(), path.local_cid(), @@ -2369,7 +2368,7 @@ impl Connection { // Determine how we are sending packets (PTO, etc..). let profile = self.loss_recovery.send_profile(&path.borrow(), now); - debug!("[{self}] output_path send_profile {profile:?}"); + qdebug!("[{self}] output_path send_profile {profile:?}"); // Frames for different epochs must go in different packets, but then these // packets can go in a single datagram @@ -2499,14 +2498,14 @@ impl Connection { } if encoder.is_empty() { - debug!("TX blocked, profile={profile:?}"); + qdebug!("TX blocked, profile={profile:?}"); Ok(SendOption::No(profile.paced())) } else { // Perform additional padding for Initial packets as necessary. let mut packets: Vec = encoder.into(); if let Some(mut initial) = initial_sent.take() { if needs_padding { - debug!( + qdebug!( "[{self}] pad Initial from {} to PLPMTU {}", packets.len(), profile.limit() @@ -2533,7 +2532,7 @@ impl Connection { let la = self .loss_recovery .largest_acknowledged_pn(PacketNumberSpace::ApplicationData); - info!("[{self}] Initiating key update"); + qinfo!("[{self}] Initiating key update"); self.crypto.states.initiate_key_update(la) } else { Err(Error::KeyUpdateBlocked) @@ -2547,7 +2546,7 @@ impl Connection { } fn client_start(&mut self, now: Instant) -> Res<()> { - debug!("[{self}] client_start"); + qdebug!("[{self}] client_start"); debug_assert_eq!(self.role, Role::Client); if let Some(path) = self.paths.primary() { qlog::client_connection_started(&self.qlog, &path, now); @@ -2561,7 +2560,7 @@ impl Connection { self.handshake(now, self.version, PacketNumberSpace::Initial, None)?; self.set_state(State::WaitInitial, now); self.zero_rtt_state = if self.crypto.enable_0rtt(self.version, self.role)? { - debug!("[{self}] Enabled 0-RTT"); + qdebug!("[{self}] Enabled 0-RTT"); ZeroRttState::Sending } else { ZeroRttState::Init @@ -2672,7 +2671,7 @@ impl Connection { .map(ConnectionId::as_cid_ref) != tp.map(ConnectionIdRef::from) { - warn!( + qwarn!( "[{self}] ISCID test failed: self cid {:?} != tp cid {:?}", self.remote_initial_source_cid, tp.map(hex), @@ -2688,7 +2687,7 @@ impl Connection { .map(ConnectionId::as_cid_ref) != tp.map(ConnectionIdRef::from) { - warn!( + qwarn!( "[{self}] ODCID test failed: self cid {:?} != tp cid {:?}", self.original_destination_cid, tp.map(hex), @@ -2706,7 +2705,7 @@ impl Connection { None }; if expected != tp.map(ConnectionIdRef::from) { - warn!( + qwarn!( "[{self}] RSCID test failed. self cid {expected:?} != tp cid {:?}", tp.map(hex), ); @@ -2724,7 +2723,7 @@ impl Connection { // `current` and `other` are the value from the peer's transport parameters. // We're checking that these match our expectations. if let Some((current, other)) = remote_tps.get_versions() { - trace!( + qtrace!( "[{self}] validate_versions: current={:x} chosen={current:x} other={other:x?}", self.version.wire_version(), ); @@ -2735,7 +2734,7 @@ impl Connection { // was provided. Ok(()) } else if self.version().wire_version() != current { - info!("[{self}] validate_versions: current version mismatch"); + qinfo!("[{self}] validate_versions: current version mismatch"); Err(Error::VersionNegotiation) } else if self .conn_params @@ -2760,12 +2759,12 @@ impl Connection { { Ok(()) } else { - info!("[{self}] validate_versions: failed"); + qinfo!("[{self}] validate_versions: failed"); Err(Error::VersionNegotiation) } } } else if self.version != Version::Version1 && !self.version.is_draft() { - info!("[{self}] validate_versions: missing extension"); + qinfo!("[{self}] validate_versions: missing extension"); Err(Error::VersionNegotiation) } else { Ok(()) @@ -2774,7 +2773,7 @@ impl Connection { fn confirm_version(&mut self, v: Version) { if self.version != v { - debug!("[{self}] Compatible upgrade {:?} ==> {v:?}", self.version); + qdebug!("[{self}] Compatible upgrade {:?} ==> {v:?}", self.version); } self.crypto.confirm_version(v); self.version = v; @@ -2806,7 +2805,7 @@ impl Connection { space: PacketNumberSpace, data: Option<&[u8]>, ) -> Res<()> { - trace!("[{self}] Handshake space={space} data={data:0x?}"); + qtrace!("[{self}] Handshake space={space} data={data:0x?}"); let was_authentication_pending = *self.crypto.tls.state() == HandshakeState::AuthenticationPending; @@ -2827,7 +2826,7 @@ impl Connection { } } _ => { - error!("Crypto state should not be new or failed after successful handshake"); + qerror!("Crypto state should not be new or failed after successful handshake"); return Err(Error::CryptoError(neqo_crypto::Error::InternalError)); } } @@ -2877,7 +2876,7 @@ impl Connection { now: Instant, ) -> Res<()> { if !frame.is_allowed(packet_type) { - info!("frame not allowed: {frame:?} {packet_type:?}"); + qinfo!("frame not allowed: {frame:?} {packet_type:?}"); return Err(Error::ProtocolViolation); } let space = PacketNumberSpace::from(packet_type); @@ -2909,7 +2908,7 @@ impl Connection { // (If we ever start using non-contiguous packet numbers, we need to check all the // packet numbers in the ACKed ranges.) if largest_acknowledged >= next_pn { - warn!("Largest ACKed {largest_acknowledged} was never sent"); + qwarn!("Largest ACKed {largest_acknowledged} was never sent"); return Err(Error::AckedUnsentPacket); } @@ -2918,7 +2917,7 @@ impl Connection { self.handle_ack(space, ranges, ecn_count, ack_delay, now); } Frame::Crypto { offset, data } => { - trace!( + qtrace!( "[{self}] Crypto frame on space={space} offset={offset}, data={:0x?}", &data ); @@ -2927,7 +2926,7 @@ impl Connection { if self.crypto.streams.data_ready(space) { let mut buf = Vec::new(); let read = self.crypto.streams.read_to_end(space, &mut buf); - debug!("Read {read:?} bytes"); + qdebug!("Read {read:?} bytes"); self.handshake(now, packet_version, space, Some(&buf))?; self.create_resumption_token(now); } else { @@ -2960,7 +2959,7 @@ impl Connection { self.paths .retire_cids(retire_prior, &mut self.connection_ids); if self.connection_ids.len() >= LOCAL_ACTIVE_CID_LIMIT { - info!("[{self}] received too many connection IDs"); + qinfo!("[{self}] received too many connection IDs"); return Err(Error::ConnectionIdLimitExceeded); } } @@ -2991,7 +2990,7 @@ impl Connection { reason_phrase, } => { self.stats.borrow_mut().frame_rx.connection_close += 1; - info!( + qinfo!( "[{self}] ConnectionClose received. Error code: {error_code:?} frame type {frame_type:x} reason {reason_phrase}" ); let (detail, frame_type) = if let CloseError::Application(_) = error_code { @@ -3058,7 +3057,7 @@ impl Connection { fn handle_lost_packets(&mut self, lost_packets: &[SentPacket]) { for lost in lost_packets { for token in lost.tokens() { - debug!("[{self}] Lost: {token:?}"); + qdebug!("[{self}] Lost: {token:?}"); match token { RecoveryToken::Ack(ack_token) => { // If we lost an ACK frame during the handshake, send another one. @@ -3107,7 +3106,7 @@ impl Connection { R: IntoIterator> + Debug, R::IntoIter: ExactSizeIterator, { - debug!("[{self}] Rx ACK space={space}, ranges={ack_ranges:?}"); + qdebug!("[{self}] Rx ACK space={space}, ranges={ack_ranges:?}"); let Some(path) = self.paths.primary() else { return; @@ -3162,7 +3161,7 @@ impl Connection { if !matches!(self.zero_rtt_state, ZeroRttState::Sending) { return; } - debug!("[{self}] 0-RTT rejected"); + qdebug!("[{self}] 0-RTT rejected"); self.resend_0rtt(now); self.streams.zero_rtt_rejected(); self.crypto.states.discard_0rtt_keys(); @@ -3170,9 +3169,9 @@ impl Connection { } fn set_connected(&mut self, now: Instant) -> Res<()> { - debug!("[{self}] TLS connection complete"); + qdebug!("[{self}] TLS connection complete"); if self.crypto.tls.info().map(SecretAgentInfo::alpn).is_none() { - warn!("[{self}] No ALPN. Closing connection"); + qwarn!("[{self}] No ALPN. Closing connection"); // 120 = no_application_protocol return Err(Error::CryptoAlert(120)); } @@ -3218,13 +3217,13 @@ impl Connection { self.state_signaling.handshake_done(); self.set_confirmed(now)?; } - info!("[{self}] Connection established"); + qinfo!("[{self}] Connection established"); Ok(()) } fn set_state(&mut self, state: State, now: Instant) { if state > self.state { - debug!("[{self}] State change from {:?} -> {state:?}", self.state); + qdebug!("[{self}] State change from {:?} -> {state:?}", self.state); self.state = state.clone(); if self.state.closed() { self.streams.clear_streams(); diff --git a/neqo-transport/src/connection/saved.rs b/neqo-transport/src/connection/saved.rs index 39d95b13f6..d5e0313e52 100644 --- a/neqo-transport/src/connection/saved.rs +++ b/neqo-transport/src/connection/saved.rs @@ -6,8 +6,7 @@ use std::{mem, time::Instant}; -use log::{debug, info}; -use neqo_common::Datagram; +use neqo_common::{qdebug, qinfo, Datagram}; use crate::crypto::CryptoSpace; @@ -42,10 +41,10 @@ impl SavedDatagrams { let store = self.store(cspace); if store.len() < MAX_SAVED_DATAGRAMS { - debug!("saving datagram of {} bytes", d.len()); + qdebug!("saving datagram of {} bytes", d.len()); store.push(SavedDatagram { d, t }); } else { - info!("not saving datagram of {} bytes", d.len()); + qinfo!("not saving datagram of {} bytes", d.len()); } } diff --git a/neqo-transport/src/connection/tests/cc.rs b/neqo-transport/src/connection/tests/cc.rs index 83087b4f93..ce84e3e5ca 100644 --- a/neqo-transport/src/connection/tests/cc.rs +++ b/neqo-transport/src/connection/tests/cc.rs @@ -6,8 +6,7 @@ use std::{mem, time::Duration}; -use log::{debug, info}; -use neqo_common::{Datagram, IpTosEcn}; +use neqo_common::{qdebug, qinfo, Datagram, IpTosEcn}; use super::{ super::Output, ack_bytes, assert_full_cwnd, connect_rtt_idle, cwnd, cwnd_avail, cwnd_packets, @@ -240,7 +239,7 @@ fn cc_cong_avoidance_recovery_period_to_cong_avoidance() { // Should be in CARP now. now += DEFAULT_RTT / 2; - info!("moving to congestion avoidance {}", cwnd(&client)); + qinfo!("moving to congestion avoidance {}", cwnd(&client)); // Now make sure that we increase congestion window according to the // accurate byte counting version of congestion avoidance. @@ -250,10 +249,10 @@ fn cc_cong_avoidance_recovery_period_to_cong_avoidance() { let (mut c_tx_dgrams, next_now) = fill_cwnd(&mut client, stream_id, now); now = next_now; for i in 0..5 { - info!("iteration {i}"); + qinfo!("iteration {i}"); let c_tx_size: usize = c_tx_dgrams.iter().map(Datagram::len).sum(); - info!( + qinfo!( "client sending {c_tx_size} bytes into cwnd of {}", cwnd(&client) ); @@ -398,7 +397,7 @@ fn ack_are_not_cc() { // The server hasn't received any of these packets yet, the server // won't ACK, but if it sends an ack-eliciting packet instead. - debug!("[{server}] Sending ack-eliciting"); + qdebug!("[{server}] Sending ack-eliciting"); let other_stream = server.stream_create(StreamType::BiDi).unwrap(); assert_eq!(other_stream, 1); server.stream_send(other_stream, b"dropped").unwrap(); @@ -412,10 +411,10 @@ fn ack_are_not_cc() { assert!(ack_eliciting_packet.is_some()); // The client can ack the server packet even if cc windows is full. - debug!("[{client}] Process ack-eliciting"); + qdebug!("[{client}] Process ack-eliciting"); let ack_pkt = client.process(ack_eliciting_packet, now).dgram(); assert!(ack_pkt.is_some()); - debug!("[{server}] Handle ACK"); + qdebug!("[{server}] Handle ACK"); let prev_ack_count = server.stats().frame_rx.ack; server.process_input(ack_pkt.unwrap(), now); assert_eq!(server.stats().frame_rx.ack, prev_ack_count + 1); diff --git a/neqo-transport/src/connection/tests/handshake.rs b/neqo-transport/src/connection/tests/handshake.rs index c44724f0b6..dcdbd9e276 100644 --- a/neqo-transport/src/connection/tests/handshake.rs +++ b/neqo-transport/src/connection/tests/handshake.rs @@ -12,8 +12,7 @@ use std::{ time::Duration, }; -use log::debug; -use neqo_common::{event::Provider, Datagram}; +use neqo_common::{event::Provider, qdebug, Datagram}; use neqo_crypto::{ constants::TLS_CHACHA20_POLY1305_SHA256, generate_ech_keys, AuthenticationStatus, }; @@ -46,19 +45,19 @@ const ECH_CONFIG_ID: u8 = 7; const ECH_PUBLIC_NAME: &str = "public.example"; fn full_handshake(pmtud: bool) { - debug!("---- client: generate CH"); + qdebug!("---- client: generate CH"); let mut client = new_client(ConnectionParameters::default().pmtud(pmtud)); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(out.as_dgram_ref().unwrap().len(), client.plpmtu()); - debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = new_server(ConnectionParameters::default().pmtud(pmtud)); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(out.as_dgram_ref().unwrap().len(), server.plpmtu()); - debug!("---- client: cert verification"); + qdebug!("---- client: cert verification"); let out = client.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); @@ -67,17 +66,17 @@ fn full_handshake(pmtud: bool) { assert!(maybe_authenticate(&mut client)); - debug!("---- client: SH..FIN -> FIN"); + qdebug!("---- client: SH..FIN -> FIN"); let out = client.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(*client.state(), State::Connected); - debug!("---- server: FIN -> ACKS"); + qdebug!("---- server: FIN -> ACKS"); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(*server.state(), State::Confirmed); - debug!("---- client: ACKS -> 0"); + qdebug!("---- client: ACKS -> 0"); let out = client.process(out.dgram(), now()); if pmtud { // PMTUD causes a PING probe to be sent here @@ -101,17 +100,17 @@ fn handshake_pmtud() { #[test] fn handshake_failed_authentication() { - debug!("---- client: generate CH"); + qdebug!("---- client: generate CH"); let mut client = default_client(); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); - debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); - debug!("---- client: cert verification"); + qdebug!("---- client: cert verification"); let out = client.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); @@ -120,14 +119,14 @@ fn handshake_failed_authentication() { let authentication_needed = |e| matches!(e, ConnectionEvent::AuthenticationNeeded); assert!(client.events().any(authentication_needed)); - debug!("---- client: Alert(certificate_revoked)"); + qdebug!("---- client: Alert(certificate_revoked)"); client.authenticated(AuthenticationStatus::CertRevoked, now()); - debug!("---- client: -> Alert(certificate_revoked)"); + qdebug!("---- client: -> Alert(certificate_revoked)"); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); - debug!("---- server: Alert(certificate_revoked)"); + qdebug!("---- server: Alert(certificate_revoked)"); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_some()); assert_error(&client, &CloseReason::Transport(Error::CryptoAlert(44))); @@ -158,42 +157,42 @@ fn no_alpn() { #[test] fn dup_server_flight1() { - debug!("---- client: generate CH"); + qdebug!("---- client: generate CH"); let mut client = default_client(); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); assert_eq!(out.as_dgram_ref().unwrap().len(), client.plpmtu()); - debug!("Output={:0x?}", out.as_dgram_ref()); + qdebug!("Output={:0x?}", out.as_dgram_ref()); - debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let out_to_rep = server.process(out.dgram(), now()); assert!(out_to_rep.as_dgram_ref().is_some()); - debug!("Output={:0x?}", out_to_rep.as_dgram_ref()); + qdebug!("Output={:0x?}", out_to_rep.as_dgram_ref()); - debug!("---- client: cert verification"); + qdebug!("---- client: cert verification"); let out = client.process(Some(out_to_rep.as_dgram_ref().cloned().unwrap()), now()); assert!(out.as_dgram_ref().is_some()); - debug!("Output={:0x?}", out.as_dgram_ref()); + qdebug!("Output={:0x?}", out.as_dgram_ref()); let out = server.process(out.dgram(), now()); assert!(out.as_dgram_ref().is_none()); assert!(maybe_authenticate(&mut client)); - debug!("---- client: SH..FIN -> FIN"); + qdebug!("---- client: SH..FIN -> FIN"); let out = client.process_output(now()); assert!(out.as_dgram_ref().is_some()); - debug!("Output={:0x?}", out.as_dgram_ref()); + qdebug!("Output={:0x?}", out.as_dgram_ref()); assert_eq!(3, client.stats().packets_rx); assert_eq!(0, client.stats().dups_rx); assert_eq!(1, client.stats().dropped_rx); - debug!("---- Dup, ignored"); + qdebug!("---- Dup, ignored"); let out = client.process(out_to_rep.dgram(), now()); assert!(out.as_dgram_ref().is_none()); - debug!("Output={:0x?}", out.as_dgram_ref()); + qdebug!("Output={:0x?}", out.as_dgram_ref()); // Four packets total received, 1 of them is a dup and one has been dropped because Initial keys // are dropped. Add 2 counts of the padding that the server adds to Initial packets. diff --git a/neqo-transport/src/connection/tests/idle.rs b/neqo-transport/src/connection/tests/idle.rs index 6fff90f5d7..5fb39255ff 100644 --- a/neqo-transport/src/connection/tests/idle.rs +++ b/neqo-transport/src/connection/tests/idle.rs @@ -9,8 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{trace, warn}; -use neqo_common::Encoder; +use neqo_common::{qtrace, qwarn, Encoder}; use test_fixture::{now, split_datagram}; use super::{ @@ -339,7 +338,7 @@ fn idle_caching() { // Now let the server Initial through, with the CRYPTO frame. let dgram = server.process_output(end).dgram(); let (initial, _) = split_datagram(&dgram.unwrap()); - warn!("client ingests initial, finally"); + qwarn!("client ingests initial, finally"); mem::drop(client.process(Some(initial), end)); maybe_authenticate(&mut client); let dgram = client.process_output(end).dgram(); @@ -360,7 +359,7 @@ fn create_stream_idle_rtt( ) -> (Instant, StreamId) { let check_idle = |endpoint: &mut Connection, now: Instant| { let delay = endpoint.process_output(now).callback(); - trace!("[{endpoint}] idle timeout {delay:?}"); + qtrace!("[{endpoint}] idle timeout {delay:?}"); if rtt < default_timeout() / 4 { assert_eq!(default_timeout(), delay); } else { @@ -641,7 +640,7 @@ fn keep_alive_large_rtt() { for endpoint in &mut [client, server] { endpoint.stream_keep_alive(stream, true).unwrap(); let delay = endpoint.process_output(now).callback(); - trace!("[{endpoint}] new delay {delay:?}"); + qtrace!("[{endpoint}] new delay {delay:?}"); assert!(delay > keep_alive_timeout()); assert!(delay > rtt); } diff --git a/neqo-transport/src/connection/tests/keys.rs b/neqo-transport/src/connection/tests/keys.rs index a4c71cfdf3..59bbc2f24c 100644 --- a/neqo-transport/src/connection/tests/keys.rs +++ b/neqo-transport/src/connection/tests/keys.rs @@ -6,8 +6,7 @@ use std::mem; -use log::debug; -use neqo_common::Datagram; +use neqo_common::{qdebug, Datagram}; use test_fixture::now; use super::{ @@ -56,18 +55,18 @@ fn overwrite_invocations(n: PacketNumber) { #[test] fn discarded_initial_keys() { - debug!("---- client: generate CH"); + qdebug!("---- client: generate CH"); let mut client = default_client(); let init_pkt_c = client.process_output(now()).dgram(); assert!(init_pkt_c.is_some()); assert_eq!(init_pkt_c.as_ref().unwrap().len(), client.plpmtu()); - debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let init_pkt_s = server.process(init_pkt_c.clone(), now()).dgram(); assert!(init_pkt_s.is_some()); - debug!("---- client: cert verification"); + qdebug!("---- client: cert verification"); let out = client.process(init_pkt_s.clone(), now()).dgram(); assert!(out.is_some()); @@ -86,7 +85,7 @@ fn discarded_initial_keys() { // The dropped packet is padding. The Initial packet has been mark dup. check_discarded(&mut server, &init_pkt_c.clone().unwrap(), false, 1, 1); - debug!("---- client: SH..FIN -> FIN"); + qdebug!("---- client: SH..FIN -> FIN"); let out = client.process_output(now()).dgram(); assert!(out.is_some()); diff --git a/neqo-transport/src/connection/tests/migration.rs b/neqo-transport/src/connection/tests/migration.rs index 8d54bc47d3..9e05c9d289 100644 --- a/neqo-transport/src/connection/tests/migration.rs +++ b/neqo-transport/src/connection/tests/migration.rs @@ -12,8 +12,7 @@ use std::{ time::{Duration, Instant}, }; -use log::debug; -use neqo_common::{Datagram, Decoder}; +use neqo_common::{qdebug, Datagram, Decoder}; use test_fixture::{ assertions::{assert_v4_path, assert_v6_path}, fixture_init, new_neqo_qlog, now, DEFAULT_ADDR, DEFAULT_ADDR_V4, @@ -103,10 +102,10 @@ fn rebind( new_path: fn(&Datagram) -> Datagram, mut now: Instant, ) -> Instant { - debug!("Rebinding"); + qdebug!("Rebinding"); let c1 = send_something(client, now); let c1_new = new_path(&c1); - debug!("Rebinding to {}", c1_new.source()); + qdebug!("Rebinding to {}", c1_new.source()); // Server will reply to modified datagram with a PATH_CHALLENGE. // Due to the amplification limit, this will not be padded to MIN_INITIAL_PACKET_SIZE. @@ -231,7 +230,7 @@ fn rebind( now += server.process_output(now).callback(); } - debug!("Rebinding done"); + qdebug!("Rebinding done"); now } diff --git a/neqo-transport/src/connection/tests/mod.rs b/neqo-transport/src/connection/tests/mod.rs index f0a8d83677..66af58fac8 100644 --- a/neqo-transport/src/connection/tests/mod.rs +++ b/neqo-transport/src/connection/tests/mod.rs @@ -14,8 +14,7 @@ use std::{ }; use enum_map::enum_map; -use log::{debug, trace}; -use neqo_common::{event::Provider, Datagram, Decoder, Role}; +use neqo_common::{event::Provider, qdebug, qtrace, Datagram, Decoder, Role}; use neqo_crypto::{random, AllowZeroRtt, AuthenticationStatus, ResumptionToken}; use test_fixture::{fixture_init, new_neqo_qlog, now, DEFAULT_ADDR}; @@ -229,7 +228,7 @@ fn handshake_with_modifier( did_ping[a.role()] = true; } input = output.and_then(modifier); - trace!("handshake: t += {:?}", rtt / 2); + qtrace!("handshake: t += {:?}", rtt / 2); now += rtt / 2; mem::swap(&mut a, &mut b); } @@ -347,7 +346,7 @@ fn connect_rtt_idle_with_modifier( // Drain events from both as well. _ = client.events().count(); _ = server.events().count(); - trace!("----- connected and idle with RTT {rtt:?}"); + qtrace!("----- connected and idle with RTT {rtt:?}"); now } @@ -371,7 +370,7 @@ fn fill_stream(c: &mut Connection, stream: StreamId) { const BLOCK_SIZE: usize = 4_096; loop { let bytes_sent = c.stream_send(stream, &[0x42; BLOCK_SIZE]).unwrap(); - trace!("fill_cwnd wrote {bytes_sent} bytes"); + qtrace!("fill_cwnd wrote {bytes_sent} bytes"); if bytes_sent < BLOCK_SIZE { break; } @@ -385,13 +384,13 @@ fn fill_stream(c: &mut Connection, stream: StreamId) { /// pacing, this looks at the congestion window to tell when to stop. /// Returns a list of datagrams and the new time. fn fill_cwnd(c: &mut Connection, stream: StreamId, mut now: Instant) -> (Vec, Instant) { - trace!("fill_cwnd starting cwnd: {}", cwnd_avail(c)); + qtrace!("fill_cwnd starting cwnd: {}", cwnd_avail(c)); fill_stream(c, stream); let mut total_dgrams = Vec::new(); loop { let pkt = c.process_output(now); - trace!( + qtrace!( "fill_cwnd cwnd remaining={}, output: {pkt:?}", cwnd_avail(c) ); @@ -409,7 +408,7 @@ fn fill_cwnd(c: &mut Connection, stream: StreamId, mut now: Instant) -> (Vec() ); @@ -465,14 +464,14 @@ where let mut srv_buf = [0; 4_096]; let in_dgrams = in_dgrams.into_iter(); - debug!("[{dest}] ack_bytes {} datagrams", in_dgrams.len()); + qdebug!("[{dest}] ack_bytes {} datagrams", in_dgrams.len()); for dgram in in_dgrams { dest.process_input(dgram, now); } loop { let (bytes_read, _fin) = dest.stream_recv(stream, &mut srv_buf).unwrap(); - trace!("[{dest}] ack_bytes read {bytes_read} bytes"); + qtrace!("[{dest}] ack_bytes read {bytes_read} bytes"); if bytes_read == 0 { break; } @@ -502,13 +501,13 @@ fn induce_persistent_congestion( ) -> Instant { // Note: wait some arbitrary time that should be longer than pto // timer. This is rather brittle. - trace!("[{client}] induce_persistent_congestion"); + qtrace!("[{client}] induce_persistent_congestion"); now += AT_LEAST_PTO; let mut pto_counts = [0; MAX_PTO_COUNTS]; assert_eq!(client.stats.borrow().pto_counts, pto_counts); - trace!("[{client}] first PTO"); + qtrace!("[{client}] first PTO"); let (c_tx_dgrams, next_now) = fill_cwnd(client, stream, now); now = next_now; assert_eq!(c_tx_dgrams.len(), 2); // Two PTO packets @@ -516,7 +515,7 @@ fn induce_persistent_congestion( pto_counts[0] = 1; assert_eq!(client.stats.borrow().pto_counts, pto_counts); - trace!("[{client}] second PTO"); + qtrace!("[{client}] second PTO"); now += AT_LEAST_PTO * 2; let (c_tx_dgrams, next_now) = fill_cwnd(client, stream, now); now = next_now; @@ -526,7 +525,7 @@ fn induce_persistent_congestion( pto_counts[1] = 1; assert_eq!(client.stats.borrow().pto_counts, pto_counts); - trace!("[{client}] third PTO"); + qtrace!("[{client}] third PTO"); now += AT_LEAST_PTO * 4; let (c_tx_dgrams, next_now) = fill_cwnd(client, stream, now); now = next_now; @@ -591,7 +590,7 @@ fn send_something_paced_with_modifier( let stream_id = sender.stream_create(StreamType::UniDi).unwrap(); assert!(sender.stream_send(stream_id, DEFAULT_STREAM_DATA).is_ok()); assert!(sender.stream_close_send(stream_id).is_ok()); - debug!("[{sender}] send_something on {stream_id}"); + qdebug!("[{sender}] send_something on {stream_id}"); let dgram = match sender.process_output(now) { Output::Callback(t) => { assert!(allow_pacing, "send_something: unexpected delay"); diff --git a/neqo-transport/src/connection/tests/recovery.rs b/neqo-transport/src/connection/tests/recovery.rs index c881eb98a1..63a2368e94 100644 --- a/neqo-transport/src/connection/tests/recovery.rs +++ b/neqo-transport/src/connection/tests/recovery.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use log::debug; +use neqo_common::qdebug; use neqo_crypto::AuthenticationStatus; use test_fixture::{ assertions::{assert_handshake, assert_initial}, @@ -166,7 +166,7 @@ fn pto_initial() { const INITIAL_PTO: Duration = Duration::from_millis(300); let mut now = now(); - debug!("---- client: generate CH"); + qdebug!("---- client: generate CH"); let mut client = default_client(); let pkt1 = client.process_output(now).dgram(); assert!(pkt1.is_some()); @@ -240,7 +240,7 @@ fn pto_handshake_complete() { now += HALF_RTT; client.authenticated(AuthenticationStatus::Ok, now); - debug!("---- client: SH..FIN -> FIN"); + qdebug!("---- client: SH..FIN -> FIN"); let pkt1 = client.process_output(now).dgram(); assert_handshake(pkt1.as_ref().unwrap()); assert_eq!(*client.state(), State::Connected); @@ -253,7 +253,7 @@ fn pto_handshake_complete() { // Wait for PTO to expire and resend a handshake packet. // Wait long enough that the 1-RTT PTO also fires. - debug!("---- client: PTO"); + qdebug!("---- client: PTO"); now += HALF_RTT * 6; let pkt2 = client.process_output(now).dgram(); assert_handshake(pkt2.as_ref().unwrap()); @@ -280,7 +280,7 @@ fn pto_handshake_complete() { // We still have only a single PTO assert_eq!(client.stats.borrow().pto_counts, pto_counts); - debug!("---- server: receive FIN and send ACK"); + qdebug!("---- server: receive FIN and send ACK"); now += HALF_RTT; // Now let the server have pkt1 and expect an immediate Handshake ACK. // The output will be a Handshake packet with ACK and 1-RTT packet with @@ -332,17 +332,17 @@ fn pto_handshake_complete() { #[test] fn pto_handshake_frames() { let mut now = now(); - debug!("---- client: generate CH"); + qdebug!("---- client: generate CH"); let mut client = default_client(); let pkt = client.process_output(now); now += Duration::from_millis(10); - debug!("---- server: CH -> SH, EE, CERT, CV, FIN"); + qdebug!("---- server: CH -> SH, EE, CERT, CV, FIN"); let mut server = default_server(); let pkt = server.process(pkt.dgram(), now); now += Duration::from_millis(10); - debug!("---- client: cert verification"); + qdebug!("---- client: cert verification"); let pkt = client.process(pkt.dgram(), now); now += Duration::from_millis(10); @@ -354,7 +354,7 @@ fn pto_handshake_frames() { let stream = client.stream_create(StreamType::UniDi).unwrap(); assert_eq!(stream, 2); assert_eq!(client.stream_send(stream, b"zero").unwrap(), 4); - debug!("---- client: SH..FIN -> FIN and 1RTT packet"); + qdebug!("---- client: SH..FIN -> FIN and 1RTT packet"); let pkt1 = client.process_output(now).dgram(); assert!(pkt1.is_some()); @@ -646,7 +646,7 @@ fn trickle(sender: &mut Connection, receiver: &mut Connection, mut count: usize, let id = sender.stream_create(StreamType::UniDi).unwrap(); let mut maybe_ack = None; while count > 0 { - debug!("trickle: remaining={count}"); + qdebug!("trickle: remaining={count}"); assert_eq!(sender.stream_send(id, &[9]).unwrap(), 1); let dgram = sender.process(maybe_ack, now).dgram(); diff --git a/neqo-transport/src/connection/tests/stream.rs b/neqo-transport/src/connection/tests/stream.rs index 56865678fc..89e1773dae 100644 --- a/neqo-transport/src/connection/tests/stream.rs +++ b/neqo-transport/src/connection/tests/stream.rs @@ -6,8 +6,7 @@ use std::{cmp::max, collections::HashMap, mem}; -use log::debug; -use neqo_common::event::Provider; +use neqo_common::{event::Provider, qdebug}; use test_fixture::now; use super::{ @@ -63,7 +62,7 @@ fn transfer() { let mut server = default_server(); connect_force_idle(&mut client, &mut server); - debug!("---- client sends"); + qdebug!("---- client sends"); // Send let client_stream_id = client.stream_create(StreamType::UniDi).unwrap(); client.stream_send(client_stream_id, &[6; 100]).unwrap(); @@ -85,12 +84,12 @@ fn transfer() { assert_eq!(datagrams.len(), 4); assert_eq!(*client.state(), State::Confirmed); - debug!("---- server receives"); + qdebug!("---- server receives"); for d in datagrams { let out = server.process(Some(d), now()); // With an RTT of zero, the server will acknowledge every packet immediately. assert!(out.as_dgram_ref().is_some()); - debug!("Output={:0x?}", out.as_dgram_ref()); + qdebug!("Output={:0x?}", out.as_dgram_ref()); } assert_eq!(*server.state(), State::Confirmed); @@ -123,7 +122,7 @@ fn sendorder_test(order_of_sendorder: &[Option]) { let mut server = default_server(); connect_force_idle(&mut client, &mut server); - debug!("---- client sends"); + qdebug!("---- client sends"); // open all streams and set the sendorders let mut ordered = Vec::new(); let mut streams = Vec::::new(); @@ -150,10 +149,10 @@ fn sendorder_test(order_of_sendorder: &[Option]) { } assert_eq!(*client.state(), State::Confirmed); - debug!("---- server receives"); + qdebug!("---- server receives"); for d in datagrams { let out = server.process(Some(d), now()); - debug!("Output={:0x?}", out.as_dgram_ref()); + qdebug!("Output={:0x?}", out.as_dgram_ref()); } assert_eq!(*server.state(), State::Confirmed); diff --git a/neqo-transport/src/connection/tests/zerortt.rs b/neqo-transport/src/connection/tests/zerortt.rs index aeb135b906..1370e3f659 100644 --- a/neqo-transport/src/connection/tests/zerortt.rs +++ b/neqo-transport/src/connection/tests/zerortt.rs @@ -6,8 +6,7 @@ use std::{cell::RefCell, rc::Rc, time::Duration}; -use log::debug; -use neqo_common::event::Provider; +use neqo_common::{event::Provider, qdebug}; use neqo_crypto::{AllowZeroRtt, AntiReplay}; use test_fixture::{assertions, now}; @@ -292,7 +291,7 @@ fn zero_rtt_loss_accepted() { assertions::assert_coalesced_0rtt(&ci.as_dgram_ref().unwrap()[..]); // Drop CI/0-RTT a number of times - debug!("Drop CI/0-RTT {i} extra times"); + qdebug!("Drop CI/0-RTT {i} extra times"); for _ in 0..i { now += client.process_output(now).callback(); ci = client.process_output(now); diff --git a/neqo-transport/src/crypto.rs b/neqo-transport/src/crypto.rs index 4fdc912e18..651317bb4b 100644 --- a/neqo-transport/src/crypto.rs +++ b/neqo-transport/src/crypto.rs @@ -14,8 +14,7 @@ use std::{ time::Instant, }; -use log::{debug, info, trace}; -use neqo_common::{hex, hex_snip_middle, Encoder, Role}; +use neqo_common::{hex, hex_snip_middle, qdebug, qinfo, qtrace, Encoder, Role}; use neqo_crypto::{ hkdf, hp::HpKey, Aead, Agent, AntiReplay, Cipher, Epoch, Error as CryptoError, HandshakeState, PrivateKey, PublicKey, Record, RecordList, ResumptionToken, SymKey, ZeroRttChecker, @@ -191,7 +190,7 @@ impl Crypto { data: Option<&[u8]>, ) -> Res<&HandshakeState> { let input = data.map(|d| { - trace!("Handshake record received {d:0x?} "); + qtrace!("Handshake record received {d:0x?} "); let epoch = match space { PacketNumberSpace::Initial => TLS_EPOCH_INITIAL, PacketNumberSpace::Handshake => TLS_EPOCH_HANDSHAKE, @@ -212,7 +211,7 @@ impl Crypto { } Err(CryptoError::EchRetry(v)) => Err(Error::EchRetry(v)), Err(e) => { - info!("Handshake failed {e:?}"); + qinfo!("Handshake failed {e:?}"); Err(self .tls .alert() @@ -266,7 +265,7 @@ impl Crypto { } fn install_handshake_keys(&mut self) -> Res { - trace!("[{self}] Attempt to install handshake keys"); + qtrace!("[{self}] Attempt to install handshake keys"); let Some(write_secret) = self.tls.write_secret(TLS_EPOCH_HANDSHAKE) else { // No keys is fine. return Ok(false); @@ -282,15 +281,15 @@ impl Crypto { .ok_or(Error::InternalError)?; self.states .set_handshake_keys(self.version, &write_secret, &read_secret, cipher)?; - debug!("[{self}] Handshake keys installed"); + qdebug!("[{self}] Handshake keys installed"); Ok(true) } fn maybe_install_application_write_key(&mut self, version: Version) -> Res<()> { - trace!("[{self}] Attempt to install application write key"); + qtrace!("[{self}] Attempt to install application write key"); if let Some(secret) = self.tls.write_secret(TLS_EPOCH_APPLICATION_DATA) { self.states.set_application_write_key(version, &secret)?; - debug!("[{self}] Application write key installed"); + qdebug!("[{self}] Application write key installed"); } Ok(()) } @@ -306,7 +305,7 @@ impl Crypto { .ok_or(Error::InternalError)?; self.states .set_application_read_key(version, &read_secret, expire_0rtt)?; - debug!("[{self}] application read keys installed"); + qdebug!("[{self}] application read keys installed"); Ok(()) } @@ -316,7 +315,7 @@ impl Crypto { if r.ct != TLS_CT_HANDSHAKE { return Err(Error::ProtocolViolation); } - trace!("[{self}] Adding CRYPTO data {r:?}"); + qtrace!("[{self}] Adding CRYPTO data {r:?}"); self.streams .send(PacketNumberSpace::from(r.epoch), &r.data)?; } @@ -334,17 +333,21 @@ impl Crypto { } pub fn acked(&mut self, token: &CryptoRecoveryToken) { - debug!( + qdebug!( "Acked crypto frame space={} offset={} length={}", - token.space, token.offset, token.length + token.space, + token.offset, + token.length ); self.streams.acked(token); } pub fn lost(&mut self, token: &CryptoRecoveryToken) { - info!( + qinfo!( "Lost crypto frame space={} offset={} length={}", - token.space, token.offset, token.length + token.space, + token.offset, + token.length ); self.streams.lost(token); } @@ -371,7 +374,7 @@ impl Crypto { ) -> Option { if let Agent::Client(ref mut c) = self.tls { c.resumption_token().as_ref().map(|t| { - trace!("TLS token {}", hex(t.as_ref())); + qtrace!("TLS token {}", hex(t.as_ref())); let mut enc = Encoder::default(); enc.encode_uint(4, version.wire_version()); enc.encode_varint(rtt); @@ -380,7 +383,7 @@ impl Crypto { }); enc.encode_vvec(new_token.unwrap_or(&[])); enc.encode(t.as_ref()); - debug!("resumption token {}", hex_snip_middle(enc.as_ref())); + qdebug!("resumption token {}", hex_snip_middle(enc.as_ref())); ResumptionToken::new(enc.into(), t.expiration_time()) }) } else { @@ -445,7 +448,7 @@ impl CryptoDxState { secret: &SymKey, cipher: Cipher, ) -> Res { - debug!("Making {direction:?} {epoch} CryptoDxState, v={version:?} cipher={cipher}",); + qdebug!("Making {direction:?} {epoch} CryptoDxState, v={version:?} cipher={cipher}",); let hplabel = String::from(version.label_prefix()) + "hp"; Ok(Self { version, @@ -466,7 +469,7 @@ impl CryptoDxState { label: &str, dcid: &[u8], ) -> Res { - trace!("new_initial {version:?} {}", ConnectionIdRef::from(dcid)); + qtrace!("new_initial {version:?} {}", ConnectionIdRef::from(dcid)); let salt = version.initial_salt(); let cipher = TLS_AES_128_GCM_SHA256; let initial_secret = hkdf::extract( @@ -572,9 +575,10 @@ impl CryptoDxState { self.used_pn = next..next; Ok(()) } else if prev.used_pn.end > self.used_pn.start { - debug!( + qdebug!( "[{self}] Found packet with too new packet number {} > {}, compared to {prev}", - self.used_pn.start, prev.used_pn.end, + self.used_pn.start, + prev.used_pn.end, ); Err(Error::PacketNumberOverlap) } else { @@ -588,7 +592,7 @@ impl CryptoDxState { /// old keys are received after a key update. That needs to be caught elsewhere. pub fn used(&mut self, pn: PacketNumber) -> Res<()> { if pn < self.min_pn { - debug!( + qdebug!( "[{self}] Found packet with too old packet number: {pn} < {}", self.min_pn ); @@ -619,7 +623,7 @@ impl CryptoDxState { pub fn compute_mask(&self, sample: &[u8]) -> Res<[u8; HpKey::SAMPLE_SIZE]> { let mask = self.hpkey.mask(sample)?; - trace!("[{self}] HP sample={} mask={}", hex(sample), hex(mask)); + qtrace!("[{self}] HP sample={} mask={}", hex(sample), hex(mask)); Ok(mask) } @@ -630,7 +634,7 @@ impl CryptoDxState { pub fn encrypt(&mut self, pn: PacketNumber, hdr: &[u8], body: &[u8]) -> Res> { debug_assert_eq!(self.direction, CryptoDxDirection::Write); - trace!( + qtrace!( "[{self}] encrypt pn={pn} hdr={} body={}", hex(hdr), hex(body) @@ -651,7 +655,7 @@ impl CryptoDxState { let mut out = vec![0; size]; let res = self.aead.encrypt(pn, hdr, body, &mut out)?; - trace!("[{self}] encrypt ct={}", hex(res)); + qtrace!("[{self}] encrypt ct={}", hex(res)); debug_assert_eq!(pn, self.next_pn()); self.used(pn)?; Ok(res.to_vec()) @@ -664,7 +668,7 @@ impl CryptoDxState { pub fn decrypt(&mut self, pn: PacketNumber, hdr: &[u8], body: &[u8]) -> Res> { debug_assert_eq!(self.direction, CryptoDxDirection::Read); - trace!( + qtrace!( "[{self}] decrypt pn={pn} hdr={} body={}", hex(hdr), hex(body) @@ -943,7 +947,7 @@ impl CryptoStates { }; for v in versions { - debug!( + qdebug!( "[{self}] Creating initial cipher state v={v:?}, role={role:?} dcid={}", hex(dcid) ); @@ -953,7 +957,7 @@ impl CryptoStates { rx: CryptoDxState::new_initial(*v, CryptoDxDirection::Read, read, dcid)?, }; if let Some(prev) = self.initials.get(v) { - info!( + qinfo!( "[{self}] Continue packet numbers for initial after retry (write is {:?})", prev.rx.used_pn, ); @@ -1002,7 +1006,7 @@ impl CryptoStates { secret: &SymKey, cipher: Cipher, ) -> Res<()> { - trace!("[{self}] install 0-RTT keys"); + qtrace!("[{self}] install 0-RTT keys"); self.zero_rtt = Some(CryptoDxState::new( version, dir, @@ -1027,7 +1031,7 @@ impl CryptoStates { } pub fn discard_0rtt_keys(&mut self) { - trace!("[{self}] discard 0-RTT keys"); + qtrace!("[{self}] discard 0-RTT keys"); assert!( self.app_read.is_none(), "Can't discard 0-RTT after setting application keys" @@ -1109,11 +1113,11 @@ impl CryptoStates { if self.maybe_update_write()? { Ok(()) } else { - debug!("[{self}] Write keys already updated"); + qdebug!("[{self}] Write keys already updated"); Err(Error::KeyUpdateBlocked) } } else { - debug!("[{self}] Waiting for ACK or blocked on read key timer"); + qdebug!("[{self}] Waiting for ACK or blocked on read key timer"); Err(Error::KeyUpdateBlocked) } } @@ -1127,7 +1131,7 @@ impl CryptoStates { let write = &self.app_write.as_ref().ok_or(Error::InternalError)?; let read = &self.app_read.as_ref().ok_or(Error::InternalError)?; if write.epoch() == read.epoch() { - debug!("[{self}] Update write keys to epoch={}", write.epoch() + 1); + qdebug!("[{self}] Update write keys to epoch={}", write.epoch() + 1); self.app_write = Some(write.next()?); Ok(true) } else { @@ -1141,7 +1145,7 @@ impl CryptoStates { pub fn auto_update(&mut self) -> Res<()> { if let Some(app_write) = self.app_write.as_ref() { if app_write.dx.should_update() { - info!("[{self}] Initiating automatic key update"); + qinfo!("[{self}] Initiating automatic key update"); if !self.maybe_update_write()? { return Err(Error::KeysExhausted); } @@ -1161,7 +1165,7 @@ impl CryptoStates { /// we want to ensure that we can continue to receive any delayed /// packets that use the old keys. So we just set a timer. pub fn key_update_received(&mut self, expiration: Instant) -> Res<()> { - trace!("[{self}] Key update received"); + qtrace!("[{self}] Key update received"); // If we received a key update, then we assume that the peer has // acknowledged a packet we sent in this epoch. It's OK to do that // because they aren't allowed to update without first having received @@ -1191,10 +1195,10 @@ impl CryptoStates { // If enough time has passed, then install new keys and clear the timer. if now >= expiry { if self.has_0rtt_read() { - trace!("[{self}] Discarding 0-RTT keys"); + qtrace!("[{self}] Discarding 0-RTT keys"); self.zero_rtt = None; } else { - trace!("[{self}] Rotating read keys"); + qtrace!("[{self}] Rotating read keys"); mem::swap(&mut self.app_read, &mut self.app_read_next); self.app_read_next = Some(self.app_read.as_ref().ok_or(Error::InternalError)?.next()?); @@ -1219,7 +1223,7 @@ impl CryptoStates { pub fn check_pn_overlap(&mut self) -> Res<()> { // We only need to do the check while we are waiting for read keys to be updated. if self.read_update_time.is_some() { - trace!("[{self}] Checking for PN overlap"); + qtrace!("[{self}] Checking for PN overlap"); let next_dx = &mut self.app_read_next.as_mut().ok_or(Error::InternalError)?.dx; next_dx.continuation(&self.app_read.as_ref().ok_or(Error::InternalError)?.dx)?; } @@ -1519,7 +1523,7 @@ impl CryptoStreams { }; for (offset, length) in written.into_iter().flatten() { cs.tx.mark_as_sent(offset, length); - debug!("CRYPTO for {space} offset={offset}, len={length}"); + qdebug!("CRYPTO for {space} offset={offset}, len={length}"); tokens.push(RecoveryToken::Crypto(CryptoRecoveryToken { space, offset, diff --git a/neqo-transport/src/ecn.rs b/neqo-transport/src/ecn.rs index a020af938e..5e56c14e21 100644 --- a/neqo-transport/src/ecn.rs +++ b/neqo-transport/src/ecn.rs @@ -7,8 +7,7 @@ use std::ops::{AddAssign, Deref, DerefMut, Sub}; use enum_map::{Enum, EnumMap}; -use log::{debug, info, warn}; -use neqo_common::IpTosEcn; +use neqo_common::{qdebug, qinfo, qwarn, IpTosEcn}; use crate::{ packet::{PacketNumber, PacketType}, @@ -188,9 +187,9 @@ impl EcnInfo { pub fn on_packet_sent(&mut self, stats: &mut Stats) { if let EcnValidationState::Testing { probes_sent, .. } = &mut self.state { *probes_sent += 1; - debug!("ECN probing: sent {probes_sent} probes"); + qdebug!("ECN probing: sent {probes_sent} probes"); if *probes_sent == ECN_TEST_COUNT { - debug!("ECN probing concluded with {probes_sent} probes sent"); + qdebug!("ECN probing concluded with {probes_sent} probes sent"); self.state.set(EcnValidationState::Unknown, stats); } } @@ -231,7 +230,9 @@ impl EcnInfo { // If we have lost all initial probes a bunch of times, we can conclude that the path // is not ECN capable and likely drops all ECN marked packets. if probes_sent == probes_lost && *probes_lost == ECN_TEST_COUNT_INITIAL_PHASE { - debug!("ECN validation failed, all {probes_lost} initial marked packets were lost"); + qdebug!( + "ECN validation failed, all {probes_lost} initial marked packets were lost" + ); self.disable_ecn(stats, EcnValidationError::BlackHole); } } @@ -274,7 +275,7 @@ impl EcnInfo { // > either the ECT(0) or ECT(1) codepoint set, ECN validation fails if the // > corresponding ECN counts are not present in the ACK frame. let Some(ack_ecn) = ack_ecn else { - warn!("ECN validation failed, no ECN counts in ACK frame"); + qwarn!("ECN validation failed, no ECN counts in ACK frame"); self.disable_ecn(stats, EcnValidationError::Bleaching); return; }; @@ -291,22 +292,22 @@ impl EcnInfo { .try_into() .unwrap(); if newly_acked_sent_with_ect0 == 0 { - warn!("ECN validation failed, no ECT(0) packets were newly acked"); + qwarn!("ECN validation failed, no ECT(0) packets were newly acked"); self.disable_ecn(stats, EcnValidationError::Bleaching); return; } let ecn_diff = ack_ecn - self.baseline; let sum_inc = ecn_diff[IpTosEcn::Ect0] + ecn_diff[IpTosEcn::Ce]; if sum_inc < newly_acked_sent_with_ect0 { - warn!( + qwarn!( "ECN validation failed, ACK counted {sum_inc} new marks, but {newly_acked_sent_with_ect0} of newly acked packets were sent with ECT(0)" ); self.disable_ecn(stats, EcnValidationError::Bleaching); } else if ecn_diff[IpTosEcn::Ect1] > 0 { - warn!("ECN validation failed, ACK counted ECT(1) marks that were never sent"); + qwarn!("ECN validation failed, ACK counted ECT(1) marks that were never sent"); self.disable_ecn(stats, EcnValidationError::ReceivedUnsentECT1); } else if self.state != EcnValidationState::Capable { - info!("ECN validation succeeded, path is capable"); + qinfo!("ECN validation succeeded, path is capable"); self.state.set(EcnValidationState::Capable, stats); } self.baseline = ack_ecn; diff --git a/neqo-transport/src/fc.rs b/neqo-transport/src/fc.rs index 43a8f23fd1..5a753719df 100644 --- a/neqo-transport/src/fc.rs +++ b/neqo-transport/src/fc.rs @@ -12,8 +12,7 @@ use std::{ ops::{Deref, DerefMut, Index, IndexMut}, }; -use log::trace; -use neqo_common::Role; +use neqo_common::{qtrace, Role}; use crate::{ frame::{ @@ -326,7 +325,7 @@ impl ReceiverFlowControl<()> { pub fn consume(&mut self, count: u64) -> Res<()> { if self.consumed + count > self.max_allowed { - trace!( + qtrace!( "Session RX window exceeded: consumed:{} new:{count} limit:{}", self.consumed, self.max_allowed @@ -383,7 +382,7 @@ impl ReceiverFlowControl { } if consumed > self.max_allowed { - trace!("Stream RX window exceeded: {consumed}"); + qtrace!("Stream RX window exceeded: {consumed}"); return Err(Error::FlowControlError); } let new_consumed = consumed - self.consumed; diff --git a/neqo-transport/src/frame.rs b/neqo-transport/src/frame.rs index 933ef25cc4..9559723156 100644 --- a/neqo-transport/src/frame.rs +++ b/neqo-transport/src/frame.rs @@ -8,8 +8,7 @@ use std::ops::RangeInclusive; -use log::trace; -use neqo_common::{Decoder, Encoder}; +use neqo_common::{qtrace, Decoder, Encoder}; use crate::{ cid::MAX_CONNECTION_ID_LEN, @@ -528,10 +527,10 @@ impl<'a> Frame<'a> { }; let fill = (t & STREAM_FRAME_BIT_LEN) == 0; let data = if fill { - trace!("STREAM frame, extends to the end of the packet"); + qtrace!("STREAM frame, extends to the end of the packet"); dec.decode_remainder() } else { - trace!("STREAM frame, with length"); + qtrace!("STREAM frame, with length"); d(dec.decode_vvec())? }; if o + u64::try_from(data.len())? > ((1 << 62) - 1) { @@ -645,10 +644,10 @@ impl<'a> Frame<'a> { FRAME_TYPE_DATAGRAM | FRAME_TYPE_DATAGRAM_WITH_LEN => { let fill = (t & DATAGRAM_FRAME_BIT_LEN) == 0; let data = if fill { - trace!("DATAGRAM frame, extends to the end of the packet"); + qtrace!("DATAGRAM frame, extends to the end of the packet"); dec.decode_remainder() } else { - trace!("DATAGRAM frame, with length"); + qtrace!("DATAGRAM frame, with length"); d(dec.decode_vvec())? }; Ok(Self::Datagram { data, fill }) diff --git a/neqo-transport/src/lib.rs b/neqo-transport/src/lib.rs index 9950d6dc52..551c6ea33e 100644 --- a/neqo-transport/src/lib.rs +++ b/neqo-transport/src/lib.rs @@ -6,7 +6,7 @@ #![allow(clippy::module_name_repetitions)] // This lint doesn't work here. -use log::warn; +use neqo_common::qwarn; use neqo_crypto::Error as CryptoError; mod ackrate; @@ -179,7 +179,7 @@ impl Error { impl From for Error { fn from(err: CryptoError) -> Self { - warn!("Crypto operation failed {err:?}"); + qwarn!("Crypto operation failed {err:?}"); match err { CryptoError::EchRetry(config) => Self::EchRetry(config), _ => Self::CryptoError(err), diff --git a/neqo-transport/src/pace.rs b/neqo-transport/src/pace.rs index c0e6a6a20e..3670fe1d6f 100644 --- a/neqo-transport/src/pace.rs +++ b/neqo-transport/src/pace.rs @@ -12,7 +12,7 @@ use std::{ time::{Duration, Instant}, }; -use log::trace; +use neqo_common::qtrace; use crate::rtt::GRANULARITY; @@ -76,7 +76,7 @@ impl Pacer { /// the current time is). pub fn next(&self, rtt: Duration, cwnd: usize) -> Instant { if self.c >= self.p { - trace!("[{self}] next {cwnd}/{rtt:?} no wait = {:?}", self.t); + qtrace!("[{self}] next {cwnd}/{rtt:?} no wait = {:?}", self.t); return self.t; } @@ -89,12 +89,12 @@ impl Pacer { // If the increment is below the timer granularity, send immediately. if w < GRANULARITY { - trace!("[{self}] next {cwnd}/{rtt:?} below granularity ({w:?})",); + qtrace!("[{self}] next {cwnd}/{rtt:?} below granularity ({w:?})",); return self.t; } let nxt = self.t + w; - trace!("[{self}] next {cwnd}/{rtt:?} wait {w:?} = {nxt:?}"); + qtrace!("[{self}] next {cwnd}/{rtt:?} wait {w:?} = {nxt:?}"); nxt } @@ -108,7 +108,7 @@ impl Pacer { return; } - trace!("[{self}] spend {count} over {cwnd}, {rtt:?}"); + qtrace!("[{self}] spend {count} over {cwnd}, {rtt:?}"); // Increase the capacity by: // `(now - self.t) * PACER_SPEEDUP * cwnd / rtt` // That is, the elapsed fraction of the RTT times rate that data is added. diff --git a/neqo-transport/src/packet/mod.rs b/neqo-transport/src/packet/mod.rs index a006d66649..448a7ec50a 100644 --- a/neqo-transport/src/packet/mod.rs +++ b/neqo-transport/src/packet/mod.rs @@ -12,8 +12,7 @@ use std::{ time::Instant, }; -use log::{trace, warn}; -use neqo_common::{hex, hex_with_len, Decoder, Encoder}; +use neqo_common::{hex, hex_with_len, qtrace, qwarn, Decoder, Encoder}; use neqo_crypto::random; use crate::{ @@ -398,7 +397,7 @@ impl PacketBuilder { /// This will return an error if the packet is too large. pub fn build(mut self, crypto: &mut CryptoDxState) -> Res { if self.len() > self.limit { - warn!("Packet contents are more than the limit"); + qwarn!("Packet contents are more than the limit"); debug_assert!(false); return Err(Error::InternalError); } @@ -410,7 +409,7 @@ impl PacketBuilder { let hdr = &self.encoder.as_ref()[self.header.clone()]; let body = &self.encoder.as_ref()[self.header.end..]; - trace!( + qtrace!( "Packet build pn={} hdr={} body={}", self.pn, hex(hdr), @@ -435,7 +434,7 @@ impl PacketBuilder { // Finally, cut off the plaintext and add back the ciphertext. self.encoder.truncate(self.header.end); self.encoder.encode(&ciphertext); - trace!("Packet built {}", hex(&self.encoder)); + qtrace!("Packet built {}", hex(&self.encoder)); Ok(self.encoder) } @@ -799,7 +798,7 @@ impl<'a> PublicPacket<'a> { .data .get(sample_offset..(sample_offset + SAMPLE_SIZE)) .map_or(Err(Error::NoMoreData), |sample| { - trace!("unmask hdr={}", hex(&self.data[..sample_offset])); + qtrace!("unmask hdr={}", hex(&self.data[..sample_offset])); crypto.compute_mask(sample) })?; @@ -828,7 +827,7 @@ impl<'a> PublicPacket<'a> { hdrbytes.truncate(self.header_len + pn_len); pn_encoded >>= 8 * (MAX_PACKET_NUMBER_LEN - pn_len); - trace!("unmasked hdr={}", hex(&hdrbytes)); + qtrace!("unmasked hdr={}", hex(&hdrbytes)); let key_phase = self.packet_type == PacketType::Short && (first_byte & PACKET_BIT_KEY_PHASE) == PACKET_BIT_KEY_PHASE; @@ -857,7 +856,7 @@ impl<'a> PublicPacket<'a> { // fail is if the cryptographic module is bad or the packet is // too small (which is public information). let (key_phase, pn, header, body) = self.decrypt_header(rx)?; - trace!("[{rx}] decoded header: {header:?}"); + qtrace!("[{rx}] decoded header: {header:?}"); let Some(rx) = crypto.rx(version, cspace, key_phase) else { return Err(Error::DecryptError); }; @@ -878,7 +877,7 @@ impl<'a> PublicPacket<'a> { } else if crypto.rx_pending(cspace) { Err(Error::KeysPending(cspace)) } else { - trace!("keys for {cspace:?} already discarded"); + qtrace!("keys for {cspace:?} already discarded"); Err(Error::KeysDiscarded(cspace)) } } diff --git a/neqo-transport/src/packet/retry.rs b/neqo-transport/src/packet/retry.rs index 53b04dbc50..741b28c7f5 100644 --- a/neqo-transport/src/packet/retry.rs +++ b/neqo-transport/src/packet/retry.rs @@ -6,7 +6,7 @@ use std::cell::RefCell; -use log::error; +use neqo_common::qerror; use neqo_crypto::{hkdf, Aead, TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}; use crate::{version::Version, Error, Res}; @@ -43,7 +43,7 @@ where } .try_with(|aead| f(&aead.borrow())) .map_err(|e| { - error!("Unable to access Retry AEAD: {e:?}"); + qerror!("Unable to access Retry AEAD: {e:?}"); Error::InternalError })? } diff --git a/neqo-transport/src/path.rs b/neqo-transport/src/path.rs index cf5486f472..0e6f2b82aa 100644 --- a/neqo-transport/src/path.rs +++ b/neqo-transport/src/path.rs @@ -15,8 +15,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{debug, info, trace}; -use neqo_common::{hex, qlog::NeqoQlog, Datagram, Encoder, IpTos, IpTosEcn}; +use neqo_common::{hex, qdebug, qinfo, qlog::NeqoQlog, qtrace, Datagram, Encoder, IpTos, IpTosEcn}; use neqo_crypto::random; use crate::{ @@ -114,7 +113,7 @@ impl Paths { if let Some(cid) = &retired.borrow().remote_cid { let seqno = cid.sequence_number(); if cid.connection_id().is_empty() { - debug!("Connection ID {seqno} is zero-length, not retiring"); + qdebug!("Connection ID {seqno} is zero-length, not retiring"); } else { to_retire.push(seqno); } @@ -143,7 +142,7 @@ impl Paths { .as_ref() .is_some_and(|target| Rc::ptr_eq(target, &removed)) { - info!( + qinfo!( "[{}] The migration target path had to be removed", path.borrow() ); @@ -152,7 +151,7 @@ impl Paths { debug_assert_eq!(Rc::strong_count(&removed), 1); } - debug!("[{}] Make permanent", path.borrow()); + qdebug!("[{}] Make permanent", path.borrow()); path.borrow_mut().make_permanent(local_cid, remote_cid); self.paths.push(Rc::clone(path)); if self.primary.is_none() { @@ -165,7 +164,7 @@ impl Paths { /// to a migration from a peer, in which case the old path needs to be probed. #[must_use] fn select_primary(&mut self, path: &PathRef, now: Instant) -> Option { - debug!("[{}] set as primary path", path.borrow()); + qdebug!("[{}] set as primary path", path.borrow()); let old_path = self.primary.replace(Rc::clone(path)).inspect(|old| { old.borrow_mut().set_primary(false, now); }); @@ -224,7 +223,7 @@ impl Paths { if p.borrow_mut().process_timeout(now, pto, stats) { true } else { - debug!("[{}] Retiring path", p.borrow()); + qdebug!("[{}] Retiring path", p.borrow()); if p.borrow().is_primary() { primary_failed = true; } @@ -245,7 +244,7 @@ impl Paths { { // Need a clone as `fallback` is borrowed from `self`. let path = Rc::clone(fallback); - info!("[{}] Failing over after primary path failed", path.borrow()); + qinfo!("[{}] Failing over after primary path failed", path.borrow()); mem::drop(self.select_primary(&path, now)); true } else { @@ -364,7 +363,7 @@ impl Paths { .as_ref() .is_some_and(|target| Rc::ptr_eq(target, p)) { - info!( + qinfo!( "[{path}] NEW_CONNECTION_ID with Retire Prior To forced migration to fail" ); *migration_target = None; @@ -595,7 +594,7 @@ impl Path { /// Set whether this path is primary. pub(crate) fn set_primary(&mut self, primary: bool, now: Instant) { - trace!("[{self}] Make primary {primary}"); + qtrace!("[{self}] Make primary {primary}"); debug_assert!(self.remote_cid.is_some()); self.primary = primary; if !primary { @@ -606,7 +605,7 @@ impl Path { /// Set the current path as valid. This updates the time that the path was /// last validated and cancels any path validation. pub fn set_valid(&mut self, now: Instant) { - debug!("[{self}] Path validated {now:?}"); + qdebug!("[{self}] Path validated {now:?}"); self.state = ProbeState::Valid; self.validated = Some(now); } @@ -700,7 +699,7 @@ impl Path { let need_full_probe = !*mtu; self.set_valid(now); if need_full_probe { - debug!("[{self}] Sub-MTU probe successful, reset probe count"); + qdebug!("[{self}] Sub-MTU probe successful, reset probe count"); self.probe(stats); } true @@ -729,16 +728,16 @@ impl Path { self.state = if probe_count >= MAX_PATH_PROBES { if self.ecn_info.ecn_mark() == IpTosEcn::Ect0 { // The path validation failure may be due to ECN blackholing, try again without ECN. - info!("[{self}] Possible ECN blackhole, disabling ECN and re-probing path"); + qinfo!("[{self}] Possible ECN blackhole, disabling ECN and re-probing path"); self.ecn_info .disable_ecn(stats, crate::ecn::EcnValidationError::BlackHole); ProbeState::ProbeNeeded { probe_count: 0 } } else { - info!("[{self}] Probing failed"); + qinfo!("[{self}] Probing failed"); ProbeState::Failed } } else { - debug!("[{self}] Initiating probe"); + qdebug!("[{self}] Initiating probe"); ProbeState::ProbeNeeded { probe_count } }; } @@ -760,7 +759,7 @@ impl Path { } // Send PATH_RESPONSE. let resp_sent = if let Some(challenge) = self.challenge.take() { - trace!("[{self}] Responding to path challenge {}", hex(challenge)); + qtrace!("[{self}] Responding to path challenge {}", hex(challenge)); builder.encode_varint(FRAME_TYPE_PATH_RESPONSE); builder.encode(&challenge[..]); @@ -777,7 +776,7 @@ impl Path { // Send PATH_CHALLENGE. if let ProbeState::ProbeNeeded { probe_count } = self.state { - trace!("[{self}] Initiating path challenge {probe_count}"); + qtrace!("[{self}] Initiating path challenge {probe_count}"); let data = random::<8>(); builder.encode_varint(FRAME_TYPE_PATH_CHALLENGE); builder.encode(&data); @@ -928,7 +927,7 @@ impl Path { // that there is some RTT information, which is better than nothing. // Two cases: 1. at the client when handling a Retry and // 2. at the server when disposing the Initial packet number space. - info!( + qinfo!( "[{self}] discarding a packet without an RTT estimate; guessing RTT={:?}", now - sent.time_sent() ); diff --git a/neqo-transport/src/pmtud.rs b/neqo-transport/src/pmtud.rs index f2d8dfef7e..72f626d98b 100644 --- a/neqo-transport/src/pmtud.rs +++ b/neqo-transport/src/pmtud.rs @@ -10,7 +10,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{debug, info}; +use neqo_common::{qdebug, qinfo}; use static_assertions::const_assert; use crate::{frame::FRAME_TYPE_PING, packet::PacketBuilder, recovery::SentPacket, Stats}; @@ -89,7 +89,7 @@ impl Pmtud { /// Checks whether the PMTUD raise timer should be fired, and does so if needed. pub fn maybe_fire_raise_timer(&mut self, now: Instant) { if self.probe_state == Probe::NotNeeded && self.raise_timer.is_some_and(|t| now >= t) { - debug!("PMTUD raise timer fired"); + qdebug!("PMTUD raise timer fired"); self.raise_timer = None; self.start(); } @@ -129,9 +129,10 @@ impl Pmtud { stats.pmtud_tx += 1; self.probe_count += 1; self.probe_state = Probe::Sent; - debug!( + qdebug!( "Sending PMTUD probe of size {}, count {}", - self.search_table[self.probe_index], self.probe_count + self.search_table[self.probe_index], + self.probe_count ); } @@ -185,7 +186,7 @@ impl Pmtud { // total number of successful probes. stats.pmtud_ack += acked; self.mtu = self.search_table[self.probe_index]; - debug!("PMTUD probe of size {} succeeded", self.mtu); + qdebug!("PMTUD probe of size {} succeeded", self.mtu); self.start(); } @@ -197,7 +198,7 @@ impl Pmtud { self.probe_count = 0; // Reset the count self.loss_counts.fill(0); // Reset the loss counts self.raise_timer = Some(now + PMTU_RAISE_TIMER); - info!( + qinfo!( "PMTUD stopped, PLPMTU is now {}, raise timer {:?}", self.mtu, self.raise_timer.unwrap() @@ -269,7 +270,7 @@ impl Pmtud { }; let last_ok = first_failed - 1; - debug!( + qdebug!( "Packet of size > {} lost >= {MAX_PROBES} times", self.search_table[last_ok] ); @@ -295,7 +296,7 @@ impl Pmtud { self.loss_counts.fill(0); self.raise_timer = None; stats.pmtud_change += 1; - debug!("PMTUD restarted, PLPMTU is now {}", self.mtu); + qdebug!("PMTUD restarted, PLPMTU is now {}", self.mtu); self.start(); } @@ -305,7 +306,7 @@ impl Pmtud { self.probe_state = Probe::Needed; // We need to send a probe self.probe_count = 0; // For the first time self.probe_index += 1; // At this size - debug!( + qdebug!( "PMTUD started with probe size {}", self.search_table[self.probe_index], ); @@ -331,8 +332,7 @@ mod tests { time::Instant, }; - use log::debug; - use neqo_common::{Encoder, IpTosEcn}; + use neqo_common::{qdebug, Encoder, IpTosEcn}; use test_fixture::{fixture_init, now}; use crate::{ @@ -457,7 +457,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - debug!("Reducing MTU to {smaller_mtu}"); + qdebug!("Reducing MTU to {smaller_mtu}"); // Drop packets > smaller_mtu until we need a probe again. while !pmtud.needs_probe() { let pn = prot.next_pn(); @@ -510,7 +510,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - debug!("Increasing MTU to {larger_mtu}"); + qdebug!("Increasing MTU to {larger_mtu}"); let now = now + PMTU_RAISE_TIMER; pmtud.maybe_fire_raise_timer(now); while pmtud.needs_probe() { diff --git a/neqo-transport/src/qlog.rs b/neqo-transport/src/qlog.rs index ffd266fe6d..07a7db1846 100644 --- a/neqo-transport/src/qlog.rs +++ b/neqo-transport/src/qlog.rs @@ -11,8 +11,7 @@ use std::{ time::{Duration, Instant}, }; -use log::info; -use neqo_common::{hex, qlog::NeqoQlog, Decoder, IpTosEcn}; +use neqo_common::{hex, qinfo, qlog::NeqoQlog, Decoder, IpTosEcn}; use qlog::events::{ connectivity::{ConnectionStarted, ConnectionState, ConnectionStateUpdated}, quic::{ @@ -232,7 +231,7 @@ pub fn packet_sent( if let Ok(f) = Frame::decode(&mut d) { frames.push(QuicFrame::from(f)); } else { - info!("qlog: invalid frame"); + qinfo!("qlog: invalid frame"); break; } } @@ -326,7 +325,7 @@ pub fn packet_received( if let Ok(f) = Frame::decode(&mut d) { frames.push(QuicFrame::from(f)); } else { - info!("qlog: invalid frame"); + qinfo!("qlog: invalid frame"); break; } } diff --git a/neqo-transport/src/recovery/mod.rs b/neqo-transport/src/recovery/mod.rs index 64e4325cce..ef53df35c5 100644 --- a/neqo-transport/src/recovery/mod.rs +++ b/neqo-transport/src/recovery/mod.rs @@ -20,8 +20,7 @@ use std::{ }; use enum_map::{enum_map, EnumMap}; -use log::{debug, info, trace, warn}; -use neqo_common::qlog::NeqoQlog; +use neqo_common::{qdebug, qinfo, qlog::NeqoQlog, qtrace, qwarn}; pub use sent::SentPacket; use sent::SentPackets; pub use token::{RecoveryToken, StreamRecoveryToken}; @@ -183,7 +182,7 @@ impl LossRecoverySpace { .iter_mut() .filter_map(|sent| { if sent.pto() { - trace!("PTO: marking packet {} lost ", sent.pn()); + qtrace!("PTO: marking packet {} lost ", sent.pn()); Some(&*sent) } else { None @@ -251,7 +250,7 @@ impl LossRecoverySpace { debug_assert!(self.in_flight_outstanding >= count); self.in_flight_outstanding -= count; if self.in_flight_outstanding == 0 { - trace!("remove_packet outstanding == 0 for space {}", self.space); + qtrace!("remove_packet outstanding == 0 for space {}", self.space); } } @@ -323,7 +322,7 @@ impl LossRecoverySpace { // Housekeeping. self.remove_old_lost(now, cleanup_delay); - trace!( + qtrace!( "detect lost {}: now={now:?} delay={loss_delay:?}", self.space, ); @@ -339,13 +338,13 @@ impl LossRecoverySpace { { // Packets sent before now - loss_delay are deemed lost. if packet.time_sent() + loss_delay <= now { - trace!( + qtrace!( "lost={}, time sent {:?} is before lost_delay {loss_delay:?}", packet.pn(), packet.time_sent() ); } else if largest_acked >= Some(packet.pn() + PACKET_THRESHOLD) { - trace!( + qtrace!( "lost={}, is >= {PACKET_THRESHOLD} from largest acked {largest_acked:?}", packet.pn() ); @@ -547,12 +546,12 @@ impl LossRecovery { pub fn on_packet_sent(&mut self, path: &PathRef, mut sent_packet: SentPacket, now: Instant) { let pn_space = PacketNumberSpace::from(sent_packet.packet_type()); - trace!("[{self}] packet {pn_space}-{} sent", sent_packet.pn()); + qtrace!("[{self}] packet {pn_space}-{} sent", sent_packet.pn()); if let Some(space) = self.spaces.get_mut(pn_space) { path.borrow_mut().packet_sent(&mut sent_packet, now); space.on_packet_sent(sent_packet); } else { - warn!( + qwarn!( "[{self}] ignoring {pn_space}-{} from dropped space", sent_packet.pn() ); @@ -611,7 +610,7 @@ impl LossRecovery { R::IntoIter: ExactSizeIterator, { let Some(space) = self.spaces.get_mut(pn_space) else { - info!("ACK on discarded space"); + qinfo!("ACK on discarded space"); return (Vec::new(), Vec::new()); }; @@ -640,7 +639,7 @@ impl LossRecovery { } } - debug!( + qdebug!( "[{self}] ACK for {pn_space} - largest_acked={}", largest_acked_pkt.pn() ); @@ -728,7 +727,7 @@ impl LossRecovery { /// Discard state for a given packet number space. pub fn discard(&mut self, primary_path: &PathRef, space: PacketNumberSpace, now: Instant) { - debug!("[{self}] Reset loss recovery state for {space}"); + qdebug!("[{self}] Reset loss recovery state for {space}"); let mut path = primary_path.borrow_mut(); for p in self.spaces.drop_space(space) { path.discard_packet(&p, now, &mut self.stats.borrow_mut()); @@ -755,7 +754,7 @@ impl LossRecovery { } else { None }; - trace!("[{self}] next_timeout loss={loss_time:?} pto={pto_time:?}"); + qtrace!("[{self}] next_timeout loss={loss_time:?} pto={pto_time:?}"); match (loss_time, pto_time) { (Some(loss_time), Some(pto_time)) => Some(min(loss_time, pto_time)), (Some(loss_time), None) => Some(loss_time), @@ -859,7 +858,7 @@ impl LossRecovery { if let Some(t) = self.pto_time(rtt, *pn_space) { allow_probes[*pn_space] = true; if t <= now { - debug!("[{self}] PTO timer fired for {pn_space}"); + qdebug!("[{self}] PTO timer fired for {pn_space}"); let space = self.spaces.get_mut(*pn_space).unwrap(); lost.extend( space @@ -875,13 +874,13 @@ impl LossRecovery { // This has to happen outside the loop. Increasing the PTO count here causes the // pto_time to increase which might cause PTO for later packet number spaces to not fire. if let Some(pn_space) = pto_space { - trace!("[{self}] PTO {pn_space}, probing {allow_probes:?}"); + qtrace!("[{self}] PTO {pn_space}, probing {allow_probes:?}"); self.fire_pto(pn_space, allow_probes, now); } } pub fn timeout(&mut self, primary_path: &PathRef, now: Instant) -> Vec { - trace!("[{self}] timeout {now:?}"); + qtrace!("[{self}] timeout {now:?}"); let loss_delay = primary_path.borrow().rtt().loss_delay(); let confirmed = self.confirmed(); @@ -915,7 +914,7 @@ impl LossRecovery { /// what the current congestion window is, and what the pacer says. #[allow(clippy::option_if_let_else)] pub fn send_profile(&mut self, path: &Path, now: Instant) -> SendProfile { - trace!("[{self}] get send profile {now:?}"); + qtrace!("[{self}] get send profile {now:?}"); let sender = path.sender(); let mtu = path.plpmtu(); if let Some(profile) = self diff --git a/neqo-transport/src/recv_stream.rs b/neqo-transport/src/recv_stream.rs index 0162b66d5d..f8c598adbd 100644 --- a/neqo-transport/src/recv_stream.rs +++ b/neqo-transport/src/recv_stream.rs @@ -15,8 +15,7 @@ use std::{ rc::{Rc, Weak}, }; -use log::trace; -use neqo_common::Role; +use neqo_common::{qtrace, Role}; use smallvec::SmallVec; use crate::{ @@ -133,7 +132,7 @@ impl RxStreamOrderer { /// Only when `u64` values cannot be converted to `usize`, which only /// happens on 32-bit machines that hold far too much data at the same time. pub fn inbound_frame(&mut self, mut new_start: u64, mut new_data: &[u8]) { - trace!("Inbound data offset={new_start} len={}", new_data.len()); + qtrace!("Inbound data offset={new_start} len={}", new_data.len()); // Get entry before where new entry would go, so we can see if we already // have the new bytes. @@ -166,7 +165,7 @@ impl RxStreamOrderer { // Add a range containing only new data // (In-order frames will take this path, with no overlap) let overlap = prev_end.saturating_sub(new_start); - trace!("New frame {new_start}-{new_end} received, overlap: {overlap}"); + qtrace!("New frame {new_start}-{new_end} received, overlap: {overlap}"); new_start += overlap; new_data = &new_data[usize::try_from(overlap).unwrap()..]; // If it is small enough, extend the previous buffer. @@ -178,11 +177,11 @@ impl RxStreamOrderer { // NNNN // NNNN // Do nothing - trace!("Dropping frame with already-received range {new_start}-{new_end}"); + qtrace!("Dropping frame with already-received range {new_start}-{new_end}"); return; } } else { - trace!("New frame {new_start}-{new_end} received"); + qtrace!("New frame {new_start}-{new_end} received"); false }; @@ -219,14 +218,14 @@ impl RxStreamOrderer { // Fills in the hole, exactly (probably common) break; } else if next_end >= new_end { - trace!( + qtrace!( "New frame {new_start}-{new_end} overlaps with next frame by {overlap}, truncating" ); let truncate_to = new_data.len() - usize::try_from(overlap).unwrap(); to_add = &new_data[..truncate_to]; break; } - trace!( + qtrace!( "New frame {new_start}-{new_end} spans entire next frame {next_start}-{next_end}, replacing" ); to_remove.push(next_start); @@ -309,7 +308,7 @@ impl RxStreamOrderer { /// Copy received data (if any) into the buffer. Returns bytes copied. fn read(&mut self, buf: &mut [u8]) -> usize { - trace!("Reading {} bytes, {} available", buf.len(), self.buffered()); + qtrace!("Reading {} bytes, {} available", buf.len(), self.buffered()); let mut copied = 0; for (&range_start, range_data) in &mut self.data_ranges { @@ -546,7 +545,7 @@ impl RecvStream { mem::discriminant(&self.state), mem::discriminant(&new_state) ); - trace!( + qtrace!( "RecvStream {} state {} -> {}", self.stream_id.as_u64(), self.state.name(), @@ -669,7 +668,7 @@ impl RecvStream { | RecvStreamState::AbortReading { .. } | RecvStreamState::WaitForReset { .. } | RecvStreamState::ResetRecvd { .. } => { - trace!("data received when we are in state {}", self.state.name()); + qtrace!("data received when we are in state {}", self.state.name()); } } @@ -832,7 +831,7 @@ impl RecvStream { } pub fn stop_sending(&mut self, err: AppError) { - trace!("stop_sending called when in state {}", self.state.name()); + qtrace!("stop_sending called when in state {}", self.state.name()); match &mut self.state { RecvStreamState::Recv { fc, @@ -986,8 +985,7 @@ impl RecvStream { mod tests { use std::{cell::RefCell, ops::Range, rc::Rc}; - use log::trace; - use neqo_common::Encoder; + use neqo_common::{qtrace, Encoder}; use super::RecvStream; use crate::{ @@ -1002,7 +1000,7 @@ mod tests { fn recv_ranges(ranges: &[Range], available: usize) { const ZEROES: &[u8] = &[0; 100]; - trace!("recv_ranges {ranges:?}"); + qtrace!("recv_ranges {ranges:?}"); let mut s = RxStreamOrderer::default(); for r in ranges { @@ -1014,7 +1012,7 @@ mod tests { let mut total_recvd = 0; loop { let recvd = s.read(&mut buf[..]); - trace!("recv_ranges read {recvd}"); + qtrace!("recv_ranges read {recvd}"); total_recvd += recvd; if recvd == 0 { assert_eq!(total_recvd, available); diff --git a/neqo-transport/src/rtt.rs b/neqo-transport/src/rtt.rs index 6bbade740f..8e5b95bccb 100644 --- a/neqo-transport/src/rtt.rs +++ b/neqo-transport/src/rtt.rs @@ -11,8 +11,7 @@ use std::{ time::{Duration, Instant}, }; -use log::trace; -use neqo_common::qlog::NeqoQlog; +use neqo_common::{qlog::NeqoQlog, qtrace}; use crate::{ ackrate::{AckRate, PeerAckDelay}, @@ -75,7 +74,7 @@ impl RttEstimate { } pub fn set_initial(&mut self, rtt: Duration) { - trace!("initial RTT={rtt:?}"); + qtrace!("initial RTT={rtt:?}"); if rtt >= GRANULARITY { // Ignore if the value is too small. self.init(rtt); @@ -141,7 +140,7 @@ impl RttEstimate { self.rttvar = (self.rttvar * 3 + rttvar_sample) / 4; self.smoothed_rtt = (self.smoothed_rtt * 7 + rtt_sample) / 8; } - trace!( + qtrace!( "RTT latest={:?} -> estimate={:?}~{:?}", self.latest_rtt, self.smoothed_rtt, diff --git a/neqo-transport/src/send_stream.rs b/neqo-transport/src/send_stream.rs index 05e50f5dc8..cb1203b401 100644 --- a/neqo-transport/src/send_stream.rs +++ b/neqo-transport/src/send_stream.rs @@ -18,8 +18,7 @@ use std::{ }; use indexmap::IndexMap; -use log::{debug, error, trace}; -use neqo_common::{Encoder, Role}; +use neqo_common::{qdebug, qerror, qtrace, Encoder, Role}; use smallvec::SmallVec; use crate::{ @@ -406,7 +405,7 @@ impl RangeTracker { fn unmark_range(&mut self, off: u64, len: usize) { if len == 0 { - debug!("unmark 0-length range at {off}"); + qdebug!("unmark 0-length range at {off}"); return; } @@ -424,7 +423,7 @@ impl RangeTracker { // Check for overlap if *cur_off + *cur_len > off { if *cur_state == RangeState::Acked { - debug!( + qdebug!( "Attempted to unmark Acked range {cur_off}-{cur_len} with unmark_range {off}-{}", off + len ); @@ -436,7 +435,7 @@ impl RangeTracker { } if *cur_state == RangeState::Acked { - debug!( + qdebug!( "Attempted to unmark Acked range {cur_off}-{cur_len} with unmark_range {off}-{}", off + len ); @@ -641,7 +640,7 @@ impl SendStreamState { } fn transition(&mut self, new_state: Self) { - trace!("SendStream state {} -> {}", self.name(), new_state.name()); + qtrace!("SendStream state {} -> {}", self.name(), new_state.name()); *self = new_state; } } @@ -755,7 +754,7 @@ impl SendStream { tokens: &mut Vec, stats: &mut FrameStats, ) { - trace!("write STREAM frames at priority {priority:?}"); + qtrace!("write STREAM frames at priority {priority:?}"); if !self.write_reset_frame(priority, builder, tokens, stats) { self.write_blocked_frame(priority, builder, tokens, stats); self.write_stream_frame(priority, builder, tokens, stats); @@ -873,7 +872,7 @@ impl SendStream { let result = send_buf.next_bytes(); if let Some((offset, slice)) = result { if retransmission_only { - trace!( + qtrace!( "next_bytes apply retransmission limit at {}", self.retransmission_offset ); @@ -921,7 +920,7 @@ impl SendStream { fn length_and_fill(data_len: usize, space: usize) -> (usize, bool) { if data_len >= space { // More data than space allows, or an exact fit => fast path. - trace!("SendStream::length_and_fill fill {space}"); + qtrace!("SendStream::length_and_fill fill {space}"); return (space, true); } @@ -934,7 +933,7 @@ impl SendStream { // From here we can always fit `data_len`, but we might as well fill // if there is no space for the length field plus another frame. let fill = data_len + length_len + PacketBuilder::MINIMUM_FRAME_SIZE > space; - trace!("SendStream::length_and_fill {data_len} fill {fill}"); + qtrace!("SendStream::length_and_fill {data_len} fill {fill}"); (data_len, fill) } @@ -966,14 +965,14 @@ impl SendStream { 0 }; if overhead > builder.remaining() { - trace!("[{self}] write_frame no space for header"); + qtrace!("[{self}] write_frame no space for header"); return; } let (length, fill) = Self::length_and_fill(data.len(), builder.remaining() - overhead); let fin = final_size.is_some_and(|fs| fs == offset + u64::try_from(length).unwrap()); if length == 0 && !fin { - trace!("[{self}] write_frame no data, no fin"); + qtrace!("[{self}] write_frame no data, no fin"); return; } @@ -1010,7 +1009,7 @@ impl SendStream { | SendStreamState::Send { .. } | SendStreamState::DataSent { .. } | SendStreamState::DataRecvd { .. } => { - trace!("[{self}] Reset acked while in {} state?", self.state.name()); + qtrace!("[{self}] Reset acked while in {} state?", self.state.name()); } SendStreamState::ResetSent { final_retired, @@ -1020,7 +1019,7 @@ impl SendStream { final_retired, final_written, }), - SendStreamState::ResetRecvd { .. } => trace!("[{self}] already in ResetRecvd state"), + SendStreamState::ResetRecvd { .. } => qtrace!("[{self}] already in ResetRecvd state"), }; } @@ -1080,7 +1079,7 @@ impl SendStream { { fc.frame_lost(limit); } else { - trace!("[{self}] Ignoring lost STREAM_DATA_BLOCKED({limit})"); + qtrace!("[{self}] Ignoring lost STREAM_DATA_BLOCKED({limit})"); } } @@ -1148,7 +1147,7 @@ impl SendStream { }); } } - _ => trace!( + _ => qtrace!( "[{self}] mark_as_acked called from state {}", self.state.name() ), @@ -1161,7 +1160,7 @@ impl SendStream { self.retransmission_offset, offset + u64::try_from(len).unwrap(), ); - trace!( + qtrace!( "[{self}] mark_as_lost retransmission offset={}", self.retransmission_offset ); @@ -1252,7 +1251,7 @@ impl SendStream { fn send_internal(&mut self, buf: &[u8], atomic: bool) -> Res { if buf.is_empty() { - error!("[{self}] zero-length send on stream"); + qerror!("[{self}] zero-length send on stream"); return Err(Error::InvalidInput); } @@ -1316,10 +1315,10 @@ impl SendStream { fin_acked: false, }); } - SendStreamState::DataSent { .. } => trace!("[{self}] already in DataSent state"), - SendStreamState::DataRecvd { .. } => trace!("[{self}] already in DataRecvd state"), - SendStreamState::ResetSent { .. } => trace!("[{self}] already in ResetSent state"), - SendStreamState::ResetRecvd { .. } => trace!("[{self}] already in ResetRecvd state"), + SendStreamState::DataSent { .. } => qtrace!("[{self}] already in DataSent state"), + SendStreamState::DataRecvd { .. } => qtrace!("[{self}] already in DataRecvd state"), + SendStreamState::ResetSent { .. } => qtrace!("[{self}] already in ResetSent state"), + SendStreamState::ResetRecvd { .. } => qtrace!("[{self}] already in ResetRecvd state"), } } @@ -1360,9 +1359,9 @@ impl SendStream { final_written: buffered, }); } - SendStreamState::DataRecvd { .. } => trace!("[{self}] already in DataRecvd state"), - SendStreamState::ResetSent { .. } => trace!("[{self}] already in ResetSent state"), - SendStreamState::ResetRecvd { .. } => trace!("[{self}] already in ResetRecvd state"), + SendStreamState::DataRecvd { .. } => qtrace!("[{self}] already in DataRecvd state"), + SendStreamState::ResetSent { .. } => qtrace!("[{self}] already in ResetSent state"), + SendStreamState::ResetRecvd { .. } => qtrace!("[{self}] already in ResetRecvd state"), }; } @@ -1573,7 +1572,7 @@ impl SendStreams { self.get_mut(stream_id).unwrap().set_sendorder(sendorder); group = self.group_mut(sendorder); group.insert(stream_id); - trace!( + qtrace!( "ordering of stream_ids: {:?}", self.sendordered.values().collect::>() ); @@ -1687,7 +1686,7 @@ impl SendStreams { tokens: &mut Vec, stats: &mut FrameStats, ) { - trace!("write STREAM frames at priority {priority:?}"); + qtrace!("write STREAM frames at priority {priority:?}"); // WebTransport data (which is Normal) may have a SendOrder // priority attached. The spec states (6.3 write-chunk 6.1): @@ -1721,16 +1720,16 @@ impl SendStreams { // Iterate the map, but only those without fairness, then iterate // OrderGroups, then iterate each group - trace!("processing streams... unfair:"); + qtrace!("processing streams... unfair:"); for stream in self.map.values_mut() { if !stream.is_fair() { - trace!(" {stream}"); + qtrace!(" {stream}"); if !stream.write_frames_with_early_return(priority, builder, tokens, stats) { break; } } } - trace!("fair streams:"); + qtrace!("fair streams:"); let stream_ids = self.regular.iter().chain( self.sendordered .values_mut() @@ -1740,9 +1739,9 @@ impl SendStreams { for stream_id in stream_ids { let stream = self.map.get_mut(&stream_id).unwrap(); if let Some(order) = stream.sendorder() { - trace!(" {stream_id} ({order})"); + qtrace!(" {stream_id} ({order})"); } else { - trace!(" None"); + qtrace!(" None"); } if !stream.write_frames_with_early_return(priority, builder, tokens, stats) { break; @@ -1786,8 +1785,7 @@ pub struct SendStreamRecoveryToken { mod tests { use std::{cell::RefCell, collections::VecDeque, num::NonZeroUsize, rc::Rc}; - use log::trace; - use neqo_common::{event::Provider, hex_with_len, Encoder}; + use neqo_common::{event::Provider, hex_with_len, qtrace, Encoder}; use super::SendStreamRecoveryToken; use crate::{ @@ -2937,7 +2935,7 @@ mod tests { fn frame_sent_sid(stream: u64, offset: usize, len: usize, fin: bool, space: usize) -> bool { const BUF: &[u8] = &[0x42; 128]; - trace!("frame_sent stream={stream} offset={offset} len={len} fin={fin}, space={space}"); + qtrace!("frame_sent stream={stream} offset={offset} len={len} fin={fin}, space={space}"); let mut s = stream_with_sent(stream, offset); @@ -2961,7 +2959,7 @@ mod tests { &mut tokens, &mut stats, ); - trace!( + qtrace!( "STREAM frame: {}", hex_with_len(&builder.as_ref()[header_len..]) ); @@ -3045,7 +3043,7 @@ mod tests { fn stream_frame_at_boundary(data: &[u8]) { fn send_with_extra_capacity(data: &[u8], extra: usize, expect_full: bool) -> Vec { - trace!("send_with_extra_capacity {} + {extra}", data.len()); + qtrace!("send_with_extra_capacity {} + {extra}", data.len()); let mut s = stream_with_sent(0, 0); s.send(data).unwrap(); s.close(); diff --git a/neqo-transport/src/sender.rs b/neqo-transport/src/sender.rs index 91ce62492f..5dd8f2d69c 100644 --- a/neqo-transport/src/sender.rs +++ b/neqo-transport/src/sender.rs @@ -13,8 +13,7 @@ use std::{ time::{Duration, Instant}, }; -use log::debug; -use neqo_common::qlog::NeqoQlog; +use neqo_common::{qdebug, qlog::NeqoQlog}; use crate::{ cc::{ClassicCongestionControl, CongestionControl, CongestionControlAlgorithm, Cubic, NewReno}, @@ -93,7 +92,7 @@ impl PacketSender { fn maybe_update_pacer_mtu(&mut self) { let current_mtu = self.pmtud().plpmtu(); if current_mtu != self.pacer.mtu() { - debug!( + qdebug!( "PLPMTU changed from {} to {current_mtu}, updating pacer", self.pacer.mtu() ); diff --git a/neqo-transport/src/server.rs b/neqo-transport/src/server.rs index 1696667f8d..4680bb92f6 100644 --- a/neqo-transport/src/server.rs +++ b/neqo-transport/src/server.rs @@ -16,8 +16,10 @@ use std::{ time::Instant, }; -use log::{debug, error, info, trace, warn}; -use neqo_common::{event::Provider, hex, qlog::NeqoQlog, Datagram, IpTos, Role}; +use neqo_common::{ + event::Provider, hex, qdebug, qerror, qinfo, qlog::NeqoQlog, qtrace, qwarn, Datagram, IpTos, + Role, +}; use neqo_crypto::{ encode_ech_config, AntiReplay, Cipher, PrivateKey, PublicKey, ZeroRttCheckResult, ZeroRttChecker, @@ -197,7 +199,7 @@ impl Server { dgram: Datagram>, now: Instant, ) -> Output { - debug!("[{self}] Handle initial"); + qdebug!("[{self}] Handle initial"); let res = self .address_validation .borrow() @@ -209,7 +211,7 @@ impl Server { self.accept_connection(initial, dgram, Some(orig_dcid), now) } AddressValidationResult::Validate => { - info!("[{self}] Send retry for {:?}", initial.dst_cid); + qinfo!("[{self}] Send retry for {:?}", initial.dst_cid); let res = self.address_validation.borrow().generate_retry_token( &initial.dst_cid, @@ -217,7 +219,7 @@ impl Server { now, ); let Ok(token) = res else { - error!("[{self}] unable to generate token, dropping packet"); + qerror!("[{self}] unable to generate token, dropping packet"); return Output::None; }; if let Some(new_dcid) = self.cid_generator.borrow_mut().generate_cid() { @@ -230,11 +232,11 @@ impl Server { ); packet.map_or_else( |_| { - error!("[{self}] unable to encode retry, dropping packet"); + qerror!("[{self}] unable to encode retry, dropping packet"); Output::None }, |p| { - debug!( + qdebug!( "[{self}] type={:?} path:{} {}->{} {:?} len {}", PacketType::Retry, initial.dst_cid, @@ -252,7 +254,7 @@ impl Server { }, ) } else { - error!("[{self}] no connection ID for retry, dropping packet"); + qerror!("[{self}] no connection ID for retry, dropping packet"); Output::None } } @@ -271,7 +273,7 @@ impl Server { format!("server-{odcid}"), ) .unwrap_or_else(|e| { - error!("failed to create NeqoQlog: {e}"); + qerror!("failed to create NeqoQlog: {e}"); NeqoQlog::disabled() }) }) @@ -285,7 +287,7 @@ impl Server { ) { let zcheck = self.zero_rtt_checker.clone(); if c.server_enable_0rtt(&self.anti_replay, zcheck).is_err() { - warn!("[{self}] Unable to enable 0-RTT"); + qwarn!("[{self}] Unable to enable 0-RTT"); } if let Some(odcid) = &orig_dcid { // There was a retry, so set the connection IDs for. @@ -297,7 +299,7 @@ impl Server { if c.server_enable_ech(cfg.config, &cfg.public_name, &cfg.sk, &cfg.pk) .is_err() { - warn!("[{self}] Unable to enable ECH"); + qwarn!("[{self}] Unable to enable ECH"); } } } @@ -309,7 +311,7 @@ impl Server { orig_dcid: Option, now: Instant, ) -> Output { - info!( + qinfo!( "[{self}] Accept connection {:?}", orig_dcid.as_ref().unwrap_or(&initial.dst_cid) ); @@ -333,7 +335,7 @@ impl Server { out } Err(e) => { - warn!("[{self}] Unable to create connection"); + qwarn!("[{self}] Unable to create connection"); if e == crate::Error::VersionNegotiation { crate::qlog::server_version_information_failed( &self.create_qlog_trace(orig_dcid.unwrap_or(initial.dst_cid).as_cid_ref()), @@ -348,13 +350,13 @@ impl Server { } fn process_input(&mut self, dgram: Datagram>, now: Instant) -> Output { - trace!("Process datagram: {}", hex(&dgram[..])); + qtrace!("Process datagram: {}", hex(&dgram[..])); // This is only looking at the first packet header in the datagram. // All packets in the datagram are routed to the same connection. let res = PublicPacket::decode(&dgram[..], self.cid_generator.borrow().as_decoder()); let Ok((packet, _remainder)) = res else { - trace!("[{self}] Discarding {dgram:?}"); + qtrace!("[{self}] Discarding {dgram:?}"); return Output::None; }; @@ -369,7 +371,7 @@ impl Server { if packet.packet_type() == PacketType::Short { // TODO send a stateless reset here. - trace!("[{self}] Short header packet for an unknown connection"); + qtrace!("[{self}] Short header packet for an unknown connection"); return Output::None; } @@ -382,18 +384,18 @@ impl Server { .contains(&packet.version().unwrap())) { if dgram.len() < MIN_INITIAL_PACKET_SIZE { - debug!("[{self}] Unsupported version: too short"); + qdebug!("[{self}] Unsupported version: too short"); return Output::None; } - debug!("[{self}] Unsupported version: {:x}", packet.wire_version()); + qdebug!("[{self}] Unsupported version: {:x}", packet.wire_version()); let vn = PacketBuilder::version_negotiation( &packet.scid()[..], &packet.dcid()[..], packet.wire_version(), self.conn_params.get_versions().all(), ); - debug!( + qdebug!( "[{self}] type={:?} path:{} {}->{} {:?} len {}", PacketType::VersionNegotiation, packet.dcid(), @@ -421,7 +423,7 @@ impl Server { match packet.packet_type() { PacketType::Initial => { if dgram.len() < MIN_INITIAL_PACKET_SIZE { - debug!("[{self}] Drop initial: too short"); + qdebug!("[{self}] Drop initial: too short"); return Output::None; } // Copy values from `packet` because they are currently still borrowing from @@ -431,12 +433,12 @@ impl Server { } PacketType::ZeroRtt => { let dcid = ConnectionId::from(packet.dcid()); - debug!("[{self}] Dropping 0-RTT for unknown connection {dcid}"); + qdebug!("[{self}] Dropping 0-RTT for unknown connection {dcid}"); Output::None } PacketType::OtherVersion => unreachable!(), _ => { - trace!("[{self}] Not an initial packet"); + qtrace!("[{self}] Not an initial packet"); Output::None } } diff --git a/neqo-transport/src/shuffle.rs b/neqo-transport/src/shuffle.rs index bc1cf06c34..fd81190c27 100644 --- a/neqo-transport/src/shuffle.rs +++ b/neqo-transport/src/shuffle.rs @@ -6,8 +6,7 @@ use std::ops::Range; -use log::trace; -use neqo_common::Decoder; +use neqo_common::{qtrace, Decoder}; /// Finds the range where the SNI extension lives, or returns `None`. #[must_use] @@ -55,7 +54,7 @@ pub fn find_sni(buf: &[u8]) -> Option> { if end > dec.offset() + dec.remaining() { return None; } - trace!( + qtrace!( "SNI range {start}..{end}: {:?}", String::from_utf8_lossy(&buf[start..end]) ); diff --git a/neqo-transport/src/stats.rs b/neqo-transport/src/stats.rs index ae60b7fe07..4db972dcd0 100644 --- a/neqo-transport/src/stats.rs +++ b/neqo-transport/src/stats.rs @@ -14,7 +14,7 @@ use std::{ time::Duration, }; -use log::warn; +use neqo_common::qwarn; use crate::{ ecn::{EcnCount, EcnValidationCount}, @@ -222,7 +222,7 @@ impl Stats { pub fn pkt_dropped(&mut self, reason: impl AsRef) { self.dropped_rx += 1; - warn!( + qwarn!( "[{}] Dropped received packet: {}; Total: {}", self.info, reason.as_ref(), diff --git a/neqo-transport/src/streams.rs b/neqo-transport/src/streams.rs index c949cc7215..cffc51d736 100644 --- a/neqo-transport/src/streams.rs +++ b/neqo-transport/src/streams.rs @@ -7,8 +7,7 @@ // Stream management for a connection. use std::{cell::RefCell, cmp::Ordering, rc::Rc}; -use log::{trace, warn}; -use neqo_common::Role; +use neqo_common::{qtrace, qwarn, Role}; use crate::{ fc::{LocalStreamLimits, ReceiverFlowControl, RemoteStreamLimits, SenderFlowControl}, @@ -165,7 +164,7 @@ impl Streams { stream_id, maximum_stream_data, } => { - trace!( + qtrace!( "Stream {} Received MaxStreamData {}", *stream_id, *maximum_stream_data @@ -184,12 +183,12 @@ impl Streams { } Frame::DataBlocked { data_limit } => { // Should never happen since we set data limit to max - warn!("Received DataBlocked with data limit {data_limit}"); + qwarn!("Received DataBlocked with data limit {data_limit}"); stats.data_blocked += 1; self.handle_data_blocked(); } Frame::StreamDataBlocked { stream_id, .. } => { - trace!("Received StreamDataBlocked"); + qtrace!("Received StreamDataBlocked"); stats.stream_data_blocked += 1; // Terminate connection with STREAM_STATE_ERROR if send-only // stream (-transport 19.13) diff --git a/neqo-transport/src/tparams.rs b/neqo-transport/src/tparams.rs index df2a1785f5..117b62ba9b 100644 --- a/neqo-transport/src/tparams.rs +++ b/neqo-transport/src/tparams.rs @@ -13,8 +13,7 @@ use std::{ rc::Rc, }; -use log::{debug, info, trace}; -use neqo_common::{hex, Decoder, Encoder, Role}; +use neqo_common::{hex, qdebug, qinfo, qtrace, Decoder, Encoder, Role}; use neqo_crypto::{ constants::{TLS_HS_CLIENT_HELLO, TLS_HS_ENCRYPTED_EXTENSIONS}, ext::{ExtensionHandler, ExtensionHandlerResult, ExtensionWriterResult}, @@ -140,7 +139,7 @@ pub enum TransportParameter { impl TransportParameter { fn encode(&self, enc: &mut Encoder, tp: TransportParameterId) { - trace!("TP encoded; type 0x{tp:02x} val {self:?}"); + qtrace!("TP encoded; type 0x{tp:02x} val {self:?}"); enc.encode_varint(tp); match self { Self::Bytes(a) => { @@ -251,7 +250,7 @@ impl TransportParameter { fn decode(dec: &mut Decoder) -> Res> { let tp = dec.decode_varint().ok_or(Error::NoMoreData)?; let content = dec.decode_vvec().ok_or(Error::NoMoreData)?; - trace!("TP {tp:x} length {:x}", content.len()); + qtrace!("TP {tp:x} length {:x}", content.len()); let mut d = Decoder::from(content); let value = match tp { ORIGINAL_DESTINATION_CONNECTION_ID @@ -310,7 +309,7 @@ impl TransportParameter { if d.remaining() > 0 { return Err(Error::TooMuchData); } - trace!("TP decoded; type 0x{tp:02x} val {value:?}"); + qtrace!("TP decoded; type 0x{tp:02x} val {value:?}"); Ok(Some((tp, value))) } } @@ -335,7 +334,7 @@ impl TransportParameters { /// using the provided decoder. pub(crate) fn decode(d: &mut Decoder) -> Res { let mut tps = Self::default(); - trace!("Parsed fixed TP header"); + qtrace!("Parsed fixed TP header"); while d.remaining() > 0 { match TransportParameter::decode(d) { @@ -628,7 +627,7 @@ impl TransportParametersHandler { fn compatible_upgrade(&mut self, remote_tp: &TransportParameters) -> Res<()> { if let Some((current, other)) = remote_tp.get_versions() { - trace!( + qtrace!( "Peer versions: {current:x} {other:x?}; config {:?}", self.versions, ); @@ -638,7 +637,7 @@ impl TransportParametersHandler { if self.versions.compatible().any(|&v| v == chosen) { Ok(()) } else { - info!( + qinfo!( "Chosen version {current:x} is not compatible with initial version {:x}", self.versions.initial().wire_version(), ); @@ -646,7 +645,7 @@ impl TransportParametersHandler { } } else { if current != self.versions.initial().wire_version() { - info!( + qinfo!( "Current version {current:x} != own version {:x}", self.versions.initial().wire_version(), ); @@ -655,7 +654,7 @@ impl TransportParametersHandler { if let Some(preferred) = self.versions.preferred_compatible(other) { if preferred != self.versions.initial() { - info!( + qinfo!( "Compatible upgrade {:?} ==> {preferred:?}", self.versions.initial() ); @@ -664,7 +663,7 @@ impl TransportParametersHandler { } Ok(()) } else { - info!("Unable to find any compatible version"); + qinfo!("Unable to find any compatible version"); Err(Error::TransportParameterError) } } @@ -680,7 +679,7 @@ impl ExtensionHandler for TransportParametersHandler { return ExtensionWriterResult::Skip; } - debug!("Writing transport parameters, msg={msg:?}"); + qdebug!("Writing transport parameters, msg={msg:?}"); // TODO(ekr@rtfm.com): Modify to avoid a copy. let mut enc = Encoder::default(); @@ -691,7 +690,7 @@ impl ExtensionHandler for TransportParametersHandler { } fn handle(&mut self, msg: HandshakeMessage, d: &[u8]) -> ExtensionHandlerResult { - trace!( + qtrace!( "Handling transport parameters, msg={msg:?} value={}", hex(d), ); @@ -743,24 +742,24 @@ where fn check(&self, token: &[u8]) -> ZeroRttCheckResult { // Reject 0-RTT if there is no token. if token.is_empty() { - debug!("0-RTT: no token, no 0-RTT"); + qdebug!("0-RTT: no token, no 0-RTT"); return ZeroRttCheckResult::Reject; } let mut dec = Decoder::from(token); let Some(tpslice) = dec.decode_vvec() else { - info!("0-RTT: token code error"); + qinfo!("0-RTT: token code error"); return ZeroRttCheckResult::Fail; }; let mut dec_tp = Decoder::from(tpslice); let Ok(remembered) = TransportParameters::decode(&mut dec_tp) else { - info!("0-RTT: transport parameter decode error"); + qinfo!("0-RTT: transport parameter decode error"); return ZeroRttCheckResult::Fail; }; if self.handler.borrow().local.ok_for_0rtt(&remembered) { - info!("0-RTT: transport parameters OK, passing to application checker"); + qinfo!("0-RTT: transport parameters OK, passing to application checker"); self.app_checker.check(dec.decode_remainder()) } else { - info!("0-RTT: transport parameters bad, rejecting"); + qinfo!("0-RTT: transport parameters bad, rejecting"); ZeroRttCheckResult::Reject } } diff --git a/neqo-transport/src/tracking.rs b/neqo-transport/src/tracking.rs index 00ae5c644c..fc60d044c7 100644 --- a/neqo-transport/src/tracking.rs +++ b/neqo-transport/src/tracking.rs @@ -14,8 +14,7 @@ use std::{ }; use enum_map::{enum_map, Enum, EnumMap}; -use log::{debug, info, trace, warn}; -use neqo_common::IpTosEcn; +use neqo_common::{qdebug, qinfo, qtrace, qwarn, IpTosEcn}; use neqo_crypto::{Epoch, TLS_EPOCH_HANDSHAKE, TLS_EPOCH_INITIAL}; use crate::{ @@ -181,12 +180,12 @@ impl PacketRange { assert!(!self.contains(pn)); // Only insert if this is adjacent the current range. if (self.largest + 1) == pn { - trace!("[{self}] Adding largest {pn}"); + qtrace!("[{self}] Adding largest {pn}"); self.largest += 1; self.ack_needed = true; InsertionResult::Largest } else if self.smallest == (pn + 1) { - trace!("[{self}] Adding smallest {pn}"); + qtrace!("[{self}] Adding smallest {pn}"); self.smallest -= 1; self.ack_needed = true; InsertionResult::Smallest @@ -197,7 +196,7 @@ impl PacketRange { /// Maybe merge a higher-numbered range into this. fn merge_larger(&mut self, other: &Self) { - info!("[{self}] Merging {other}"); + qinfo!("[{self}] Merging {other}"); // This only works if they are immediately adjacent. assert_eq!(self.largest + 1, other.smallest); @@ -370,10 +369,10 @@ impl RecvdPackets { if self.ranges.len() > MAX_TRACKED_RANGES { let oldest = self.ranges.pop_back().unwrap(); if oldest.ack_needed { - warn!("[{self}] Dropping unacknowledged ACK range: {oldest}"); + qwarn!("[{self}] Dropping unacknowledged ACK range: {oldest}"); // TODO(mt) Record some statistics about this so we can tune MAX_TRACKED_RANGES. } else { - debug!("[{self}] Drop ACK range: {oldest}"); + qdebug!("[{self}] Drop ACK range: {oldest}"); } self.min_tracked = oldest.largest + 1; } @@ -383,7 +382,7 @@ impl RecvdPackets { /// Return true if the packet was the largest received so far. pub fn set_received(&mut self, now: Instant, pn: PacketNumber, ack_eliciting: bool) -> bool { let next_in_order_pn = self.ranges.front().map_or(0, |r| r.largest + 1); - trace!("[{self}] received {pn}, next: {next_in_order_pn}"); + qtrace!("[{self}] received {pn}, next: {next_in_order_pn}"); self.add(pn); self.trim_ranges(); @@ -414,7 +413,7 @@ impl RecvdPackets { // of the change is very small. self.ack_time.unwrap_or_else(|| now + self.ack_delay) }; - debug!("[{self}] Set ACK timer to {ack_time:?}"); + qdebug!("[{self}] Set ACK timer to {ack_time:?}"); self.ack_time = Some(ack_time); } largest @@ -423,7 +422,7 @@ impl RecvdPackets { /// If we just received a PING frame, we should immediately acknowledge. pub fn immediate_ack(&mut self, now: Instant) { self.ack_time = Some(now); - debug!("[{self}] immediate_ack at {now:?}"); + qdebug!("[{self}] immediate_ack at {now:?}"); } /// Check if the packet is a duplicate. @@ -602,7 +601,7 @@ impl AckTracker { #[cfg(debug_assertions)] for (space, recvd) in &self.spaces { if let Some(recvd) = recvd { - trace!("ack_time for {space} = {:?}", recvd.ack_time()); + qtrace!("ack_time for {space} = {:?}", recvd.ack_time()); } } diff --git a/neqo-transport/src/version.rs b/neqo-transport/src/version.rs index c3771dda13..8381a9086b 100644 --- a/neqo-transport/src/version.rs +++ b/neqo-transport/src/version.rs @@ -4,7 +4,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use log::debug; +use neqo_common::qdebug; use crate::{Error, Res}; @@ -188,7 +188,7 @@ impl VersionConfig { /// Overwrite the initial value; used by the `Server` when handling new connections /// and by the client on resumption. pub(crate) fn set_initial(&mut self, initial: Version) { - debug!( + qdebug!( "Overwrite initial version {:?} ==> {initial:?}", self.initial ); diff --git a/neqo-transport/tests/common/mod.rs b/neqo-transport/tests/common/mod.rs index e806a2f33b..a16c5f2c92 100644 --- a/neqo-transport/tests/common/mod.rs +++ b/neqo-transport/tests/common/mod.rs @@ -8,8 +8,7 @@ use std::{cell::RefCell, mem, ops::Range, rc::Rc}; -use log::trace; -use neqo_common::{event::Provider, hex_with_len, Datagram, Decoder, Role}; +use neqo_common::{event::Provider, hex_with_len, qtrace, Datagram, Decoder, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, hkdf, diff --git a/neqo-transport/tests/retry.rs b/neqo-transport/tests/retry.rs index cd545b8445..0dc083859b 100644 --- a/neqo-transport/tests/retry.rs +++ b/neqo-transport/tests/retry.rs @@ -15,8 +15,7 @@ use std::{ }; use common::{connected_server, default_server, generate_ticket}; -use log::{debug, trace}; -use neqo_common::{hex_with_len, Datagram, Encoder, Role}; +use neqo_common::{hex_with_len, qdebug, qtrace, Datagram, Encoder, Role}; use neqo_crypto::AuthenticationStatus; use neqo_transport::{ server::ValidateAddress, CloseReason, Error, State, StreamType, MIN_INITIAL_PACKET_SIZE, @@ -399,7 +398,7 @@ fn mitm_retry() { .encode_varint(u64::try_from(payload.len()).unwrap()); let pn_offset = enc.len(); let notoken_header = enc.encode_uint(pn_len, pn).as_ref().to_vec(); - trace!("notoken_header={}", hex_with_len(¬oken_header)); + qtrace!("notoken_header={}", hex_with_len(¬oken_header)); // Encrypt. let mut notoken_packet = Encoder::with_capacity(MIN_INITIAL_PACKET_SIZE) @@ -418,7 +417,7 @@ fn mitm_retry() { // All MIN_INITIAL_PACKET_SIZE bytes are needed to reach the minimum datagram size. apply_header_protection(&hp, &mut notoken_packet, pn_offset..(pn_offset + pn_len)); - trace!("packet={}", hex_with_len(¬oken_packet)); + qtrace!("packet={}", hex_with_len(¬oken_packet)); let new_datagram = Datagram::new( client_initial2.source(), @@ -426,7 +425,7 @@ fn mitm_retry() { client_initial2.tos(), notoken_packet, ); - debug!("passing modified Initial to the main server"); + qdebug!("passing modified Initial to the main server"); let dgram = server.process(Some(new_datagram), now()).dgram(); assert!(dgram.is_some()); diff --git a/neqo-transport/tests/server.rs b/neqo-transport/tests/server.rs index 653cfc5c08..8ff6511e0b 100644 --- a/neqo-transport/tests/server.rs +++ b/neqo-transport/tests/server.rs @@ -9,8 +9,7 @@ mod common; use std::{cell::RefCell, mem, net::SocketAddr, rc::Rc, time::Duration}; use common::{connect, connected_server, default_server, find_ticket, generate_ticket, new_server}; -use log::trace; -use neqo_common::{Datagram, Decoder, Encoder, Role}; +use neqo_common::{qtrace, Datagram, Decoder, Encoder, Role}; use neqo_crypto::{ generate_ech_keys, AllowZeroRtt, AuthenticationStatus, ZeroRttCheckResult, ZeroRttChecker, }; @@ -738,7 +737,7 @@ fn closed() { let res = client.process_output(now()); assert!(res.callback() > Duration::new(0, 0)); - trace!("60s later"); + qtrace!("60s later"); let res = server.process_output(now() + Duration::from_secs(60)); assert_eq!(res, Output::None); } diff --git a/neqo-udp/src/lib.rs b/neqo-udp/src/lib.rs index 827bdae5a0..cbe3b2f4c0 100644 --- a/neqo-udp/src/lib.rs +++ b/neqo-udp/src/lib.rs @@ -12,8 +12,7 @@ use std::{ slice::{self, Chunks}, }; -use log::{debug, trace}; -use neqo_common::{Datagram, IpTos}; +use neqo_common::{qdebug, qtrace, Datagram, IpTos}; use quinn_udp::{EcnCodepoint, RecvMeta, Transmit, UdpSocketState}; /// Socket receive buffer size. @@ -38,7 +37,7 @@ pub fn send_inner( state.try_send(socket, &transmit)?; - trace!( + qtrace!( "sent {} bytes from {} to {}", d.len(), d.source(), @@ -71,9 +70,11 @@ pub fn recv_inner<'a>( )?; if meta.len == 0 || meta.stride == 0 { - debug!( + qdebug!( "ignoring datagram from {} to {local_address} len {} stride {}", - meta.addr, meta.len, meta.stride + meta.addr, + meta.len, + meta.stride ); continue; } @@ -81,7 +82,7 @@ pub fn recv_inner<'a>( break &recv_buf[..meta.len]; }; - trace!( + qtrace!( "received {} bytes from {} to {local_address} in {} segments", data.len(), meta.addr, diff --git a/test-fixture/src/header_protection.rs b/test-fixture/src/header_protection.rs index fbe209c331..3b7b8b0dc2 100644 --- a/test-fixture/src/header_protection.rs +++ b/test-fixture/src/header_protection.rs @@ -8,8 +8,7 @@ use std::{cell::RefCell, mem, ops::Range, rc::Rc}; -use log::trace; -use neqo_common::{event::Provider, hex_with_len, Datagram, Decoder, Role}; +use neqo_common::{event::Provider, hex_with_len, qtrace, Datagram, Decoder, Role}; use neqo_crypto::{ constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, hkdf, @@ -132,7 +131,7 @@ pub fn apply_header_protection(hp: &HpKey, packet: &mut [u8], pn_bytes: Range (&[u8], Option<&[u8]>) { } else { None }; - trace!("split packet: {} {:?}", hex(p1), p2.map(hex)); + qtrace!("split packet: {} {:?}", hex(p1), p2.map(hex)); (p1, p2) } diff --git a/test-fixture/src/sim/connection.rs b/test-fixture/src/sim/connection.rs index 4891a1b12f..4f04328a2b 100644 --- a/test-fixture/src/sim/connection.rs +++ b/test-fixture/src/sim/connection.rs @@ -12,8 +12,7 @@ use std::{ time::Instant, }; -use log::{debug, info, trace}; -use neqo_common::{event::Provider, Datagram}; +use neqo_common::{event::Provider, qdebug, qinfo, qtrace, Datagram}; use neqo_crypto::AuthenticationStatus; use neqo_transport::{ Connection, ConnectionEvent, ConnectionParameters, Output, State, StreamId, StreamType, @@ -146,7 +145,7 @@ impl Node for ConnectionNode { let mut active = false; while let Some(e) = self.c.next_event() { - trace!("[{}] received event {e:?}", self.c); + qtrace!("[{}] received event {e:?}", self.c); // Perform authentication automatically. if matches!(e, ConnectionEvent::AuthenticationNeeded) { @@ -161,7 +160,7 @@ impl Node for ConnectionNode { if matches!(res, Output::Datagram(_)) || !active { return res; } - debug!("[{}] no datagram and goal activity, looping", self.c); + qdebug!("[{}] no datagram and goal activity, looping", self.c); } } @@ -176,7 +175,7 @@ impl Node for ConnectionNode { } fn print_summary(&self, test_name: &str) { - info!("{test_name}: {:?}", self.c.stats()); + qinfo!("{test_name}: {:?}", self.c.stats()); } } @@ -234,7 +233,7 @@ impl SendData { fn make_stream(&mut self, c: &mut Connection) { if self.stream_id.is_none() { if let Ok(stream_id) = c.stream_create(StreamType::UniDi) { - debug!("[{c}] made stream {stream_id} for sending"); + qdebug!("[{c}] made stream {stream_id} for sending"); self.stream_id = Some(stream_id); } } @@ -250,7 +249,7 @@ impl SendData { return status; } self.remaining -= sent; - trace!("sent {sent} remaining {}", self.remaining); + qtrace!("sent {sent} remaining {}", self.remaining); if self.remaining == 0 { c.stream_close_send(stream_id).unwrap(); return GoalStatus::Done; @@ -316,7 +315,7 @@ impl ReceiveData { loop { let end = min(self.remaining, buf.len()); let (recvd, _) = c.stream_recv(stream_id, &mut buf[..end]).unwrap(); - trace!("received {recvd} remaining {}", self.remaining); + qtrace!("received {recvd} remaining {}", self.remaining); if recvd == 0 { return status; } diff --git a/test-fixture/src/sim/drop.rs b/test-fixture/src/sim/drop.rs index 8f48a09abc..fbecd0536c 100644 --- a/test-fixture/src/sim/drop.rs +++ b/test-fixture/src/sim/drop.rs @@ -9,8 +9,7 @@ use std::{ time::Instant, }; -use log::trace; -use neqo_common::Datagram; +use neqo_common::{qtrace, Datagram}; use neqo_transport::Output; use super::{Node, Rng}; @@ -63,7 +62,7 @@ impl Node for Drop { fn process(&mut self, d: Option, _now: Instant) -> Output { d.map_or(Output::None, |dgram| { if self.drop() { - trace!("drop {}", dgram.len()); + qtrace!("drop {}", dgram.len()); Output::None } else { Output::Datagram(dgram) diff --git a/test-fixture/src/sim/mod.rs b/test-fixture/src/sim/mod.rs index 258946d220..35af6e0c46 100644 --- a/test-fixture/src/sim/mod.rs +++ b/test-fixture/src/sim/mod.rs @@ -22,8 +22,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{debug, error, info, trace}; -use neqo_common::{Datagram, Encoder}; +use neqo_common::{qdebug, qerror, qinfo, qtrace, Datagram, Encoder}; use neqo_transport::Output; use rng::Random; use NodeState::{Active, Idle, Waiting}; @@ -163,12 +162,12 @@ impl Simulator { // variable, if set. if let Ok(dir) = std::env::var("DUMP_SIMULATION_SEEDS") { if create_dir_all(&dir).is_err() { - error!("Failed to create directory {dir}"); + qerror!("Failed to create directory {dir}"); } else { let seed_str = sim.rng.borrow().seed_str(); let path = PathBuf::from(format!("{dir}/{}-{seed_str}", sim.name)); if File::create(&path).is_err() { - error!("Failed to write seed to {}", path.to_string_lossy()); + qerror!("Failed to write seed to {}", path.to_string_lossy()); } } } @@ -200,25 +199,25 @@ impl Simulator { loop { for n in &mut self.nodes { if dgram.is_none() && !n.ready(now) { - debug!("[{}] kipping {:?}", self.name, n.node); + qdebug!("[{}] kipping {:?}", self.name, n.node); continue; } - debug!("[{}] processing {:?}", self.name, n.node); + qdebug!("[{}] processing {:?}", self.name, n.node); let res = n.process(dgram.take(), now); n.state = match res { Output::Datagram(d) => { - trace!("[{}] => datagram {}", self.name, d.len()); + qtrace!("[{}] => datagram {}", self.name, d.len()); dgram = Some(d); Active } Output::Callback(delay) => { - trace!("[{}] => callback {delay:?}", self.name); + qtrace!("[{}] => callback {delay:?}", self.name); assert_ne!(delay, Duration::new(0, 0)); Waiting(now + delay) } Output::None => { - trace!("[{}] => nothing", self.name); + qtrace!("[{}] => nothing", self.name); assert!(n.done(), "nodes should be done when they go idle"); Idle } @@ -232,7 +231,7 @@ impl Simulator { if dgram.is_none() { let next = self.next_time(now); if next > now { - info!( + qinfo!( "[{}] advancing time by {:?} to {:?}", self.name, next - now, @@ -248,7 +247,7 @@ impl Simulator { pub fn setup(mut self) -> ReadySimulator { let start = now(); - info!("{}: seed {}", self.name, self.rng.borrow().seed_str()); + qinfo!("{}: seed {}", self.name, self.rng.borrow().seed_str()); for n in &mut self.nodes { n.init(self.rng.clone(), start); } @@ -256,7 +255,7 @@ impl Simulator { let setup_start = Instant::now(); let now = self.process_loop(start, start); let setup_time = now - start; - info!( + qinfo!( "{t}: Setup took {wall:?} (wall) {setup_time:?} (simulated)", t = self.name, wall = setup_start.elapsed(), @@ -298,7 +297,7 @@ impl ReadySimulator { let real_start = Instant::now(); let end = self.sim.process_loop(self.start, self.now); let sim_time = end - self.now; - info!( + qinfo!( "{t}: Simulation took {wall:?} (wall) {sim_time:?} (simulated)", t = self.sim.name, wall = real_start.elapsed(), diff --git a/test-fixture/src/sim/taildrop.rs b/test-fixture/src/sim/taildrop.rs index 586eda7e55..b6e7466c59 100644 --- a/test-fixture/src/sim/taildrop.rs +++ b/test-fixture/src/sim/taildrop.rs @@ -11,8 +11,7 @@ use std::{ time::{Duration, Instant}, }; -use log::{info, trace}; -use neqo_common::Datagram; +use neqo_common::{qinfo, qtrace, Datagram}; use neqo_transport::Output; use super::Node; @@ -134,7 +133,7 @@ impl TailDrop { self.maxq = max(self.maxq, self.used); self.queue.push_back(d); } else { - trace!("taildrop dropping {} bytes", d.len()); + qtrace!("taildrop dropping {} bytes", d.len()); self.dropped += 1; } } @@ -176,9 +175,12 @@ impl Node for TailDrop { } fn print_summary(&self, test_name: &str) { - info!( + qinfo!( "{test_name}: taildrop: rx {} drop {} tx {} maxq {}", - self.received, self.dropped, self.delivered, self.maxq, + self.received, + self.dropped, + self.delivered, + self.maxq, ); } } From 69879bcefe9411e64d4f9a726aa8114907f48ce4 Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 15:49:34 +0200 Subject: [PATCH 7/9] Minimize diff --- Cargo.lock | 4 ++-- neqo-common/tests/log.rs | 27 +++++++++++++++++++++++++++ neqo-http3/src/stream_type_reader.rs | 1 + neqo-http3/tests/send_message.rs | 2 +- neqo-transport/src/cc/classic_cc.rs | 6 ++---- neqo-transport/src/connection/dump.rs | 4 ++-- neqo-transport/src/connection/mod.rs | 2 +- 7 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 neqo-common/tests/log.rs diff --git a/Cargo.lock b/Cargo.lock index 1a1e553639..240b4861de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -364,9 +364,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.10.2" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" +checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" dependencies = [ "is-terminal", "log", diff --git a/neqo-common/tests/log.rs b/neqo-common/tests/log.rs new file mode 100644 index 0000000000..9cdec162cd --- /dev/null +++ b/neqo-common/tests/log.rs @@ -0,0 +1,27 @@ +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use neqo_common::{qdebug, qerror, qinfo, qtrace, qwarn}; + +#[test] +fn basic() { + qerror!("error"); + qwarn!("warn"); + qinfo!("info"); + qdebug!("debug"); + qtrace!("trace"); +} + +#[test] +fn args() { + let num = 1; + let obj = std::time::Instant::now(); + qerror!("error {num} {obj:?}"); + qwarn!("warn {num} {obj:?}"); + qinfo!("info {num} {obj:?}"); + qdebug!("debug {num} {obj:?}"); + qtrace!("trace {num} {obj:?}"); +} diff --git a/neqo-http3/src/stream_type_reader.rs b/neqo-http3/src/stream_type_reader.rs index 7aa4caed4c..b65c2e4a1f 100644 --- a/neqo-http3/src/stream_type_reader.rs +++ b/neqo-http3/src/stream_type_reader.rs @@ -3,6 +3,7 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. + use neqo_common::{qtrace, Decoder, IncrementalDecoderUint, Role}; use neqo_qpack::{decoder::QPACK_UNI_STREAM_TYPE_DECODER, encoder::QPACK_UNI_STREAM_TYPE_ENCODER}; use neqo_transport::{Connection, StreamId, StreamType}; diff --git a/neqo-http3/tests/send_message.rs b/neqo-http3/tests/send_message.rs index e36e5dc982..19a47cde7c 100644 --- a/neqo-http3/tests/send_message.rs +++ b/neqo-http3/tests/send_message.rs @@ -23,7 +23,7 @@ fn response_header_no_data() -> &'static Vec
{ fn response_header_103() -> &'static Vec
{ static HEADERS: OnceLock> = OnceLock::new(); - HEADERS.get_or_init(|| vec![Header::new(":status", "103"), Header::new("link", "..")]) + HEADERS.get_or_init(|| vec![Header::new(":status", "103"), Header::new("link", "...")]) } fn exchange_packets(client: &mut Http3Client, server: &mut Http3Server) { diff --git a/neqo-transport/src/cc/classic_cc.rs b/neqo-transport/src/cc/classic_cc.rs index 6a8fbc877a..cd296f83f4 100644 --- a/neqo-transport/src/cc/classic_cc.rs +++ b/neqo-transport/src/cc/classic_cc.rs @@ -12,7 +12,8 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qdebug, qinfo, qtrace}; +use ::qlog::events::{quic::CongestionStateUpdated, EventData}; +use neqo_common::{const_max, const_min, qdebug, qinfo, qlog::NeqoQlog, qtrace}; use super::CongestionControl; use crate::{ @@ -23,9 +24,6 @@ use crate::{ sender::PACING_BURST_SIZE, Pmtud, }; -#[rustfmt::skip] // to keep `::` and thus prevent conflict with `crate::qlog` -use ::qlog::events::{quic::CongestionStateUpdated, EventData}; -use neqo_common::{const_max, const_min, qlog::NeqoQlog}; pub const CWND_INITIAL_PKTS: usize = 10; const PERSISTENT_CONG_THRESH: u32 = 3; diff --git a/neqo-transport/src/connection/dump.rs b/neqo-transport/src/connection/dump.rs index 82a5b93fd6..2719351771 100644 --- a/neqo-transport/src/connection/dump.rs +++ b/neqo-transport/src/connection/dump.rs @@ -5,7 +5,7 @@ // except according to those terms. // Enable just this file for logging to just see packets. -// e.g. "RUST_LOG=neqo_transport::dump neqo-client .." +// e.g. "RUST_LOG=neqo_transport::dump neqo-client ..." use std::fmt::Write; @@ -37,7 +37,7 @@ pub fn dump_packet( let mut d = Decoder::from(payload); while d.remaining() > 0 { let Ok(f) = Frame::decode(&mut d) else { - s.push_str(" [broken].."); + s.push_str(" [broken]..."); break; }; let x = f.dump(); diff --git a/neqo-transport/src/connection/mod.rs b/neqo-transport/src/connection/mod.rs index be4a0fb5e0..548dae76f0 100644 --- a/neqo-transport/src/connection/mod.rs +++ b/neqo-transport/src/connection/mod.rs @@ -3171,7 +3171,7 @@ impl Connection { fn set_connected(&mut self, now: Instant) -> Res<()> { qdebug!("[{self}] TLS connection complete"); if self.crypto.tls.info().map(SecretAgentInfo::alpn).is_none() { - qwarn!("[{self}] No ALPN. Closing connection"); + qwarn!("[{self}] No ALPN, closing connection"); // 120 = no_application_protocol return Err(Error::CryptoAlert(120)); } From ae0d462f76881094fe7db6db25b2a67d40ea62bf Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 15:55:57 +0200 Subject: [PATCH 8/9] machete --- neqo-bin/Cargo.toml | 3 +++ neqo-http3/Cargo.toml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/neqo-bin/Cargo.toml b/neqo-bin/Cargo.toml index ce8accbf0a..ebd9134bbb 100644 --- a/neqo-bin/Cargo.toml +++ b/neqo-bin/Cargo.toml @@ -54,6 +54,9 @@ tokio = { version = "1", default-features = false, features = ["sync"] } bench = ["neqo-transport/bench"] draft-29 = [] +[package.metadata.cargo-machete] +ignored = ["log"] + [lib] # See https://github.com/bheisler/criterion.rs/blob/master/book/src/faq.md#cargo-bench-gives-unrecognized-option-errors-for-valid-command-line-options bench = false diff --git a/neqo-http3/Cargo.toml b/neqo-http3/Cargo.toml index 93c76160bd..d92f32174b 100644 --- a/neqo-http3/Cargo.toml +++ b/neqo-http3/Cargo.toml @@ -36,6 +36,9 @@ test-fixture = { path = "../test-fixture" } disable-encryption = ["neqo-transport/disable-encryption", "neqo-crypto/disable-encryption"] draft-29 = [] +[package.metadata.cargo-machete] +ignored = ["log"] + [lib] # See https://github.com/bheisler/criterion.rs/blob/master/book/src/faq.md#cargo-bench-gives-unrecognized-option-errors-for-valid-command-line-options bench = false From 5ff2d827d101584137334bf2543725132daa8444 Mon Sep 17 00:00:00 2001 From: Lars Eggert Date: Wed, 18 Dec 2024 17:06:11 +0200 Subject: [PATCH 9/9] Make `#[clippy::format_args]` a TODO :-( --- neqo-common/src/log.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/neqo-common/src/log.rs b/neqo-common/src/log.rs index 65556f564f..74435be02e 100644 --- a/neqo-common/src/log.rs +++ b/neqo-common/src/log.rs @@ -57,27 +57,27 @@ pub fn init(level_filter: Option) { } #[macro_export] -#[clippy::format_args] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 macro_rules! qerror { ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::error!($($arg)*); } ); } #[macro_export] -#[clippy::format_args] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 macro_rules! qwarn { ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::warn!($($arg)*); } ); } #[macro_export] -#[clippy::format_args] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 macro_rules! qinfo { ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::info!($($arg)*); } ); } #[macro_export] -#[clippy::format_args] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 macro_rules! qdebug { ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::debug!($($arg)*); } ); } #[macro_export] -#[clippy::format_args] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 macro_rules! qtrace { ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::trace!($($arg)*); } ); }