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/Cargo.lock b/Cargo.lock index c104e7a109..a5a7a93983 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -398,7 +398,10 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" dependencies = [ + "is-terminal", "log", + "regex", + "termcolor", ] [[package]] @@ -1291,6 +1294,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 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-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(); diff --git a/neqo-bin/src/client/http09.rs b/neqo-bin/src/client/http09.rs index f7f62bf57a..904c8647d0 100644 --- a/neqo-bin/src/client/http09.rs +++ b/neqo-bin/src/client/http09.rs @@ -301,8 +301,7 @@ impl<'b> Handler<'b> { qdebug!("READ[{stream_id}]: {} bytes", read_buffer.len()); } else { qdebug!( - "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 3a5a777cb6..6e8fbaaf73 100644 --- a/neqo-bin/src/client/http3.rs +++ b/neqo-bin/src/client/http3.rs @@ -302,7 +302,7 @@ impl StreamHandler for DownloadStreamHandler { } else if let Ok(txt) = std::str::from_utf8(data) { qdebug!("READ[{stream_id}]: {txt}"); } else { - qdebug!("READ[{}]: 0x{}", stream_id, hex(data)); + qdebug!("READ[{stream_id}]: 0x{}", hex(data)); } if fin { @@ -344,7 +344,7 @@ impl StreamHandler for UploadStreamHandler { qinfo!("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 24102cd283..d35d53da7f 100644 --- a/neqo-bin/src/client/mod.rs +++ b/neqo-bin/src/client/mod.rs @@ -462,7 +462,7 @@ impl<'a, H: Handler> Runner<'a, H> { self.socket.send(&dgram)?; } Output::Callback(new_timeout) => { - qdebug!("Setting timeout of {:?}", new_timeout); + qdebug!("Setting timeout of {new_timeout:?}"); self.timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); break; } @@ -553,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 { - qerror!("Resumption to {host} cannot work without at least 2 URLs."); + qerror!("Resumption to {host} cannot work without at least 2 URLs"); exit(127); } @@ -570,10 +570,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(); qinfo!( - "{} 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 1a9f981780..822be1acc4 100644 --- a/neqo-bin/src/lib.rs +++ b/neqo-bin/src/lib.rs @@ -163,9 +163,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 e183a1b045..c56412a5fb 100644 --- a/neqo-bin/src/server/http09.rs +++ b/neqo-bin/src/server/http09.rs @@ -82,17 +82,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); + qdebug!("Saving partial URL: {url_dbg}"); self.read_state.insert(stream_id, partial); } else { - qdebug!("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() { - qdebug!("Stream {} not client-initiated bidi, ignoring", stream_id); + qdebug!("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 1b6384df0d..ad187f0396 100644 --- a/neqo-bin/src/server/mod.rs +++ b/neqo-bin/src/server/mod.rs @@ -251,7 +251,7 @@ impl ServerRunner { socket.send(&dgram)?; } Output::Callback(new_timeout) => { - qdebug!("Setting timeout of {:?}", new_timeout); + qdebug!("Setting timeout of {new_timeout:?}"); *timeout = Some(Box::pin(tokio::time::sleep(new_timeout))); break; } @@ -360,7 +360,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."); + qwarn!("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/Cargo.toml b/neqo-common/Cargo.toml index 4022befd9b..80771aafa5 100644 --- a/neqo-common/Cargo.toml +++ b/neqo-common/Cargo.toml @@ -18,7 +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 } +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/log.rs b/neqo-common/src/log.rs index 04028a26bd..74435be02e 100644 --- a/neqo-common/src/log.rs +++ b/neqo-common/src/log.rs @@ -14,37 +14,6 @@ use std::{ 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() @@ -64,52 +33,51 @@ pub fn 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(), + "{} {} {}", + 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() { - do_log!(::log::Level::Warn, "Logging initialization error {:?}", e); + eprintln!("Logging initialization error {e:?}"); } else { - do_log!(::log::Level::Debug, "Logging initialized"); + ::log::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] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 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)*); } ); + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::error!($($arg)*); } ); } #[macro_export] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 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)*); } ); + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::warn!($($arg)*); } ); } #[macro_export] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 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)*); } ); + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::info!($($arg)*); } ); } #[macro_export] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 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)*); } ); + ($($arg:tt)*) => ( { ::neqo_common::log::init(None); ::log::debug!($($arg)*); } ); } #[macro_export] +// TODO: Enable `#[clippy::format_args]` once our MSRV is >= 1.84 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)*); } ); + ($($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 5f7b5dca3d..0b2b4ad250 100644 --- a/neqo-common/src/qlog.rs +++ b/neqo-common/src/qlog.rs @@ -149,11 +149,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, - "Qlog event generation failed with error {}; closing qlog.", - e - ); + log::error!("Qlog event generation failed with error {e}; closing qlog."); *self.inner.borrow_mut() = None; } } @@ -169,7 +165,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); + log::error!("Error dropping NeqoQlog: {e}"); } } } diff --git a/neqo-common/tests/log.rs b/neqo-common/tests/log.rs index 135a667146..9cdec162cd 100644 --- a/neqo-common/tests/log.rs +++ b/neqo-common/tests/log.rs @@ -19,40 +19,9 @@ fn basic() { 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"); + qerror!("error {num} {obj:?}"); + qwarn!("warn {num} {obj:?}"); + qinfo!("info {num} {obj:?}"); + qdebug!("debug {num} {obj:?}"); + qtrace!("trace {num} {obj:?}"); } diff --git a/neqo-crypto/src/agent.rs b/neqo-crypto/src/agent.rs index b3e76ca39b..ad351c4cc2 100644 --- a/neqo-crypto/src/agent.rs +++ b/neqo-crypto/src/agent.rs @@ -107,7 +107,7 @@ fn get_alpn(fd: *mut ssl::PRFileDesc, pre: bool) -> Res> { } _ => None, }; - qtrace!([format!("{fd:p}")], "got ALPN {:?}", alpn); + qtrace!("[{fd:p}] got ALPN {alpn:?}"); Ok(alpn) } @@ -369,7 +369,7 @@ impl SecretAgent { if st.is_none() { *st = Some(alert.description); } else { - qwarn!([format!("{fd:p}")], "duplicate alert {}", alert.description); + qwarn!("[{fd:p}] duplicate alert {}", alert.description); } } } @@ -429,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 { - qwarn!([self], "Cannot enable ciphers in state {:?}", self.state); + qwarn!("[{self}] Cannot enable ciphers in state {:?}", self.state); return Err(Error::InternalError); } @@ -644,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); - qwarn!([self], "error: {:?}", e); + qwarn!("[{self}] error: {e:?}"); self.state = HandshakeState::Failed(e.clone()); Err(e) } else { @@ -669,7 +669,7 @@ impl SecretAgent { let info = self.capture_error(SecretAgentInfo::new(self.fd))?; HandshakeState::Complete(info) }; - qdebug!([self], "state -> {:?}", self.state); + qdebug!("[{self}] state -> {:?}", self.state); Ok(()) } @@ -729,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) }); - qdebug!([self], "SSL_AuthCertificateComplete: {:?}", result); + qdebug!("[{self}] SSL_AuthCertificateComplete: {result:?}"); // This should return SECSuccess, so don't use update_state(). self.capture_error(result)?; } @@ -891,11 +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)); - qdebug!( - [format!("{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); @@ -965,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(); - qdebug!([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)) } @@ -1175,7 +1171,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)); + 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 f2173bfd8d..7bf14f941b 100644 --- a/neqo-crypto/src/agentio.rs +++ b/neqo-crypto/src/agentio.rs @@ -52,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<()> { - qtrace!("write {:?}", self); + qtrace!("write {self:?}"); unsafe { ssl::SSL_RecordLayerData( fd, @@ -177,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) }; - qtrace!([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); @@ -186,7 +186,7 @@ impl AgentIoInput { } fn reset(&mut self) { - qtrace!([self], "reset"); + qtrace!("[{self}] reset"); self.input = null(); self.available = 0; } @@ -230,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) }; - qtrace!([self], "save output {}", hex(slice)); + qtrace!("[{self}] save output {}", hex(slice)); self.output.extend_from_slice(slice); } pub fn take_output(&mut self) -> Vec { - qtrace!([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 80609f5316..73b78173e0 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 { - qerror!([format!("{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 76fd362c14..29c4d2a370 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)?; - qtrace!("Generated key pair: sk={:?} pk={:?}", sk, pk); + qtrace!("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 3d637fb958..5d17d5fcde 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) { - qdebug!("{:?} secret available for {:?}: {:?}", dir, 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 1618a971a9..7e5c6bb964 100644 --- a/neqo-crypto/src/selfencrypt.rs +++ b/neqo-crypto/src/selfencrypt.rs @@ -61,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; - qinfo!(["SelfEncrypt"], "Rotated keys to {}", self.key_id); + qinfo!("[SelfEncrypt] Rotated keys to {}", self.key_id); Ok(()) } @@ -99,8 +99,7 @@ impl SelfEncrypt { output.resize(encoded_len, 0); cipher.encrypt(0, extended_aad.as_ref(), plaintext, &mut output[offset..])?; qtrace!( - ["SelfEncrypt"], - "seal {} {} -> {}", + "[SelfEncrypt] seal {} {} -> {}", hex(aad), hex(plaintext), hex(&output) @@ -150,8 +149,7 @@ impl SelfEncrypt { let final_len = decrypted.len(); output.truncate(final_len); qtrace!( - ["SelfEncrypt"], - "open {} {} -> {}", + "[SelfEncrypt] open {} {} -> {}", hex(aad), hex(ciphertext), hex(&output) 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/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 diff --git a/neqo-http3/src/buffered_send_stream.rs b/neqo-http3/src/buffered_send_stream.rs index 4d1ef3511b..292a1495fe 100644 --- a/neqo-http3/src/buffered_send_stream.rs +++ b/neqo-http3/src/buffered_send_stream.rs @@ -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."); + qtrace!("[{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 b55f31c55d..6efabcb4a3 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 a59b6908e7..b098c1b5fc 100644 --- a/neqo-http3/src/connection.rs +++ b/neqo-http3/src/connection.rs @@ -352,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<()> { - qdebug!([self], "Initialize the http3 connection."); + qdebug!("[{self}] Initialize the http3 connection"); self.control_stream_local.create(conn)?; self.send_settings(); @@ -361,7 +361,7 @@ impl Http3Connection { } fn send_settings(&mut self) { - qdebug!([self], "Send settings."); + qdebug!("[{self}] Send settings"); self.control_stream_local.queue_frame(&HFrame::Settings { settings: HSettings::from(&self.local_params), }); @@ -374,7 +374,7 @@ impl Http3Connection { } fn create_qpack_streams(&self, conn: &mut Connection) -> Res<()> { - qdebug!([self], "create_qpack_streams."); + qdebug!("[{self}] create_qpack_streams"); self.qpack_encoder .borrow_mut() .add_send_stream(conn.stream_create(StreamType::UniDi)?); @@ -458,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) { - qtrace!([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)), @@ -468,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 { - qtrace!([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); @@ -485,7 +485,7 @@ impl Http3Connection { conn: &mut Connection, ) -> Res<()> { for stream_id in unblocked_streams { - qdebug!([self], "Stream {} is unblocked", stream_id); + qdebug!("[{self}] Stream {stream_id} is unblocked"); if let Some(r) = self.recv_streams.get_mut(&stream_id) { let res = r .http_stream() @@ -551,12 +551,7 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!( - [self], - "Handle a stream reset stream_id={} app_err={}", - stream_id, - 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) } @@ -567,12 +562,7 @@ impl Http3Connection { app_error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!( - [self], - "Handle stream_stop_sending stream_id={} app_err={}", - stream_id, - 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); @@ -585,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 { - qdebug!([self], "Handle state change {:?}", state); + qdebug!("[{self}] Handle state change {state:?}"); match state { State::Handshaking => { if self.role == Role::Server @@ -649,7 +639,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)) } } @@ -696,15 +686,10 @@ impl Http3Connection { } NewStreamType::Push(push_id) => { - qinfo!( - [self], - "A new push stream {} push_id:{}.", - stream_id, - push_id - ); + qinfo!("[{self}] A new push stream {stream_id} push_id:{push_id}"); } NewStreamType::Decoder => { - qdebug!([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, @@ -715,7 +700,7 @@ impl Http3Connection { ); } NewStreamType::Encoder => { - qdebug!([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, @@ -726,7 +711,7 @@ impl Http3Connection { ); } NewStreamType::Http(_) => { - qinfo!([self], "A new http stream {}.", stream_id); + qinfo!("[{self}] A new http stream {stream_id}"); } NewStreamType::WebTransportStream(session_id) => { let session_exists = self @@ -739,12 +724,7 @@ 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 - ); + qinfo!("[{self}] A new WebTransport stream {stream_id} for session {session_id}"); } NewStreamType::Unknown => { conn.stream_stop_sending(stream_id, Error::HttpStreamCreation.code())?; @@ -764,7 +744,7 @@ impl Http3Connection { /// This is called when an application closes the connection. pub fn close(&mut self, error: AppError) { - qdebug!([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) { qwarn!("close(0) called when streams still active"); @@ -850,8 +830,7 @@ impl Http3Connection { T: AsRequestTarget<'t> + ?Sized + Debug, { qinfo!( - [self], - "Fetch method={} target: {:?}", + "[{self}] Fetch method={} target: {:?}", request.method, request.target, ); @@ -951,7 +930,7 @@ impl Http3Connection { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - qdebug!([self], "read_data from stream {}.", stream_id); + qdebug!("[{self}] read_data from stream {stream_id}"); let res = self .recv_streams .get_mut(&stream_id) @@ -968,12 +947,7 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - qinfo!( - [self], - "Reset sending side of stream {} error={}.", - stream_id, - error - ); + qinfo!("[{self}] Reset sending side of stream {stream_id} error={error}"); if self.send_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); @@ -990,12 +964,7 @@ impl Http3Connection { stream_id: StreamId, error: AppError, ) -> Res<()> { - qinfo!( - [self], - "Send stop sending for stream {} error={}.", - stream_id, - error - ); + qinfo!("[{self}] Send stop sending for stream {stream_id} error={error}"); if self.recv_stream_is_critical(stream_id) { return Err(Error::InvalidStreamId); } @@ -1043,7 +1012,7 @@ impl Http3Connection { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "cancel_fetch {} error={}.", stream_id, 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) { @@ -1090,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<()> { - qdebug!([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 @@ -1117,7 +1086,7 @@ impl Http3Connection { where T: AsRequestTarget<'x> + ?Sized + Debug, { - qinfo!([self], "Create WebTransport"); + qinfo!("[{self}] Create WebTransport"); if !self.webtransport_enabled() { return Err(Error::Unavailable); } @@ -1158,10 +1127,7 @@ impl Http3Connection { events: Box, accept_res: &WebTransportSessionAcceptAction, ) -> Res<()> { - qtrace!( - "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); } @@ -1237,7 +1203,7 @@ impl Http3Connection { error: u32, message: &str, ) -> Res<()> { - qtrace!("Close WebTransport session {:?}", session_id); + qtrace!("Close WebTransport session {session_id:?}"); let send_stream = self .send_streams .get_mut(&session_id) @@ -1263,11 +1229,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res { - qtrace!( - "Create new WebTransport stream session={} type={:?}", - session_id, - stream_type - ); + qtrace!("Create new WebTransport stream session={session_id} type={stream_type:?}"); let wt = self .recv_streams @@ -1304,11 +1266,7 @@ impl Http3Connection { send_events: Box, recv_events: Box, ) -> Res<()> { - qtrace!( - "Create new WebTransport stream session={} stream_id={}", - session_id, - stream_id - ); + qtrace!("Create new WebTransport stream session={session_id} stream_id={stream_id}"); let wt = self .recv_streams @@ -1401,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> { - qdebug!([self], "Handle a control frame {:?}", f); + qdebug!("[{self}] Handle a control frame {f:?}"); if !matches!(f, HFrame::Settings { .. }) && !matches!( self.settings_state, @@ -1432,7 +1390,7 @@ impl Http3Connection { } fn handle_settings(&mut self, new_settings: HSettings) -> Res<()> { - qdebug!([self], "Handle SETTINGS frame."); + qdebug!("[{self}] Handle SETTINGS frame"); match &self.settings_state { Http3RemoteSettingsState::NotReceived => { self.set_qpack_settings(&new_settings)?; @@ -1455,11 +1413,7 @@ impl Http3Connection { } if zero_rtt_value > new_value { qerror!( - [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); } @@ -1478,7 +1432,7 @@ impl Http3Connection { } } if qpack_changed { - qdebug!([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); @@ -1577,7 +1531,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); + 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) { @@ -1586,7 +1540,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); + 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 f23abee831..85040a841b 100644 --- a/neqo-http3/src/connection_client.rs +++ b/neqo-http3/src/connection_client.rs @@ -144,7 +144,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={?}]", @@ -454,7 +454,7 @@ impl Http3Client { let Some(settings_slice) = dec.decode_vvec() else { return Err(Error::InvalidResumptionToken); }; - qtrace!([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( @@ -462,7 +462,7 @@ impl Http3Client { Error::InvalidResumptionToken, )?; let tok = dec.decode_remainder(); - qtrace!([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(); @@ -489,7 +489,7 @@ impl Http3Client { where S: AsRef + Display, { - qinfo!([self], "Close the connection error={} msg={}.", error, msg); + qinfo!("[{self}] Close the connection error={error} msg={msg}"); if !matches!( self.base_handler.state, Http3State::Closing(_) | Http3State::Closed(_) @@ -577,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<()> { - qinfo!([self], "reset_stream {} error={}.", stream_id, error); + qinfo!("[{self}] reset_stream {stream_id} error={error}"); self.base_handler .cancel_fetch(stream_id, error, &mut self.conn) } @@ -588,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<()> { - qdebug!([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) } @@ -597,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<()> { - qinfo!([self], "stream_reset_send {} error={}.", stream_id, error); + qinfo!("[{self}] stream_reset_send {stream_id} error={error}"); self.base_handler .stream_reset_send(&mut self.conn, stream_id, error) } @@ -606,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<()> { - qinfo!([self], "stream_stop_sending {} error={}.", stream_id, error); + qinfo!("[{self}] stream_stop_sending {stream_id} error={error}"); self.base_handler .stream_stop_sending(&mut self.conn, stream_id, error) } @@ -625,9 +625,7 @@ impl Http3Client { /// supplied. pub fn send_data(&mut self, stream_id: StreamId, buf: &[u8]) -> Res { qinfo!( - [self], - "send_data from stream {} sending {} bytes.", - stream_id, + "[{self}] end_data from stream {stream_id} sending {} bytes", buf.len() ); self.base_handler @@ -650,7 +648,7 @@ impl Http3Client { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - qdebug!([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() { @@ -775,7 +773,7 @@ impl Http3Client { buf: &[u8], id: impl Into, ) -> Res<()> { - qtrace!("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) } @@ -854,7 +852,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."); + qtrace!("[{self}] Process"); if let Some(d) = dgram { self.process_input(d, now); } @@ -881,7 +879,7 @@ impl Http3Client { now: Instant, ) { let mut dgrams = dgrams.into_iter().peekable(); - qtrace!([self], "Process multiple datagrams"); + qtrace!("[{self}] Process multiple datagrams"); if dgrams.peek().is_none() { return; } @@ -895,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) { - qtrace!([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(); @@ -944,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 { - qtrace!([self], "Process output."); + qtrace!("[{self}] Process output"); // Maybe send() stuff on http3-managed streams self.process_http3(now); @@ -962,7 +960,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."); + qinfo!("[{self}] Connection error: goaway stream_id increased"); self.close( now, Error::HttpGeneralProtocol.code(), @@ -971,7 +969,7 @@ impl Http3Client { true } Err(e) => { - qinfo!([self], "Connection error: {}.", e); + qinfo!("[{self}] Connection error: {e}"); self.close(now, e.code(), format!("{e}")); true } @@ -994,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<()> { - qtrace!([self], "Check connection events."); + qtrace!("[{self}] Check connection events"); while let Some(e) = self.conn.next_event() { - qdebug!([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 @@ -1120,7 +1118,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" ); } }?; @@ -1178,7 +1176,7 @@ impl Http3Client { } fn handle_goaway(&mut self, goaway_stream_id: StreamId) -> Res<()> { - qinfo!([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); @@ -1195,7 +1193,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 @@ -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(); - qtrace!(["TestServer"], "control stream: {}", control); + qtrace!("[TestServer] control stream: {control}"); self.control_stream_id = Some(control); // Send stream type on the control stream. assert_eq!( @@ -3114,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"); @@ -3248,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; @@ -3295,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, @@ -4156,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)); @@ -4277,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)); @@ -4338,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()); @@ -7210,7 +7208,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 f06cf272ba..6c0d843f3f 100644 --- a/neqo-http3/src/connection_server.rs +++ b/neqo-http3/src/connection_server.rs @@ -102,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<()> { - qdebug!([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(()) @@ -120,7 +120,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "cancel_fetch {} error={}.", stream_id, error); + qinfo!("[{self}] cancel_fetch {stream_id} error={error}"); self.needs_processing = true; self.base_handler.cancel_fetch(stream_id, error, conn) } @@ -131,7 +131,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "stream_stop_sending {} error={}.", stream_id, error); + qinfo!("[{self}] stream_stop_sending {stream_id} error={error}"); self.needs_processing = true; self.base_handler .stream_stop_sending(conn, stream_id, error) @@ -143,7 +143,7 @@ impl Http3ServerHandler { error: AppError, conn: &mut Connection, ) -> Res<()> { - qinfo!([self], "stream_reset_send {} error={}.", stream_id, error); + qinfo!("[{self}] stream_reset_send {stream_id} error={error}"); self.needs_processing = true; self.base_handler.stream_reset_send(conn, stream_id, error) } @@ -215,7 +215,7 @@ impl Http3ServerHandler { /// Process HTTTP3 layer. pub fn process_http3(&mut self, conn: &mut Connection, now: Instant) { - qtrace!([self], "Process http3 internal."); + qtrace!("[{self}] Process http3 internal"); if matches!(self.base_handler.state(), Http3State::Closed(..)) { return; } @@ -254,7 +254,7 @@ impl Http3ServerHandler { } fn close(&mut self, conn: &mut Connection, now: Instant, err: &Error) { - qinfo!([self], "Connection error: {}.", err); + qinfo!("[{self}] Connection error: {err}"); conn.close(now, err.code(), format!("{err}")); self.base_handler.close(err.code()); self.events @@ -263,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<()> { - qtrace!([self], "Check connection events."); + qtrace!("[{self}] Check connection events"); while let Some(e) = conn.next_event() { - qdebug!([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); @@ -387,7 +387,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" ), }?; } @@ -411,7 +411,7 @@ impl Http3ServerHandler { stream_id: StreamId, buf: &mut [u8], ) -> Res<(usize, bool)> { - qdebug!([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 92d12ef97f..db30df1950 100644 --- a/neqo-http3/src/control_stream_local.rs +++ b/neqo-http3/src/control_stream_local.rs @@ -92,7 +92,7 @@ impl ControlStreamLocal { /// Create a control stream. pub fn create(&mut self, conn: &mut Connection) -> Res<()> { - qtrace!([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 ef2bf96d5b..644e3b55d8 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> { - qdebug!([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) => { - qdebug!([self], "received {:?}", s); + qdebug!("[{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 ea8a87659c..a7d7262e75 100644 --- a/neqo-http3/src/features/extended_connect/webtransport_session.rs +++ b/neqo-http3/src/features/extended_connect/webtransport_session.rs @@ -146,7 +146,7 @@ impl WebTransportSession { } fn receive(&mut self, conn: &mut Connection) -> Res<(ReceiveOutput, bool)> { - qtrace!([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(); @@ -229,11 +229,7 @@ impl WebTransportSession { if let Some((headers, interim, fin)) = self.stream_event_listener.borrow_mut().get_headers() { - qtrace!( - "ExtendedConnect response headers {:?}, fin={}", - headers, - fin - ); + qtrace!("ExtendedConnect response headers {headers:?}, fin={fin}"); if interim { if fin { @@ -346,7 +342,7 @@ impl WebTransportSession { &mut self.control_stream_recv, )) .map_err(|_| Error::HttpGeneralProtocolStream)?; - qtrace!([self], "Received frame: {:?} fin={}", f, fin); + qtrace!("[{self}] Received frame: {f:?} fin={fin}"); if let Some(WebTransportFrame::CloseSession { error, message }) = f { self.events.session_end( ExtendedConnectType::WebTransport, @@ -410,7 +406,7 @@ impl WebTransportSession { buf: &[u8], id: impl Into, ) -> Res<()> { - qtrace!([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 c44ff8eacd..e9b41b7b05 100644 --- a/neqo-http3/src/features/mod.rs +++ b/neqo-http3/src/features/mod.rs @@ -63,8 +63,7 @@ impl NegotiationState { } = self { qtrace!( - "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 05c3e240fe..77619e8d2d 100644 --- a/neqo-http3/src/frames/hframe.rs +++ b/neqo-http3/src/frames/hframe.rs @@ -174,7 +174,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 6d2c0614b0..445988691d 100644 --- a/neqo-http3/src/frames/reader.rs +++ b/neqo-http3/src/frames/reader.rs @@ -173,7 +173,7 @@ impl FrameReader { { (0, f) => (None, false, f), (amount, f) => { - qtrace!("FrameReader::receive: reading {} byte, fin={}", amount, f); + qtrace!("FrameReader::receive: reading {amount} byte, fin={f}"); (self.consume::(Decoder::from(&buf[..amount]))?, true, f) } }; @@ -203,16 +203,15 @@ impl FrameReader { match &mut self.state { FrameReaderState::GetType { decoder } => { if let Some(v) = decoder.consume(&mut input) { - qtrace!("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) { qtrace!( - "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 564b149c2b..82311fa522 100644 --- a/neqo-http3/src/push_controller.rs +++ b/neqo-http3/src/push_controller.rs @@ -186,10 +186,7 @@ impl PushController { new_headers: Vec
, ) -> Res<()> { qtrace!( - [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 +194,7 @@ impl PushController { match self.push_streams.get_mut(push_id) { None => { - qtrace!("Push has been closed already {}.", push_id); + qtrace!("Push has been closed already {push_id}"); Ok(()) } Some(push_state) => match push_state { @@ -237,17 +234,12 @@ impl PushController { } pub fn add_new_push_stream(&mut self, push_id: PushId, stream_id: StreamId) -> Res { - qtrace!( - "A new push stream with push_id={} stream_id={}", - push_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( || { - qinfo!("Push has been closed already."); + qinfo!("Push has been closed already"); Ok(false) }, |push_state| match push_state { @@ -269,7 +261,7 @@ impl PushController { // The following state have already have a push stream: // PushState::OnlyPushStream | PushState::Active _ => { - qerror!("Duplicate push stream."); + qerror!("Duplicate push stream"); Err(Error::HttpId) } }, @@ -279,7 +271,7 @@ impl PushController { fn check_push_id(&self, push_id: PushId) -> 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."); + qerror!("Push id is greater than current_max_push_id"); Err(Error::HttpId) } else { Ok(()) @@ -292,13 +284,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - qtrace!("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 => { - qtrace!("Push has already been closed (push_id={}).", push_id); + qtrace!("Push has already been closed (push_id={push_id})"); Ok(()) } Some(ps) => match ps { @@ -325,7 +317,7 @@ impl PushController { } pub fn close(&mut self, push_id: PushId) { - qtrace!("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 { @@ -339,13 +331,13 @@ impl PushController { conn: &mut Connection, base_handler: &mut Http3Connection, ) -> Res<()> { - qtrace!("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 => { - qtrace!("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. @@ -378,8 +370,7 @@ impl PushController { } pub fn push_stream_reset(&mut self, push_id: PushId, close_type: CloseType) { - qtrace!("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 { PushState::OnlyPushStream { .. } => { @@ -397,7 +388,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 +429,7 @@ impl PushController { pub fn new_stream_event(&mut self, push_id: PushId, 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 406bca0466..03f9b54cdd 100644 --- a/neqo-http3/src/recv_message.rs +++ b/neqo-http3/src/recv_message.rs @@ -126,7 +126,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(()) } @@ -146,13 +146,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<()> { - qtrace!([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)?, @@ -199,7 +199,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); + qtrace!( + "[{self}] set_state_to_close_pending: state={:?}", + self.state + ); match self.state { RecvMessageState::WaitingForResponseHeaders { .. } => { @@ -212,7 +215,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; @@ -250,9 +253,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); + qdebug!("[{self}] state={:?}", self.state); match &mut self.state { // In the following 3 states we need to read frames. RecvMessageState::WaitingForResponseHeaders { frame_reader } @@ -268,11 +270,7 @@ impl RecvMessage { (None, false) => break Ok(()), (Some(frame), fin) => { qdebug!( - [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,8 +305,7 @@ impl RecvMessage { && !self.blocked_push_promise.is_empty() { qinfo!( - [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(()); } @@ -326,7 +323,7 @@ impl RecvMessage { break Ok(()); } } else { - qinfo!([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 378786d12f..3fbaefa5a6 100644 --- a/neqo-http3/src/send_message.rs +++ b/neqo-http3/src/send_message.rs @@ -119,7 +119,7 @@ impl SendMessage { encoder: Rc>, conn_events: Box, ) -> Self { - qdebug!("Create a request stream_id={}", stream_id); + qdebug!("Create a request stream_id={stream_id}"); Self { state: MessageState::WaitingForHeaders, message_type, @@ -166,7 +166,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()); + qtrace!("[{self}] send_body: len={}", buf.len()); self.state.new_data()?; @@ -200,12 +200,7 @@ impl SendStream for SendMessage { min(buf.len(), available - 9) }; - qdebug!( - [self], - "send_request_body: available={} to_send={}.", - available, - to_send - ); + qdebug!("[{self}] send_request_body: available={available} to_send={to_send}"); let data_frame = HFrame::Data { len: to_send as u64, @@ -250,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))?; - qtrace!([self], "{} bytes sent", 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), )?; - qtrace!([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 8a5dc8a2f3..346bc856e6 100644 --- a/neqo-http3/src/server.rs +++ b/neqo-http3/src/server.rs @@ -119,13 +119,13 @@ impl Http3Server { } pub fn process(&mut self, dgram: Option>>, now: Instant) -> Output { - qtrace!([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) => { - qtrace!([self], "Send packet: {:?}", d); + qtrace!("[{self}] Send packet: {d:?}"); Output::Datagram(d) } _ => self.server.process(Option::::None, now), @@ -134,7 +134,7 @@ impl Http3Server { /// Process HTTP3 layer. fn process_http3(&mut self, now: Instant) { - qtrace!([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 3f174ba0a0..40ff04a002 100644 --- a/neqo-http3/src/server_events.rs +++ b/neqo-http3/src/server_events.rs @@ -35,7 +35,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) } } @@ -115,10 +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:{}.", - 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,10 +132,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:{}.", - 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(), @@ -152,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<()> { - qdebug!([self], "reset error:{}.", app_error); + qdebug!("[{self}] reset error:{app_error}"); self.handler.borrow_mut().cancel_fetch( self.stream_info.stream_id(), app_error, @@ -202,7 +198,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."); + qdebug!("[{self}] Set new response"); self.stream_handler.send_data(data) } @@ -212,7 +208,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."); + qdebug!("[{self}] Set new response"); self.stream_handler.stream_close_send() } } @@ -283,7 +279,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."); + 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 5c5fe75943..1d580e80d2 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); }; - qtrace!("Decoded uint {}", output); + qtrace!("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; - qtrace!("New Stream stream push_id={}", output); + qtrace!("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 2e52739fcb..e14fdc97fe 100644 --- a/neqo-http3/tests/httpconn.rs +++ b/neqo-http3/tests/httpconn.rs @@ -433,7 +433,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-qpack/src/decoder.rs b/neqo-qpack/src/decoder.rs index ed1d0b8a18..fc7a37eab7 100644 --- a/neqo-qpack/src/decoder.rs +++ b/neqo-qpack/src/decoder.rs @@ -40,7 +40,7 @@ impl QPackDecoder { /// If settings include invalid values. #[must_use] pub fn new(qpack_settings: &QpackSettings) -> Self { - qdebug!("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 { @@ -139,14 +139,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<()> { - qdebug!([self], "received instruction capacity cap={}", cap); + qdebug!("[{self}] received instruction capacity cap={cap}"); if cap > self.max_table_size { return Err(Error::EncoderStream); } @@ -186,7 +186,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); + qdebug!("[{self}] {r} bytes sent"); self.send_buf.read(r); } Ok(()) @@ -214,7 +214,7 @@ impl QPackDecoder { buf: &[u8], stream_id: StreamId, ) -> Res>> { - qdebug!([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 f69f9da3ac..db9cf5039d 100644 --- a/neqo-qpack/src/decoder_instructions.rs +++ b/neqo-qpack/src/decoder_instructions.rs @@ -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"); + 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)?; - qtrace!([self], "varint read {}", val); + qtrace!("[{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 5ca8e71c4e..7d4f63ee5f 100644 --- a/neqo-qpack/src/encoder.rs +++ b/neqo-qpack/src/encoder.rs @@ -93,9 +93,7 @@ impl QPackEncoder { } qdebug!( - [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, ); @@ -129,7 +127,7 @@ impl QPackEncoder { } fn read_instructions(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> { - qdebug!([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) { @@ -172,7 +170,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 +201,7 @@ impl QPackEncoder { } fn call_instruction(&mut self, instruction: DecoderInstruction, qlog: &NeqoQlog) -> Res<()> { - qdebug!([self], "call instruction {:?}", instruction); + qdebug!("[{self}] call instruction {instruction:?}"); match instruction { DecoderInstruction::InsertCountIncrement { increment } => { qlog::qpack_read_insert_count_increment_instruction( @@ -247,7 +245,7 @@ impl QPackEncoder { name: &[u8], value: &[u8], ) -> Res { - qdebug!([self], "insert {:?} {:?}.", name, value); + qdebug!("[{self}] insert {name:?} {value:?}"); let entry_size = name.len() + value.len() + ADDITIONAL_TABLE_ENTRY_SIZE; @@ -280,7 +278,7 @@ impl QPackEncoder { } fn change_capacity(&mut self, value: u64) { - qdebug!([self], "change capacity: {}", value); + qdebug!("[{self}] change capacity: {value}"); self.next_capacity = Some(value); } @@ -321,7 +319,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."); + qerror!("Send call but there is no stream yet"); Ok(()) } LocalStreamState::Uninitialized(stream_id) => { @@ -368,7 +366,7 @@ impl QPackEncoder { h: &[Header], stream_id: StreamId, ) -> HeaderEncoder { - qdebug!([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 @@ -393,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(); - qtrace!("encoding {:x?} {:x?}.", name, value); + qtrace!("encoding {name:x?} {value:x?}"); if let Some(LookupResult { index, @@ -402,10 +400,8 @@ impl QPackEncoder { }) = self.table.lookup(&name, &value, can_block) { qtrace!( - [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 3fba5c2d96..55e13cc9e4 100644 --- a/neqo-qpack/src/encoder_instructions.rs +++ b/neqo-qpack/src/encoder_instructions.rs @@ -174,9 +174,9 @@ 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"); }; - qdebug!([self], "instruction decoded"); + qdebug!("[{self}] instruction decoded"); } fn decode_instruction_type(&mut self, recv: &mut T) -> Res<()> { @@ -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(()) @@ -220,7 +220,7 @@ impl EncoderInstructionReader { &mut self, recv: &mut T, ) -> Res { - qdebug!([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)?; - qtrace!([self], "First varint read {}", val); + qtrace!("[{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)?; - qtrace!([self], "first literal read {:?}", val); + qtrace!("[{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)?; - qtrace!([self], "second literal read {:?}", val); + qtrace!("[{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 d2eab95e3e..3c3a1ec274 100644 --- a/neqo-qpack/src/header_block.rs +++ b/neqo-qpack/src/header_block.rs @@ -60,7 +60,7 @@ impl HeaderEncoder { } pub fn encode_indexed_static(&mut self, index: u64) { - qtrace!([self], "encode static index {}.", index); + qtrace!("[{self}] encode static index {index}"); self.buf .encode_prefixed_encoded_int(HEADER_FIELD_INDEX_STATIC, index); } @@ -76,7 +76,7 @@ impl HeaderEncoder { } pub fn encode_indexed_dynamic(&mut self, index: u64) { - qtrace!([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); @@ -88,13 +88,7 @@ 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?}", - index, - is_static, - value - ); + 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); @@ -116,12 +110,7 @@ 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?}.", - name, - value - ); + 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); @@ -148,13 +137,9 @@ impl HeaderEncoder { } }); qtrace!( - [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 @@ -224,8 +209,7 @@ impl<'a> HeaderDecoder<'a> { if table.base() < self.req_insert_cnt { qtrace!( - [self], - "decoding is blocked, requested inserts count={}", + "[{self}] decoding is blocked, requested inserts count={}", self.req_insert_cnt ); return Ok(HeaderDecoderResult::Blocked(self.req_insert_cnt)); @@ -274,7 +258,7 @@ impl<'a> HeaderDecoder<'a> { } } - qtrace!([self], "done decoding header block."); + qtrace!("[{self}] done decoding header block"); Ok(HeaderDecoderResult::Headers(h)) } @@ -300,8 +284,7 @@ impl<'a> HeaderDecoder<'a> { .ok_or(Error::DecompressionFailed)? }; qtrace!( - [self], - "requested inserts count is {} and base is {}", + "[{self}] requested inserts count is {} and base is {}", self.req_insert_cnt, self.base ); @@ -335,7 +318,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_STATIC.len())?; - qtrace!([self], "decoder static indexed {}.", index); + qtrace!("[{self}] decoder static indexed {index}"); let entry = HeaderTable::get_static(index)?; Ok(Header::new( parse_utf8(entry.name())?, @@ -347,7 +330,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC.len())?; - qtrace!([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())?, @@ -359,7 +342,7 @@ impl<'a> HeaderDecoder<'a> { let index = self .buf .read_prefixed_int(HEADER_FIELD_INDEX_DYNAMIC_POST.len())?; - qtrace!([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())?, @@ -368,10 +351,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." - ); + qtrace!("[{self}] read literal with name reference to the static table"); let index = self .buf @@ -384,10 +364,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." - ); + qtrace!("[{self}] read literal with name reference of the dynamic table"); let index = self .buf @@ -400,7 +377,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."); + qtrace!("[{self}] decoder literal with post-based index"); let index = self .buf @@ -413,7 +390,7 @@ impl<'a> HeaderDecoder<'a> { } fn read_literal_with_name_literal(&mut self) -> Res
{ - qtrace!([self], "decode literal with name literal."); + qtrace!("[{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 d03b118cfa..5d69eb2cdc 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 8c8b8d5eaf..57cfab4ee3 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<()> { - qtrace!([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) { - qtrace!([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) { - qtrace!([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,13 +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 { - qtrace!( - [self], - "lookup name:{:?} value {:?} can_block={}", - name, - value, - 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 { @@ -262,11 +256,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:{}", - 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 { @@ -296,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 { - qtrace!([self], "insert name={:?} value={:?}", name, value); + qtrace!("[{self}] insert name={name:?} value={value:?}"); let entry = DynamicTableEntry { name: name.to_vec(), value: value.to_vec(), @@ -329,15 +320,12 @@ impl HeaderTable { value: &[u8], ) -> Res { qtrace!( - [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() @@ -357,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 { - qtrace!([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; @@ -365,7 +353,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); + qtrace!("[{self}] duplicate name={name:?} value={value:?}"); } self.insert(&name, &value) } @@ -376,7 +364,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); + 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 bad69d0a9b..000cef1107 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); - qtrace!("AckRate inputs: {}/{}/{}, {:?}", cwnd, mtu, ratio, rtt); + qtrace!("AckRate inputs: {cwnd}/{mtu}/{ratio}, {rtt:?}"); Self { packets, delay } } @@ -82,12 +82,7 @@ impl FlexibleAckRate { mtu: usize, rtt: Duration, ) -> Self { - qtrace!( - "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 { diff --git a/neqo-transport/src/addr_valid.rs b/neqo-transport/src/addr_valid.rs index 5cb9341e0b..d0cfbd69f7 100644 --- a/neqo-transport/src/addr_valid.rs +++ b/neqo-transport/src/addr_valid.rs @@ -148,7 +148,7 @@ impl AddressValidation { } pub fn set_validation(&mut self, validation: ValidateAddress) { - qtrace!("AddressValidation {:p}: set to {:?}", self, validation); + qtrace!("AddressValidation {self:p}: set to {validation:?}"); self.validation = validation; } @@ -170,7 +170,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); + qtrace!("Expired token: {end:?} vs. {now:?}"); return None; } } @@ -199,11 +199,7 @@ impl AddressValidation { peer_address: SocketAddr, now: Instant, ) -> AddressValidationResult { - qtrace!( - "AddressValidation {:p}: validate {:?}", - self, - self.validation - ); + qtrace!("AddressValidation {self:p}: validate {:?}", self.validation); if token.is_empty() { if self.validation == ValidateAddress::Never { @@ -227,7 +223,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); + qinfo!("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 57e7a2b1f4..565df462ce 100644 --- a/neqo-transport/src/cc/classic_cc.rs +++ b/neqo-transport/src/cc/classic_cc.rs @@ -191,13 +191,11 @@ impl CongestionControl for ClassicCongestionControl { let mut new_acked = 0; for pkt in acked_pkts { qtrace!( - "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; @@ -225,7 +223,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); + 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 +233,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); + 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 +276,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); + 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. @@ -296,8 +294,7 @@ impl CongestionControl for ClassicCongestionControl { for pkt in lost_packets.iter().filter(|pkt| pkt.cc_in_flight()) { qdebug!( - "packet_lost this={:p}, pn={}, ps={}", - self, + "packet_lost this={self:p}, pn={}, ps={}", pkt.pn(), pkt.len() ); @@ -332,8 +329,7 @@ impl CongestionControl for ClassicCongestionControl { now, ); qdebug!( - "on_packets_lost this={:p}, bytes_in_flight={}, cwnd={}, state={:?}", - self, + "on_packets_lost this={self:p}, bytes_in_flight={}, cwnd={}, state={:?}", self.bytes_in_flight, self.congestion_window, self.state @@ -358,7 +354,7 @@ impl CongestionControl for ClassicCongestionControl { &[QlogMetric::BytesInFlight(self.bytes_in_flight)], now, ); - qtrace!([self], "Ignore pkt with size {}", pkt.len()); + qtrace!("[{self}] Ignore pkt with size {}", pkt.len()); } } @@ -391,8 +387,7 @@ impl CongestionControl for ClassicCongestionControl { self.bytes_in_flight += pkt.len(); qdebug!( - "packet_sent this={:p}, pn={}, ps={}", - self, + "packet_sent this={self:p}, pn={}, ps={}", pkt.pn(), pkt.len() ); @@ -457,7 +452,7 @@ impl ClassicCongestionControl { fn set_state(&mut self, state: State, now: Instant) { if self.state != state { - qdebug!([self], "state -> {:?}", state); + qdebug!("[{self}] state -> {state:?}"); let old_state = self.state; self.qlog.add_event_data_with_instant( || { @@ -520,7 +515,7 @@ impl ClassicCongestionControl { .checked_duration_since(t) .expect("time is monotonic"); if elapsed > pc_period { - qinfo!([self], "persistent congestion"); + qinfo!("[{self}] persistent congestion"); self.congestion_window = self.cwnd_min(); self.acked_bytes = 0; self.set_state(State::PersistentCongestion, now); @@ -567,8 +562,7 @@ impl ClassicCongestionControl { self.acked_bytes = acked_bytes; self.ssthresh = self.congestion_window; qdebug!( - [self], - "Cong event -> recovery; cwnd {}, ssthresh {}", + "[{self}] Cong event -> recovery; cwnd {}, ssthresh {}", self.congestion_window, self.ssthresh ); diff --git a/neqo-transport/src/cc/cubic.rs b/neqo-transport/src/cc/cubic.rs index c8c0188ddb..aeae74c253 100644 --- a/neqo-transport/src/cc/cubic.rs +++ b/neqo-transport/src/cc/cubic.rs @@ -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"); + qtrace!("[{self}] New epoch"); } } diff --git a/neqo-transport/src/connection/dump.rs b/neqo-transport/src/connection/dump.rs index 10e1025524..2719351771 100644 --- a/neqo-transport/src/connection/dump.rs +++ b/neqo-transport/src/connection/dump.rs @@ -42,17 +42,11 @@ pub fn dump_packet( }; let x = f.dump(); if !x.is_empty() { - _ = write!(&mut s, "\n {} {}", dir, &x); + _ = write!(&mut s, "\n {dir} {}", &x); } } qdebug!( - [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 9cbb9ce7e0..c6e2d34af6 100644 --- a/neqo-transport/src/connection/mod.rs +++ b/neqo-transport/src/connection/mod.rs @@ -507,7 +507,7 @@ impl Connection { Ok(()) } else { qerror!("Current state: {:?}", self.state()); - qerror!("Cannot set local tparam when not in an initial connection state."); + qerror!("Cannot set local tparam when not in an initial connection state"); Err(Error::ConnectionState) } } @@ -523,13 +523,7 @@ impl Connection { retry_cid: &ConnectionId, ) { debug_assert_eq!(self.role, Role::Server); - qtrace!( - [self], - "Retry CIDs: odcid={} remote={} retry={}", - odcid, - remote_cid, - 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()); @@ -561,7 +555,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); + qerror!("[{self}] Cannot enable ciphers in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.set_ciphers(ciphers)?; @@ -573,7 +567,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); + qerror!("[{self}] Cannot enable groups in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.set_groups(groups)?; @@ -585,7 +579,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); + qerror!("[{self}] Cannot enable groups in state {:?}", self.state); return Err(Error::ConnectionState); } self.crypto.tls.send_additional_key_shares(count)?; @@ -650,8 +644,7 @@ impl Connection { } qtrace!( - [self], - "Maybe create resumption token: {} {}", + "[{self}] Maybe create resumption token: {} {}", self.crypto.has_resumption_token(), self.new_token.has_token() ); @@ -718,7 +711,7 @@ 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); + qerror!("[{self}] set token in state {:?}", self.state); return Err(Error::ConnectionState); } if self.role == Role::Server { @@ -726,8 +719,7 @@ impl Connection { } qinfo!( - [self], - "resumption token {}", + "[{self}] resumption token {}", hex_snip_middle(token.as_ref()) ); let mut dec = Decoder::from(token.as_ref()); @@ -736,25 +728,25 @@ impl Connection { dec.decode_uint::() .ok_or(Error::InvalidResumptionToken)?, )?; - qtrace!([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)?); - qtrace!([self], " RTT {:?}", rtt); + qtrace!("[{self}] RTT {rtt:?}"); let tp_slice = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?; - qtrace!([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)?; - qtrace!([self], " Initial token {}", hex(init_token)); + qtrace!("[{self}] Initial token {}", hex(init_token)); let tok = dec.decode_remainder(); - qtrace!([self], " TLS token {}", hex(tok)); + qtrace!("[{self}] TLS token {}", hex(tok)); match self.crypto.tls { Agent::Client(ref mut c) => { @@ -789,7 +781,7 @@ impl Connection { } pub(crate) fn set_validation(&mut self, validation: &Rc>) { - qtrace!([self], "Enabling NEW_TOKEN"); + qtrace!("[{self}] Enabling NEW_TOKEN"); assert_eq!(self.role, Role::Server); self.address_validation = AddressValidationInfo::Server(Rc::downgrade(validation)); } @@ -810,7 +802,7 @@ impl Connection { }); enc.encode(extra); let records = s.send_ticket(now, enc.as_ref())?; - qdebug!([self], "send session ticket {}", hex(&enc)); + qdebug!("[{self}] send session ticket {}", hex(&enc)); self.crypto.buffer_records(records)?; } else { unreachable!(); @@ -856,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) { - qdebug!([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); @@ -918,7 +910,7 @@ impl Connection { State::Closing { error: err, .. } | State::Draining { error: err, .. } | State::Closed(err) => { - qwarn!([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 @@ -986,7 +978,7 @@ impl Connection { let pto = self.pto(); if self.idle_timeout.expired(now, pto) { - qinfo!([self], "idle timeout expired"); + qinfo!("[{self}] idle timeout expired"); self.set_state( State::Closed(CloseReason::Transport(Error::IdleTimeout)), now, @@ -995,7 +987,7 @@ impl Connection { } if self.state.closing() { - qtrace!([self], "Closing, not processing other timers"); + qtrace!("[{self}] Closing, not processing other timers"); return; } @@ -1018,7 +1010,7 @@ impl Connection { .paths .process_timeout(now, pto, &mut self.stats.borrow_mut()) { - qinfo!([self], "last available path failed"); + qinfo!("[{self}] last available path failed"); self.absorb_error::(now, Err(Error::NoAvailablePath)); } } @@ -1054,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 { - qtrace!([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 { @@ -1064,7 +1056,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); + qtrace!("[{self}] Delayed ACK timer {ack_time:?}"); delays.push(ack_time); } @@ -1074,36 +1066,36 @@ impl Connection { let pto = rtt.pto(self.confirmed()); let idle_time = self.idle_timeout.expiry(now, pto); - qtrace!([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) { - qtrace!([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) { - qtrace!([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()) { - qtrace!([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) { - qtrace!([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() { - qtrace!([self], "Key update timer {:?}", key_update_time); + qtrace!("[{self}] Key update timer {key_update_time:?}"); delays.push(key_update_time); } @@ -1117,7 +1109,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); + qdebug!("[{self}] delay duration {delay:?}"); self.hrtime.update(delay / 4); delay } @@ -1128,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 { - qtrace!([self], "process_output {:?} {:?}", self.state, now); + qtrace!("[{self}] process_output {:?} {now:?}", self.state); match (&self.state, self.role) { (State::Init, Role::Client) => { @@ -1187,7 +1179,7 @@ impl Connection { } fn handle_retry(&mut self, packet: &PublicPacket, now: Instant) -> Res<()> { - qinfo!([self], "received Retry"); + qinfo!("[{self}] received Retry"); if matches!(self.address_validation, AddressValidationInfo::Retry { .. }) { self.stats.borrow_mut().pkt_dropped("Extra Retry"); return Ok(()); @@ -1219,10 +1211,8 @@ impl Connection { let retry_scid = ConnectionId::from(packet.scid()); qinfo!( - [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); @@ -1242,7 +1232,7 @@ impl Connection { fn discard_keys(&mut self, space: PacketNumberSpace, now: Instant) { if self.crypto.discard(space) { - qdebug!([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); } @@ -1270,7 +1260,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..])); + qdebug!("[{self}] Stateless reset: {}", hex(&d[d.len() - 16..])); self.state_signaling.reset(); self.set_state( State::Draining { @@ -1288,10 +1278,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); + 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() { - qtrace!([self], "input saved @{:?}: {:?}", saved.t, saved.d); + qtrace!("[{self}] input saved @{:?}: {:?}", saved.t, saved.d); self.input(saved.d, saved.t, now); } } @@ -1324,7 +1314,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); + 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(); @@ -1354,7 +1344,7 @@ impl Connection { ); Ok(()) } else { - qinfo!([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)), @@ -1402,8 +1392,7 @@ impl Connection { return Ok(PreprocessResult::Next); } qinfo!( - [self], - "Received valid Initial packet with scid {:?} dcid {:?}", + "[{self}] Received valid Initial packet with scid {:?} dcid {:?}", packet.scid(), packet.dcid() ); @@ -1571,7 +1560,7 @@ impl Connection { let mut slc = d.as_ref(); let mut dcid = None; - qtrace!([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. @@ -1581,8 +1570,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)); + qinfo!("[{self}] Garbage packet: {e}"); + qtrace!("[{self}] Garbage packet contents: {}", hex(slc)); self.stats.borrow_mut().pkt_dropped("Garbage packet"); break; } @@ -1593,7 +1582,7 @@ impl Connection { PreprocessResult::End => return Ok(()), } - qtrace!([self], "Received unverified packet {:?}", packet); + qtrace!("[{self}] Received unverified packet {packet:?}"); match packet.decrypt(&mut self.crypto.states, now + pto) { Ok(payload) => { @@ -1624,7 +1613,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()); + qdebug!("Duplicate packet {space}-{}", payload.pn()); self.stats.borrow_mut().dups_rx += 1; } else { match self.process_packet(path, &payload, now) { @@ -1639,9 +1628,7 @@ impl Connection { } } else { qdebug!( - [self], - "Received packet {} for untracked space {}", - space, + "[{self}] Received packet {space} for untracked space {}", payload.pn() ); return Err(Error::ProtocolViolation); @@ -1741,8 +1728,7 @@ impl Connection { space.set_received(now, packet.pn(), ack_eliciting) } else { qdebug!( - [self], - "processed a {:?} packet without tracking it", + "[{self}] processed a {:?} packet without tracking it", packet.packet_type(), ); // This was a valid packet that caused the same packet number to be @@ -1799,11 +1785,11 @@ impl Connection { .make_permanent(path, None, ConnectionIdEntry::empty_remote(), now); Ok(()) } else { - qtrace!([self], "Unable to make path permanent: {}", path.borrow()); + qtrace!("[{self}] Unable to make path permanent: {}", path.borrow()); Err(Error::InvalidMigration) } } else { - qtrace!([self], "Unable to make path permanent: {}", path.borrow()); + qtrace!("[{self}] Unable to make path permanent: {}", path.borrow()); Err(Error::InvalidMigration) } } else { @@ -1829,7 +1815,7 @@ impl Connection { } fn start_handshake(&mut self, path: &PathRef, packet: &PublicPacket, now: Instant) { - qtrace!([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())); @@ -1840,17 +1826,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"); + qdebug!("[{self}] Accepted 0-RTT"); ZeroRttState::AcceptedServer } else { - qtrace!([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 { - qdebug!([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()); @@ -1931,8 +1917,7 @@ impl Connection { ); self.ensure_permanent(&path, now)?; qinfo!( - [self], - "Migrate to {} probe {}", + "[{self}] Migrate to {} probe {}", path.borrow(), if force { "now" } else { "after" } ); @@ -1950,7 +1935,7 @@ impl Connection { self.conn_params.get_preferred_address(), PreferredAddressConfig::Disabled ) { - qdebug!([self], "Preferred address is disabled"); + qdebug!("[{self}] Preferred address is disabled"); None } else { self.tps.borrow_mut().remote().get_preferred_address() @@ -1978,18 +1963,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); + qwarn!("[{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); + qwarn!("[{self}] Ignoring bad preferred address: {remote}"); } } else { - qwarn!([self], "Unable to migrate to a different address family"); + qwarn!("[{self}] Unable to migrate to a different address family"); } } else { - qdebug!([self], "No preferred address to migrate to"); + qdebug!("[{self}] No preferred address to migrate to"); } Ok(()) } @@ -2013,15 +1998,14 @@ impl Connection { .handle_migration(path, d.source(), now, &mut self.stats.borrow_mut()); } else { qinfo!( - [self], - "{} Peer migrated, but no connection ID available", + "[{self}] {} Peer migrated, but no connection ID available", path.borrow() ); } } fn output(&mut self, now: Instant) -> SendOption { - qtrace!([self], "output {:?}", now); + qtrace!("[{self}] output {now:?}"); let res = match &self.state { State::Init | State::WaitInitial @@ -2045,7 +2029,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"); + qerror!("[{self}] Attempting to close with a temporary path"); Err(Error::InternalError) } else { self.output_path(&path, now, Some(&details)) @@ -2073,8 +2057,7 @@ impl Connection { PacketBuilder::short(encoder, tx.key_phase(), path.remote_cid()) } else { qdebug!( - "Building {:?} dcid {:?} scid {:?}", - pt, + "Building {pt:?} dcid {:?} scid {:?}", path.remote_cid(), path.local_cid(), ); @@ -2388,7 +2371,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); + 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 @@ -2518,7 +2501,7 @@ impl Connection { } if encoder.is_empty() { - qdebug!("TX blocked, profile={:?}", profile); + qdebug!("TX blocked, profile={profile:?}"); Ok(SendOption::No(profile.paced())) } else { // Perform additional padding for Initial packets as necessary. @@ -2526,8 +2509,7 @@ impl Connection { if let Some(mut initial) = initial_sent.take() { if needs_padding { qdebug!( - [self], - "pad Initial from {} to PLPMTU {}", + "[{self}] pad Initial from {} to PLPMTU {}", packets.len(), profile.limit() ); @@ -2553,7 +2535,7 @@ impl Connection { let la = self .loss_recovery .largest_acknowledged_pn(PacketNumberSpace::ApplicationData); - qinfo!([self], "Initiating key update"); + qinfo!("[{self}] Initiating key update"); self.crypto.states.initiate_key_update(la) } else { Err(Error::KeyUpdateBlocked) @@ -2567,7 +2549,7 @@ impl Connection { } fn client_start(&mut self, now: Instant) -> Res<()> { - qdebug!([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); @@ -2581,7 +2563,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"); + qdebug!("[{self}] Enabled 0-RTT"); ZeroRttState::Sending } else { ZeroRttState::Init @@ -2693,8 +2675,7 @@ impl Connection { != tp.map(ConnectionIdRef::from) { qwarn!( - [self], - "ISCID test failed: self cid {:?} != tp cid {:?}", + "[{self}] ISCID test failed: self cid {:?} != tp cid {:?}", self.remote_initial_source_cid, tp.map(hex), ); @@ -2710,8 +2691,7 @@ impl Connection { != tp.map(ConnectionIdRef::from) { qwarn!( - [self], - "ODCID test failed: self cid {:?} != tp cid {:?}", + "[{self}] ODCID test failed: self cid {:?} != tp cid {:?}", self.original_destination_cid, tp.map(hex), ); @@ -2729,9 +2709,7 @@ impl Connection { }; if expected != tp.map(ConnectionIdRef::from) { qwarn!( - [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); @@ -2749,11 +2727,8 @@ impl Connection { // 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?}", + "[{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 @@ -2762,7 +2737,7 @@ impl Connection { // was provided. Ok(()) } else if self.version().wire_version() != current { - qinfo!([self], "validate_versions: current version mismatch"); + qinfo!("[{self}] validate_versions: current version mismatch"); Err(Error::VersionNegotiation) } else if self .conn_params @@ -2787,12 +2762,12 @@ impl Connection { { Ok(()) } else { - qinfo!([self], "validate_versions: failed"); + qinfo!("[{self}] validate_versions: failed"); Err(Error::VersionNegotiation) } } } else if self.version != Version::Version1 && !self.version.is_draft() { - qinfo!([self], "validate_versions: missing extension"); + qinfo!("[{self}] validate_versions: missing extension"); Err(Error::VersionNegotiation) } else { Ok(()) @@ -2801,7 +2776,7 @@ impl Connection { fn confirm_version(&mut self, v: Version) { if self.version != v { - qdebug!([self], "Compatible upgrade {:?} ==> {:?}", self.version, v); + qdebug!("[{self}] Compatible upgrade {:?} ==> {v:?}", self.version); } self.crypto.confirm_version(v); self.version = v; @@ -2833,7 +2808,7 @@ impl Connection { space: PacketNumberSpace, data: Option<&[u8]>, ) -> Res<()> { - qtrace!([self], "Handshake space={} data={:0x?}", space, data); + qtrace!("[{self}] Handshake space={space} data={data:0x?}"); let was_authentication_pending = *self.crypto.tls.state() == HandshakeState::AuthenticationPending; @@ -2904,7 +2879,7 @@ impl Connection { now: Instant, ) -> Res<()> { if !frame.is_allowed(packet_type) { - qinfo!("frame not allowed: {:?} {:?}", frame, packet_type); + qinfo!("frame not allowed: {frame:?} {packet_type:?}"); return Err(Error::ProtocolViolation); } let space = PacketNumberSpace::from(packet_type); @@ -2936,7 +2911,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); + qwarn!("Largest ACKed {largest_acknowledged} was never sent"); return Err(Error::AckedUnsentPacket); } @@ -2946,10 +2921,7 @@ impl Connection { } Frame::Crypto { offset, data } => { qtrace!( - [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; @@ -2957,7 +2929,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); + qdebug!("Read {read:?} bytes"); self.handshake(now, packet_version, space, Some(&buf))?; self.create_resumption_token(now); } else { @@ -2990,7 +2962,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"); + qinfo!("[{self}] received too many connection IDs"); return Err(Error::ConnectionIdLimitExceeded); } } @@ -3022,11 +2994,7 @@ impl Connection { } => { 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 + "[{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 @@ -3092,7 +3060,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); + qdebug!("[{self}] Lost: {token:?}"); match token { RecoveryToken::Ack(ack_token) => { // If we lost an ACK frame during the handshake, send another one. @@ -3141,7 +3109,7 @@ impl Connection { R: IntoIterator> + Debug, R::IntoIter: ExactSizeIterator, { - qdebug!([self], "Rx ACK space={}, ranges={:?}", space, ack_ranges); + qdebug!("[{self}] Rx ACK space={space}, ranges={ack_ranges:?}"); let Some(path) = self.paths.primary() else { return; @@ -3196,7 +3164,7 @@ impl Connection { if !matches!(self.zero_rtt_state, ZeroRttState::Sending) { return; } - qdebug!([self], "0-RTT rejected"); + qdebug!("[{self}] 0-RTT rejected"); self.resend_0rtt(now); self.streams.zero_rtt_rejected(); self.crypto.states.discard_0rtt_keys(); @@ -3204,9 +3172,9 @@ impl Connection { } fn set_connected(&mut self, now: Instant) -> Res<()> { - qdebug!([self], "TLS connection complete"); + 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)); } @@ -3252,13 +3220,13 @@ impl Connection { self.state_signaling.handshake_done(); self.set_confirmed(now)?; } - qinfo!([self], "Connection established"); + qinfo!("[{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); + qdebug!("[{self}] State change from {:?} -> {state:?}", self.state); self.state = state.clone(); if self.state.closed() { self.streams.clear_streams(); @@ -3384,8 +3352,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 09bcefb7a4..ce84e3e5ca 100644 --- a/neqo-transport/src/connection/tests/cc.rs +++ b/neqo-transport/src/connection/tests/cc.rs @@ -249,12 +249,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 { - qinfo!("iteration {}", i); + qinfo!("iteration {i}"); let c_tx_size: usize = c_tx_dgrams.iter().map(Datagram::len).sum(); qinfo!( - "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); @@ -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. - qdebug!([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. - qdebug!([client], "Process ack-eliciting"); + qdebug!("[{client}] Process ack-eliciting"); let ack_pkt = client.process(ack_eliciting_packet, now).dgram(); assert!(ack_pkt.is_some()); - qdebug!([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/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 024d0f9157..5fb39255ff 100644 --- a/neqo-transport/src/connection/tests/idle.rs +++ b/neqo-transport/src/connection/tests/idle.rs @@ -9,7 +9,7 @@ use std::{ time::{Duration, Instant}, }; -use neqo_common::{qtrace, Encoder}; +use neqo_common::{qtrace, qwarn, Encoder}; use test_fixture::{now, split_datagram}; use super::{ @@ -338,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()); - neqo_common::qwarn!("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(); @@ -359,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(); - qtrace!([endpoint], "idle timeout {:?}", delay); + qtrace!("[{endpoint}] idle timeout {delay:?}"); if rtt < default_timeout() / 4 { assert_eq!(default_timeout(), delay); } else { @@ -640,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(); - qtrace!([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/mod.rs b/neqo-transport/src/connection/tests/mod.rs index 5accfab36d..5c3073ae00 100644 --- a/neqo-transport/src/connection/tests/mod.rs +++ b/neqo-transport/src/connection/tests/mod.rs @@ -346,7 +346,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); + qtrace!("----- connected and idle with RTT {rtt:?}"); now } @@ -370,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(); - qtrace!("fill_cwnd wrote {} bytes", bytes_sent); + qtrace!("fill_cwnd wrote {bytes_sent} bytes"); if bytes_sent < BLOCK_SIZE { break; } @@ -391,9 +391,8 @@ 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(); - qdebug!([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(); - qtrace!([dest], "ack_bytes read {} bytes", bytes_read); + 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. - qtrace!([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); - qtrace!([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); - qtrace!([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); - qtrace!([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()); - qdebug!([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"); @@ -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 f3c319bdec..63a2368e94 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 { - qdebug!("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/crypto.rs b/neqo-transport/src/crypto.rs index 756cdbb771..651317bb4b 100644 --- a/neqo-transport/src/crypto.rs +++ b/neqo-transport/src/crypto.rs @@ -190,7 +190,7 @@ impl Crypto { data: Option<&[u8]>, ) -> Res<&HandshakeState> { let input = data.map(|d| { - qtrace!("Handshake record received {:0x?} ", d); + qtrace!("Handshake record received {d:0x?} "); let epoch = match space { PacketNumberSpace::Initial => TLS_EPOCH_INITIAL, PacketNumberSpace::Handshake => TLS_EPOCH_HANDSHAKE, @@ -211,7 +211,7 @@ impl Crypto { } Err(CryptoError::EchRetry(v)) => Err(Error::EchRetry(v)), Err(e) => { - qinfo!("Handshake failed {:?}", e); + qinfo!("Handshake failed {e:?}"); Err(self .tls .alert() @@ -265,7 +265,7 @@ impl Crypto { } fn install_handshake_keys(&mut self) -> Res { - qtrace!([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); @@ -281,15 +281,15 @@ impl Crypto { .ok_or(Error::InternalError)?; self.states .set_handshake_keys(self.version, &write_secret, &read_secret, cipher)?; - qdebug!([self], "Handshake keys installed"); + qdebug!("[{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"); + 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)?; - qdebug!([self], "Application write key installed"); + qdebug!("[{self}] Application write key installed"); } Ok(()) } @@ -305,7 +305,7 @@ impl Crypto { .ok_or(Error::InternalError)?; self.states .set_application_read_key(version, &read_secret, expire_0rtt)?; - qdebug!([self], "application read keys installed"); + qdebug!("[{self}] application read keys installed"); Ok(()) } @@ -315,7 +315,7 @@ impl Crypto { if r.ct != TLS_CT_HANDSHAKE { return Err(Error::ProtocolViolation); } - qtrace!([self], "Adding CRYPTO data {:?}", r); + qtrace!("[{self}] Adding CRYPTO data {r:?}"); self.streams .send(PacketNumberSpace::from(r.epoch), &r.data)?; } @@ -387,7 +387,7 @@ impl Crypto { ResumptionToken::new(enc.into(), t.expiration_time()) }) } else { - unreachable!("It is a server."); + unreachable!("It is a server"); } } @@ -395,7 +395,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"); } } } @@ -448,13 +448,7 @@ impl CryptoDxState { secret: &SymKey, cipher: Cipher, ) -> Res { - qdebug!( - "Making {:?} {} CryptoDxState, v={:?} cipher={}", - direction, - epoch, - version, - cipher, - ); + qdebug!("Making {direction:?} {epoch} CryptoDxState, v={version:?} cipher={cipher}",); let hplabel = String::from(version.label_prefix()) + "hp"; Ok(Self { version, @@ -475,7 +469,7 @@ impl CryptoDxState { label: &str, dcid: &[u8], ) -> Res { - qtrace!("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( @@ -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; } }); @@ -582,11 +576,9 @@ impl CryptoDxState { Ok(()) } else if prev.used_pn.end > self.used_pn.start { qdebug!( - [self], - "Found packet with too new packet number {} > {}, compared to {}", + "[{self}] Found packet with too new packet number {} > {}, compared to {prev}", self.used_pn.start, prev.used_pn.end, - prev, ); Err(Error::PacketNumberOverlap) } else { @@ -601,9 +593,7 @@ impl CryptoDxState { pub fn used(&mut self, pn: PacketNumber) -> Res<()> { if pn < self.min_pn { qdebug!( - [self], - "Found packet with too old packet number: {} < {}", - pn, + "[{self}] Found packet with too old packet number: {pn} < {}", self.min_pn ); return Err(Error::PacketNumberOverlap); @@ -633,7 +623,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)); + qtrace!("[{self}] HP sample={} mask={}", hex(sample), hex(mask)); Ok(mask) } @@ -645,9 +635,7 @@ 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={}", - pn, + "[{self}] encrypt pn={pn} hdr={} body={}", 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)); + qtrace!("[{self}] encrypt ct={}", hex(res)); debug_assert_eq!(pn, self.next_pn()); self.used(pn)?; Ok(res.to_vec()) @@ -681,9 +669,7 @@ 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={}", - pn, + "[{self}] decrypt pn={pn} hdr={} body={}", hex(hdr), hex(body) ); @@ -962,10 +948,7 @@ impl CryptoStates { for v in versions { qdebug!( - [self], - "Creating initial cipher state v={:?}, role={:?} dcid={}", - v, - role, + "[{self}] Creating initial cipher state v={v:?}, role={role:?} dcid={}", hex(dcid) ); @@ -975,8 +958,7 @@ impl CryptoStates { }; if let Some(prev) = self.initials.get(v) { qinfo!( - [self], - "Continue packet numbers for initial after retry (write is {:?})", + "[{self}] Continue packet numbers for initial after retry (write is {:?})", prev.rx.used_pn, ); initial.tx.continuation(&prev.tx)?; @@ -1024,7 +1006,7 @@ impl CryptoStates { secret: &SymKey, cipher: Cipher, ) -> Res<()> { - qtrace!([self], "install 0-RTT keys"); + qtrace!("[{self}] install 0-RTT keys"); self.zero_rtt = Some(CryptoDxState::new( version, dir, @@ -1049,7 +1031,7 @@ impl CryptoStates { } pub fn discard_0rtt_keys(&mut self) { - qtrace!([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" @@ -1131,11 +1113,11 @@ impl CryptoStates { if self.maybe_update_write()? { Ok(()) } else { - qdebug!([self], "Write keys already updated"); + qdebug!("[{self}] Write keys already updated"); Err(Error::KeyUpdateBlocked) } } else { - qdebug!([self], "Waiting for ACK or blocked on read key timer"); + qdebug!("[{self}] Waiting for ACK or blocked on read key timer"); Err(Error::KeyUpdateBlocked) } } @@ -1149,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() { - qdebug!([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 { @@ -1163,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() { - qinfo!([self], "Initiating automatic key update"); + qinfo!("[{self}] Initiating automatic key update"); if !self.maybe_update_write()? { return Err(Error::KeysExhausted); } @@ -1183,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<()> { - qtrace!([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 @@ -1213,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() { - qtrace!([self], "Discarding 0-RTT keys"); + qtrace!("[{self}] Discarding 0-RTT keys"); self.zero_rtt = None; } else { - qtrace!([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()?); @@ -1241,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() { - qtrace!([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)?; } @@ -1541,7 +1523,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); + 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 944c63ac8a..5e56c14e21 100644 --- a/neqo-transport/src/ecn.rs +++ b/neqo-transport/src/ecn.rs @@ -187,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; - qdebug!("ECN probing: sent {} probes", probes_sent); + qdebug!("ECN probing: sent {probes_sent} probes"); if *probes_sent == ECN_TEST_COUNT { - qdebug!("ECN probing concluded with {} probes sent", probes_sent); + qdebug!("ECN probing concluded with {probes_sent} probes sent"); self.state.set(EcnValidationState::Unknown, stats); } } @@ -231,8 +231,7 @@ impl EcnInfo { // is not ECN capable and likely drops all ECN marked packets. if probes_sent == probes_lost && *probes_lost == ECN_TEST_COUNT_INITIAL_PHASE { qdebug!( - "ECN validation failed, all {} initial marked packets were lost", - probes_lost + "ECN validation failed, all {probes_lost} initial marked packets were lost" ); self.disable_ecn(stats, EcnValidationError::BlackHole); } @@ -301,9 +300,7 @@ impl EcnInfo { let sum_inc = ecn_diff[IpTosEcn::Ect0] + ecn_diff[IpTosEcn::Ce]; if sum_inc < newly_acked_sent_with_ect0 { qwarn!( - "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 acc4d6582d..5a753719df 100644 --- a/neqo-transport/src/fc.rs +++ b/neqo-transport/src/fc.rs @@ -326,9 +326,8 @@ impl ReceiverFlowControl<()> { pub fn consume(&mut self, count: u64) -> Res<()> { if self.consumed + count > self.max_allowed { qtrace!( - "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); @@ -383,7 +382,7 @@ impl ReceiverFlowControl { } if consumed > self.max_allowed { - qtrace!("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 c858c41b5c..9559723156 100644 --- a/neqo-transport/src/frame.rs +++ b/neqo-transport/src/frame.rs @@ -370,7 +370,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, @@ -379,12 +379,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 869ef7a4d1..551c6ea33e 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 { - qwarn!("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 642a656da2..3670fe1d6f 100644 --- a/neqo-transport/src/pace.rs +++ b/neqo-transport/src/pace.rs @@ -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); + 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 { - qtrace!([self], "next {cwnd}/{rtt:?} below granularity ({w:?})",); + qtrace!("[{self}] next {cwnd}/{rtt:?} below granularity ({w:?})",); return self.t; } let nxt = self.t + w; - qtrace!([self], "next {cwnd}/{rtt:?} wait {w:?} = {nxt:?}"); + qtrace!("[{self}] next {cwnd}/{rtt:?} wait {w:?} = {nxt:?}"); nxt } @@ -108,7 +108,7 @@ impl Pacer { return; } - qtrace!([self], "spend {} over {}, {:?}", count, 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. @@ -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 f52f87978d..448a7ec50a 100644 --- a/neqo-transport/src/packet/mod.rs +++ b/neqo-transport/src/packet/mod.rs @@ -856,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)?; - qtrace!([rx], "decoded header: {:?}", header); + qtrace!("[{rx}] decoded header: {header:?}"); let Some(rx) = crypto.rx(version, cspace, key_phase) else { return Err(Error::DecryptError); }; @@ -877,7 +877,7 @@ impl<'a> PublicPacket<'a> { } else if crypto.rx_pending(cspace) { Err(Error::KeysPending(cspace)) } else { - qtrace!("keys for {:?} already discarded", cspace); + 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 1ef8a3cbfd..741b28c7f5 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| { - qerror!("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 c6fe207375..7990cba790 100644 --- a/neqo-transport/src/path.rs +++ b/neqo-transport/src/path.rs @@ -147,15 +147,15 @@ impl Paths { .is_some_and(|target| Rc::ptr_eq(target, &removed)) { qinfo!( - [path.borrow()], - "The migration target path had to be removed" + "[{}] 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"); + 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() { @@ -168,7 +168,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"); + 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); }); @@ -227,7 +227,7 @@ impl Paths { if p.borrow_mut().process_timeout(now, pto, stats) { true } else { - qdebug!([p.borrow()], "Retiring path"); + qdebug!("[{}] Retiring path", p.borrow()); if p.borrow().is_primary() { primary_failed = true; } @@ -248,7 +248,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"); + qinfo!("[{}] Failing over after primary path failed", path.borrow()); mem::drop(self.select_primary(&path, now)); true } else { @@ -370,8 +370,7 @@ impl Paths { .is_some_and(|target| Rc::ptr_eq(target, p)) { qinfo!( - [path], - "NEW_CONNECTION_ID with Retire Prior To forced migration to fail" + "[{path}] NEW_CONNECTION_ID with Retire Prior To forced migration to fail" ); *migration_target = None; } @@ -613,7 +612,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); + qtrace!("[{self}] Make primary {primary}"); debug_assert!(self.remote_cid.is_some()); self.primary = primary; if !primary { @@ -624,7 +623,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); + qdebug!("[{self}] Path validated {now:?}"); self.state = ProbeState::Valid; self.validated = Some(now); } @@ -718,7 +717,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"); + qdebug!("[{self}] Sub-MTU probe successful, reset probe count"); self.probe(stats); } true @@ -747,19 +746,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" - ); + 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 { - qinfo!([self], "Probing failed"); + qinfo!("[{self}] Probing failed"); ProbeState::Failed } } else { - qdebug!([self], "Initiating probe"); + qdebug!("[{self}] Initiating probe"); ProbeState::ProbeNeeded { probe_count } }; } @@ -781,7 +777,7 @@ impl Path { } // Send PATH_RESPONSE. let resp_sent = if let Some(challenge) = self.challenge.take() { - qtrace!([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[..]); @@ -798,7 +794,7 @@ impl Path { // Send PATH_CHALLENGE. if let ProbeState::ProbeNeeded { probe_count } = self.state { - qtrace!([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); @@ -950,8 +946,7 @@ impl Path { // 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={:?}", + "[{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 fd40f92699..ce983fa8a1 100644 --- a/neqo-transport/src/pmtud.rs +++ b/neqo-transport/src/pmtud.rs @@ -269,9 +269,8 @@ impl Pmtud { let last_ok = first_failed - 1; qdebug!( - "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, @@ -461,7 +460,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - qdebug!("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(); @@ -514,7 +513,7 @@ mod tests { } assert_mtu(&pmtud, mtu); - qdebug!("Increasing MTU to {}", larger_mtu); + qdebug!("Increasing MTU to {larger_mtu}"); let now = now + PMTU_RAISE_TIMER; pmtud.maybe_fire_raise_timer(now, &mut stats); while pmtud.needs_probe() { diff --git a/neqo-transport/src/recovery/mod.rs b/neqo-transport/src/recovery/mod.rs index 4879750a70..a644586bc1 100644 --- a/neqo-transport/src/recovery/mod.rs +++ b/neqo-transport/src/recovery/mod.rs @@ -323,10 +323,8 @@ impl LossRecoverySpace { self.remove_old_lost(now, cleanup_delay); qtrace!( - "detect lost {}: now={:?} delay={:?}", + "detect lost {}: now={now:?} delay={loss_delay:?}", self.space, - now, - loss_delay, ); self.first_ooo_time = None; @@ -341,17 +339,14 @@ impl LossRecoverySpace { // Packets sent before now - loss_delay are deemed lost. if packet.time_sent() + loss_delay <= now { qtrace!( - "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) { qtrace!( - "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() { @@ -551,15 +546,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()); + 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 { qwarn!( - [self], - "ignoring {}-{} from dropped space", - pn_space, + "[{self}] ignoring {pn_space}-{} from dropped space", sent_packet.pn() ); } @@ -647,9 +640,7 @@ impl LossRecovery { } qdebug!( - [self], - "ACK for {} - largest_acked={}", - pn_space, + "[{self}] ACK for {pn_space} - largest_acked={}", largest_acked_pkt.pn() ); @@ -736,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) { - qdebug!([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()); @@ -763,12 +754,7 @@ impl LossRecovery { } else { None }; - qtrace!( - [self], - "next_timeout loss={:?} pto={:?}", - loss_time, - 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), @@ -872,7 +858,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); + qdebug!("[{self}] PTO timer fired for {pn_space}"); let space = self.spaces.get_mut(*pn_space).unwrap(); lost.extend( space @@ -888,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 { - qtrace!([self], "PTO {}, probing {:?}", pn_space, 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 { - qtrace!([self], "timeout {:?}", now); + qtrace!("[{self}] timeout {now:?}"); let loss_delay = primary_path.borrow().rtt().loss_delay(); let confirmed = self.confirmed(); @@ -928,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 { - qtrace!([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 7d564abfff..f8c598adbd 100644 --- a/neqo-transport/src/recv_stream.rs +++ b/neqo-transport/src/recv_stream.rs @@ -132,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]) { - qtrace!("Inbound data offset={} len={}", new_start, 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. @@ -165,12 +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); - qtrace!( - "New frame {}-{} received, overlap: {}", - new_start, - new_end, - 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. @@ -182,15 +177,11 @@ impl RxStreamOrderer { // NNNN // NNNN // Do nothing - qtrace!( - "Dropping frame with already-received range {}-{}", - new_start, - new_end - ); + qtrace!("Dropping frame with already-received range {new_start}-{new_end}"); return; } } else { - qtrace!("New frame {}-{} received", new_start, new_end); + qtrace!("New frame {new_start}-{new_end} received"); false }; @@ -228,21 +219,14 @@ impl RxStreamOrderer { break; } else if next_end >= new_end { qtrace!( - "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; } qtrace!( - "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 @@ -1016,7 +1000,7 @@ mod tests { fn recv_ranges(ranges: &[Range], available: usize) { const ZEROES: &[u8] = &[0; 100]; - qtrace!("recv_ranges {:?}", ranges); + qtrace!("recv_ranges {ranges:?}"); let mut s = RxStreamOrderer::default(); for r in ranges { @@ -1028,7 +1012,7 @@ mod tests { let mut total_recvd = 0; loop { let recvd = s.read(&mut buf[..]); - qtrace!("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 c18bbd62ec..8e5b95bccb 100644 --- a/neqo-transport/src/rtt.rs +++ b/neqo-transport/src/rtt.rs @@ -74,7 +74,7 @@ impl RttEstimate { } pub fn set_initial(&mut self, rtt: Duration) { - qtrace!("initial RTT={:?}", rtt); + qtrace!("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 e05a0efa3f..cb1203b401 100644 --- a/neqo-transport/src/send_stream.rs +++ b/neqo-transport/src/send_stream.rs @@ -405,7 +405,7 @@ impl RangeTracker { fn unmark_range(&mut self, off: u64, len: usize) { if len == 0 { - qdebug!("unmark 0-length range at {}", off); + qdebug!("unmark 0-length range at {off}"); return; } @@ -424,10 +424,7 @@ impl RangeTracker { if *cur_off + *cur_len > off { if *cur_state == RangeState::Acked { qdebug!( - "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 { @@ -439,10 +436,7 @@ impl RangeTracker { if *cur_state == RangeState::Acked { qdebug!( - "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; @@ -760,7 +754,7 @@ impl SendStream { tokens: &mut Vec, stats: &mut FrameStats, ) { - qtrace!("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); @@ -926,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. - qtrace!("SendStream::length_and_fill fill {}", space); + qtrace!("SendStream::length_and_fill fill {space}"); return (space, true); } @@ -939,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; - qtrace!("SendStream::length_and_fill {} fill {}", data_len, fill); + qtrace!("SendStream::length_and_fill {data_len} fill {fill}"); (data_len, fill) } @@ -971,14 +965,14 @@ impl SendStream { 0 }; if overhead > builder.remaining() { - qtrace!([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 { - qtrace!([self], "write_frame no data, no fin"); + qtrace!("[{self}] write_frame no data, no fin"); return; } @@ -1015,7 +1009,7 @@ impl SendStream { | SendStreamState::Send { .. } | SendStreamState::DataSent { .. } | SendStreamState::DataRecvd { .. } => { - qtrace!([self], "Reset acked while in {} state?", self.state.name()); + qtrace!("[{self}] Reset acked while in {} state?", self.state.name()); } SendStreamState::ResetSent { final_retired, @@ -1025,7 +1019,7 @@ impl SendStream { final_retired, final_written, }), - SendStreamState::ResetRecvd { .. } => qtrace!([self], "already in ResetRecvd state"), + SendStreamState::ResetRecvd { .. } => qtrace!("[{self}] already in ResetRecvd state"), }; } @@ -1085,7 +1079,7 @@ impl SendStream { { fc.frame_lost(limit); } else { - qtrace!([self], "Ignoring lost STREAM_DATA_BLOCKED({})", limit); + qtrace!("[{self}] Ignoring lost STREAM_DATA_BLOCKED({limit})"); } } @@ -1154,8 +1148,7 @@ impl SendStream { } } _ => qtrace!( - [self], - "mark_as_acked called from state {}", + "[{self}] mark_as_acked called from state {}", self.state.name() ), } @@ -1168,8 +1161,7 @@ impl SendStream { offset + u64::try_from(len).unwrap(), ); qtrace!( - [self], - "mark_as_lost retransmission offset={}", + "[{self}] mark_as_lost retransmission offset={}", self.retransmission_offset ); if let Some(buf) = self.state.tx_buf_mut() { @@ -1259,7 +1251,7 @@ impl SendStream { fn send_internal(&mut self, buf: &[u8], atomic: bool) -> Res { if buf.is_empty() { - qerror!([self], "zero-length send on stream"); + qerror!("[{self}] zero-length send on stream"); return Err(Error::InvalidInput); } @@ -1323,10 +1315,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 { .. } => 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"), } } @@ -1367,9 +1359,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 { .. } => qtrace!("[{self}] already in DataRecvd state"), + SendStreamState::ResetSent { .. } => qtrace!("[{self}] already in ResetSent state"), + SendStreamState::ResetRecvd { .. } => qtrace!("[{self}] already in ResetRecvd state"), }; } @@ -1694,7 +1686,7 @@ impl SendStreams { tokens: &mut Vec, stats: &mut FrameStats, ) { - qtrace!("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): @@ -1731,7 +1723,7 @@ impl SendStreams { qtrace!("processing streams... unfair:"); for stream in self.map.values_mut() { if !stream.is_fair() { - qtrace!(" {}", stream); + qtrace!(" {stream}"); if !stream.write_frames_with_early_return(priority, builder, tokens, stats) { break; } @@ -1747,7 +1739,7 @@ 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); + qtrace!(" {stream_id} ({order})"); } else { qtrace!(" None"); } @@ -2943,14 +2935,7 @@ mod tests { fn frame_sent_sid(stream: u64, offset: usize, len: usize, fin: bool, space: usize) -> bool { const BUF: &[u8] = &[0x42; 128]; - qtrace!( - "frame_sent stream={} offset={} len={} fin={}, space={}", - stream, - offset, - len, - fin, - space - ); + qtrace!("frame_sent stream={stream} offset={offset} len={len} fin={fin}, space={space}"); let mut s = stream_with_sent(stream, offset); @@ -3058,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 { - qtrace!("send_with_extra_capacity {} + {}", data.len(), extra); + 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 f2f8bcb3ce..8c6f23b554 100644 --- a/neqo-transport/src/sender.rs +++ b/neqo-transport/src/sender.rs @@ -93,9 +93,8 @@ impl PacketSender { let current_mtu = self.pmtud().plpmtu(); if current_mtu != self.pacer.mtu() { qdebug!( - "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 154ad17ed3..4680bb92f6 100644 --- a/neqo-transport/src/server.rs +++ b/neqo-transport/src/server.rs @@ -199,7 +199,7 @@ impl Server { dgram: Datagram>, now: Instant, ) -> Output { - qdebug!([self], "Handle initial"); + qdebug!("[{self}] Handle initial"); let res = self .address_validation .borrow() @@ -211,7 +211,7 @@ impl Server { self.accept_connection(initial, dgram, Some(orig_dcid), now) } AddressValidationResult::Validate => { - qinfo!([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, @@ -219,7 +219,7 @@ impl Server { now, ); let Ok(token) = res else { - qerror!([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() { @@ -232,13 +232,12 @@ impl Server { ); packet.map_or_else( |_| { - qerror!([self], "unable to encode retry, dropping packet"); + qerror!("[{self}] unable to encode retry, dropping packet"); Output::None }, |p| { qdebug!( - [self], - "type={:?} path:{} {}->{} {:?} len {}", + "[{self}] type={:?} path:{} {}->{} {:?} len {}", PacketType::Retry, initial.dst_cid, dgram.destination(), @@ -255,7 +254,7 @@ impl Server { }, ) } else { - qerror!([self], "no connection ID for retry, dropping packet"); + qerror!("[{self}] no connection ID for retry, dropping packet"); Output::None } } @@ -274,7 +273,7 @@ impl Server { format!("server-{odcid}"), ) .unwrap_or_else(|e| { - qerror!("failed to create NeqoQlog: {}", e); + qerror!("failed to create NeqoQlog: {e}"); NeqoQlog::disabled() }) }) @@ -288,7 +287,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"); + qwarn!("[{self}] Unable to enable 0-RTT"); } if let Some(odcid) = &orig_dcid { // There was a retry, so set the connection IDs for. @@ -300,7 +299,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"); + qwarn!("[{self}] Unable to enable ECH"); } } } @@ -313,8 +312,7 @@ impl Server { now: Instant, ) -> Output { qinfo!( - [self], - "Accept connection {:?}", + "[{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 +335,7 @@ impl Server { out } Err(e) => { - qwarn!([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()), @@ -358,7 +356,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 { - qtrace!([self], "Discarding {:?}", dgram); + qtrace!("[{self}] Discarding {dgram:?}"); return Output::None; }; @@ -373,7 +371,7 @@ impl Server { if packet.packet_type() == PacketType::Short { // TODO send a stateless reset here. - qtrace!([self], "Short header packet for an unknown connection"); + qtrace!("[{self}] Short header packet for an unknown connection"); return Output::None; } @@ -386,11 +384,11 @@ impl Server { .contains(&packet.version().unwrap())) { if dgram.len() < MIN_INITIAL_PACKET_SIZE { - qdebug!([self], "Unsupported version: too short"); + qdebug!("[{self}] Unsupported version: too short"); return Output::None; } - qdebug!([self], "Unsupported version: {:x}", packet.wire_version()); + qdebug!("[{self}] Unsupported version: {:x}", packet.wire_version()); let vn = PacketBuilder::version_negotiation( &packet.scid()[..], &packet.dcid()[..], @@ -398,8 +396,7 @@ impl Server { self.conn_params.get_versions().all(), ); qdebug!( - [self], - "type={:?} path:{} {}->{} {:?} len {}", + "[{self}] type={:?} path:{} {}->{} {:?} len {}", PacketType::VersionNegotiation, packet.dcid(), dgram.destination(), @@ -426,7 +423,7 @@ impl Server { match packet.packet_type() { PacketType::Initial => { if dgram.len() < MIN_INITIAL_PACKET_SIZE { - qdebug!([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 @@ -436,12 +433,12 @@ impl Server { } PacketType::ZeroRtt => { let dcid = ConnectionId::from(packet.dcid()); - qdebug!([self], "Dropping 0-RTT for unknown connection {}", dcid); + qdebug!("[{self}] Dropping 0-RTT for unknown connection {dcid}"); Output::None } PacketType::OtherVersion => unreachable!(), _ => { - qtrace!([self], "Not an initial packet"); + qtrace!("[{self}] Not an initial packet"); Output::None } } diff --git a/neqo-transport/src/stats.rs b/neqo-transport/src/stats.rs index 33fdc10c2e..500a195f04 100644 --- a/neqo-transport/src/stats.rs +++ b/neqo-transport/src/stats.rs @@ -227,8 +227,8 @@ impl Stats { pub fn pkt_dropped(&mut self, reason: impl AsRef) { self.dropped_rx += 1; qwarn!( - [self.info], - "Dropped received packet: {}; Total: {}", + "[{}] 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..cffc51d736 100644 --- a/neqo-transport/src/streams.rs +++ b/neqo-transport/src/streams.rs @@ -183,7 +183,7 @@ impl Streams { } Frame::DataBlocked { data_limit } => { // Should never happen since we set data limit to max - qwarn!("Received DataBlocked with data limit {}", data_limit); + qwarn!("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 723492c448..117b62ba9b 100644 --- a/neqo-transport/src/tparams.rs +++ b/neqo-transport/src/tparams.rs @@ -139,7 +139,7 @@ pub enum TransportParameter { impl TransportParameter { fn encode(&self, enc: &mut Encoder, tp: TransportParameterId) { - qtrace!("TP encoded; type 0x{:02x} val {:?}", tp, self); + qtrace!("TP encoded; type 0x{tp:02x} val {self:?}"); enc.encode_varint(tp); match self { Self::Bytes(a) => { @@ -250,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)?; - qtrace!("TP {:x} length {:x}", tp, content.len()); + qtrace!("TP {tp:x} length {:x}", content.len()); let mut d = Decoder::from(content); let value = match tp { ORIGINAL_DESTINATION_CONNECTION_ID @@ -309,7 +309,7 @@ impl TransportParameter { if d.remaining() > 0 { return Err(Error::TooMuchData); } - qtrace!("TP decoded; type 0x{:02x} val {:?}", tp, value); + qtrace!("TP decoded; type 0x{tp:02x} val {value:?}"); Ok(Some((tp, value))) } } @@ -628,9 +628,7 @@ impl TransportParametersHandler { fn compatible_upgrade(&mut self, remote_tp: &TransportParameters) -> Res<()> { if let Some((current, other)) = remote_tp.get_versions() { qtrace!( - "Peer versions: {:x} {:x?}; config {:?}", - current, - other, + "Peer versions: {current:x} {other:x?}; config {:?}", self.versions, ); @@ -640,8 +638,7 @@ impl TransportParametersHandler { Ok(()) } else { qinfo!( - "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) @@ -649,8 +646,7 @@ impl TransportParametersHandler { } else { if current != self.versions.initial().wire_version() { qinfo!( - "Current version {:x} != own version {:x}", - current, + "Current version {current:x} != own version {:x}", self.versions.initial().wire_version(), ); return Err(Error::TransportParameterError); @@ -659,9 +655,8 @@ impl TransportParametersHandler { if let Some(preferred) = self.versions.preferred_compatible(other) { if preferred != self.versions.initial() { qinfo!( - "Compatible upgrade {:?} ==> {:?}", - self.versions.initial(), - preferred + "Compatible upgrade {:?} ==> {preferred:?}", + self.versions.initial() ); self.versions.set_initial(preferred); self.local.compatible_upgrade(preferred); @@ -684,7 +679,7 @@ impl ExtensionHandler for TransportParametersHandler { return ExtensionWriterResult::Skip; } - qdebug!("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(); @@ -696,8 +691,7 @@ impl ExtensionHandler for TransportParametersHandler { fn handle(&mut self, msg: HandshakeMessage, d: &[u8]) -> ExtensionHandlerResult { qtrace!( - "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 17ec6d6f9c..fc60d044c7 100644 --- a/neqo-transport/src/tracking.rs +++ b/neqo-transport/src/tracking.rs @@ -180,12 +180,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); + qtrace!("[{self}] Adding largest {pn}"); self.largest += 1; self.ack_needed = true; InsertionResult::Largest } else if self.smallest == (pn + 1) { - qtrace!([self], "Adding smallest {}", pn); + qtrace!("[{self}] Adding smallest {pn}"); self.smallest -= 1; self.ack_needed = true; InsertionResult::Smallest @@ -196,7 +196,7 @@ impl PacketRange { /// Maybe merge a higher-numbered range into this. fn merge_larger(&mut self, other: &Self) { - qinfo!([self], "Merging {}", other); + qinfo!("[{self}] Merging {other}"); // This only works if they are immediately adjacent. assert_eq!(self.largest + 1, other.smallest); @@ -369,10 +369,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); + qwarn!("[{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); + qdebug!("[{self}] Drop ACK range: {oldest}"); } self.min_tracked = oldest.largest + 1; } @@ -382,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); - qtrace!([self], "received {}, next: {}", pn, next_in_order_pn); + qtrace!("[{self}] received {pn}, next: {next_in_order_pn}"); self.add(pn); self.trim_ranges(); @@ -413,7 +413,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); + qdebug!("[{self}] Set ACK timer to {ack_time:?}"); self.ack_time = Some(ack_time); } largest @@ -422,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); - qdebug!([self], "immediate_ack at {:?}", now); + qdebug!("[{self}] immediate_ack at {now:?}"); } /// Check if the packet is a duplicate. @@ -601,7 +601,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()); + qtrace!("ack_time for {space} = {:?}", recvd.ack_time()); } } diff --git a/neqo-transport/src/version.rs b/neqo-transport/src/version.rs index fc6878941c..8381a9086b 100644 --- a/neqo-transport/src/version.rs +++ b/neqo-transport/src/version.rs @@ -189,9 +189,8 @@ impl VersionConfig { /// and by the client on resumption. pub(crate) fn set_initial(&mut self, initial: Version) { qdebug!( - "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 61f7fa1ca2..cbe3b2f4c0 100644 --- a/neqo-udp/src/lib.rs +++ b/neqo-udp/src/lib.rs @@ -71,9 +71,8 @@ pub fn recv_inner<'a>( if meta.len == 0 || meta.stride == 0 { qdebug!( - "ignoring datagram from {} to {} len {} stride {}", + "ignoring datagram from {} to {local_address} len {} stride {}", meta.addr, - local_address, meta.len, meta.stride ); @@ -84,10 +83,9 @@ pub fn recv_inner<'a>( }; qtrace!( - "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), ); @@ -269,7 +267,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 63fb56ce0b..4f04328a2b 100644 --- a/test-fixture/src/sim/connection.rs +++ b/test-fixture/src/sim/connection.rs @@ -145,7 +145,7 @@ impl Node for ConnectionNode { let mut active = false; while let Some(e) = self.c.next_event() { - qtrace!([self.c], "received event {:?}", e); + qtrace!("[{}] received event {e:?}", self.c); // Perform authentication automatically. if matches!(e, ConnectionEvent::AuthenticationNeeded) { @@ -160,7 +160,7 @@ impl Node for ConnectionNode { if matches!(res, Output::Datagram(_)) || !active { return res; } - qdebug!([self.c], "no datagram and goal activity, looping"); + qdebug!("[{}] no datagram and goal activity, looping", self.c); } } @@ -175,7 +175,7 @@ impl Node for ConnectionNode { } fn print_summary(&self, test_name: &str) { - qinfo!("{}: {:?}", test_name, self.c.stats()); + qinfo!("{test_name}: {:?}", self.c.stats()); } } @@ -233,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) { - qdebug!([c], "made stream {} for sending", stream_id); + qdebug!("[{c}] made stream {stream_id} for sending"); self.stream_id = Some(stream_id); } } @@ -249,7 +249,7 @@ impl SendData { return status; } self.remaining -= sent; - qtrace!("sent {} remaining {}", sent, self.remaining); + qtrace!("sent {sent} remaining {}", self.remaining); if self.remaining == 0 { c.stream_close_send(stream_id).unwrap(); return GoalStatus::Done; @@ -315,7 +315,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); + qtrace!("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 5969d0b282..35af6e0c46 100644 --- a/test-fixture/src/sim/mod.rs +++ b/test-fixture/src/sim/mod.rs @@ -199,25 +199,25 @@ impl Simulator { loop { for n in &mut self.nodes { if dgram.is_none() && !n.ready(now) { - qdebug!([self.name], "skipping {:?}", n.node); + qdebug!("[{}] kipping {:?}", self.name, n.node); continue; } - qdebug!([self.name], "processing {:?}", n.node); + qdebug!("[{}] 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()); + qtrace!("[{}] => datagram {}", self.name, d.len()); dgram = Some(d); Active } Output::Callback(delay) => { - qtrace!([self.name], " => callback {:?}", delay); + qtrace!("[{}] => callback {delay:?}", self.name); assert_ne!(delay, Duration::new(0, 0)); Waiting(now + delay) } Output::None => { - qtrace!([self.name], " => nothing"); + qtrace!("[{}] => nothing", self.name); assert!(n.done(), "nodes should be done when they go idle"); Idle } @@ -232,8 +232,8 @@ impl Simulator { let next = self.next_time(now); if next > now { qinfo!( - [self.name], - "advancing time by {:?} to {:?}", + "[{}] advancing time by {:?} to {:?}", + self.name, next - now, next - start ); diff --git a/test-fixture/src/sim/taildrop.rs b/test-fixture/src/sim/taildrop.rs index e29f458b38..b6e7466c59 100644 --- a/test-fixture/src/sim/taildrop.rs +++ b/test-fixture/src/sim/taildrop.rs @@ -176,8 +176,7 @@ impl Node for TailDrop { fn print_summary(&self, test_name: &str) { qinfo!( - "{}: taildrop: rx {} drop {} tx {} maxq {}", - test_name, + "{test_name}: taildrop: rx {} drop {} tx {} maxq {}", self.received, self.dropped, self.delivered,