From 0bf954547b1e28dae8efeeee83f847e0db5b2b6f Mon Sep 17 00:00:00 2001 From: Samuel Van der Stappen Date: Mon, 9 Nov 2026 02:18:09 +0000 Subject: [PATCH 1/2] use structured tracing fields instead of message interpolation Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- src/enumerate.rs | 13 +++++++++---- src/error.rs | 2 +- src/query.rs | 10 +++++----- src/target.rs | 32 ++++++++++++++++++++------------ 7 files changed, 48 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f725b7f..b741f47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.2.2 (unreleased) + +### Changed + +- Log events are now structured: values such as `status`, `remote`, `user`, + `flags`, and `error` are recorded as `tracing` fields instead of being + interpolated into the message, so subscribers can filter and aggregate on + them. Messages are now constant per event. Numeric flags and results are + recorded as integers rather than hex strings, and the `user` field is absent + when connecting as the logged-on user. + ## 0.2.1 (2026-11-09) ### Added diff --git a/Cargo.lock b/Cargo.lock index 9dcb541..d5ec90c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "sambrs" -version = "0.2.1" +version = "0.2.2" dependencies = [ "tracing", "windows-sys", diff --git a/Cargo.toml b/Cargo.toml index e13378a..9db49ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sambrs" -version = "0.2.1" +version = "0.2.2" authors = ["Samuel Van der Stappen "] license = "MIT" edition = "2024" diff --git a/src/enumerate.rs b/src/enumerate.rs index 0ab5e9b..942955d 100644 --- a/src/enumerate.rs +++ b/src/enumerate.rs @@ -63,7 +63,12 @@ impl Iterator for Resources { &raw mut size, ) }; - debug!("WNetEnumResourceW returned {status} (entries={count}, bytes={size})"); + debug!( + status, + entries = count, + bytes = size, + "WNetEnumResourceW returned" + ); match status { NO_ERROR if count == 0 => { trace!("zero-entry success; treating as end of enumeration"); @@ -111,7 +116,7 @@ impl Drop for Resources { fn drop(&mut self) { // SAFETY: the handle came from WNetOpenEnumW and is closed only here. let status = unsafe { WNet::WNetCloseEnum(self.handle) }; - debug!("WNetCloseEnum returned {status}"); + debug!(status, "WNetCloseEnum returned"); } } @@ -134,7 +139,7 @@ fn open(scope: u32, root_remote: Option<&str>) -> Result { &raw mut handle, ) }; - debug!("WNetOpenEnumW returned {status}"); + debug!(status, "WNetOpenEnumW returned"); check_wnet(status)?; Ok(Resources { handle, @@ -173,6 +178,6 @@ pub fn remembered() -> Result { /// `ERROR_BAD_NET_NAME` / `ERROR_NO_NET_OR_BAD_PATH` when the server cannot /// be found, or `ERROR_ACCESS_DENIED` when it refuses anonymous enumeration. pub fn server_shares(server: &str) -> Result { - trace!("enumerating disk shares on {server}"); + trace!(server, "enumerating disk shares on server"); open(WNet::RESOURCE_GLOBALNET, Some(server)) } diff --git a/src/error.rs b/src/error.rs index 062917f..385b60e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -134,7 +134,7 @@ pub(crate) fn wnet_extended_error() -> Error { crate::strings::len_u32(provider.len()), ) }; - tracing::debug!("WNetGetLastErrorW returned {status} (provider status {code})"); + tracing::debug!(status, provider_status = code, "WNetGetLastErrorW returned"); if status == NO_ERROR { Error::ExtendedError { code, diff --git a/src/query.rs b/src/query.rs index ff374e6..fb8c9b9 100644 --- a/src/query.rs +++ b/src/query.rs @@ -15,7 +15,7 @@ fn wide_out(operation: &str, mut call: impl FnMut(*mut u16, *mut u32) -> u32) -> for _ in 0..4 { let mut len = len_u32(buf.len()); let status = call(buf.as_mut_ptr(), &raw mut len); - debug!("{operation} returned {status}"); + debug!(operation, status, "WNet call returned"); match status { NO_ERROR => return Ok(crate::strings::from_wide_buf(&buf)), // `len` now holds the required size in characters. @@ -40,7 +40,7 @@ fn wide_out(operation: &str, mut call: impl FnMut(*mut u16, *mut u32) -> u32) -> /// `ERROR_CONNECTION_UNAVAIL` if it is remembered but not currently /// connected, or `ERROR_BAD_DEVICE` for an invalid device name. pub fn get_connection(drive: &str) -> Result { - trace!("querying remote share mapped to {drive}"); + trace!(drive, "querying remote share mapped to drive"); let device = to_wide(drive)?; // SAFETY: `device` outlives the call; the buffer is sized via `len`. wide_out("WNetGetConnectionW", |buf, len| unsafe { @@ -55,13 +55,13 @@ pub fn get_connection(drive: &str) -> Result { /// # Errors /// `ERROR_NOT_CONNECTED` if the name is not a connected resource. pub fn get_user(connection: &str) -> Result { - trace!("querying user for {connection}"); + trace!(connection, "querying connection user"); let name = to_wide(connection)?; // SAFETY: `name` outlives the call. let user = wide_out("WNetGetUserW", |buf, len| unsafe { WNet::WNetGetUserW(name.as_ptr(), buf, len) })?; - debug!("WNetGetUserW resolved user {user}"); + debug!(user = user.as_str(), "WNetGetUserW resolved user"); Ok(user) } @@ -89,7 +89,7 @@ pub fn get_universal_name(local_path: &str) -> Result { &raw mut size, ) }; - debug!("WNetGetUniversalNameW returned {status}"); + debug!(status, "WNetGetUniversalNameW returned"); match status { NO_ERROR => { // SAFETY: on success the buffer starts with a diff --git a/src/target.rs b/src/target.rs index 9209351..5db5006 100644 --- a/src/target.rs +++ b/src/target.rs @@ -156,9 +156,10 @@ impl SmbTarget { let resource = args.resource(); trace!( - "connecting to {} as {} with flags {flags:#x}", - self.remote, - self.username.as_deref().unwrap_or("") + remote = self.remote.as_str(), + user = self.username.as_deref(), + flags, + "connecting" ); // SAFETY: all pointers in `resource` and the credential pointers stay @@ -173,7 +174,7 @@ impl SmbTarget { ) }; - debug!("WNetAddConnection2W returned {status}"); + debug!(status, "WNetAddConnection2W returned"); check_wnet(status) } @@ -194,9 +195,10 @@ impl SmbTarget { let resource = args.resource(); trace!( - "auto-connecting to {} as {} with flags {flags:#x}", - self.remote, - self.username.as_deref().unwrap_or("") + remote = self.remote.as_str(), + user = self.username.as_deref(), + flags, + "auto-connecting" ); // Sized so any real access name fits on the first call: the name is @@ -224,7 +226,7 @@ impl SmbTarget { &raw mut result, ) }; - debug!("WNetUseConnectionW returned {status}, result {result:#x}"); + debug!(status, result, "WNetUseConnectionW returned"); check_wnet(status)?; Ok(from_wide_buf(&access_name)) } @@ -321,8 +323,10 @@ pub fn cancel_connection(name: &str, options: DisconnectOptions) -> Result<()> { } let wide = to_wide(name)?; trace!( - "disconnecting {name} (force={}, forget={})", - options.force, options.forget + name, + force = options.force, + forget = options.forget, + "disconnecting" ); // SAFETY: `wide` is a valid nul-terminated string outliving the call. let flags = if options.forget { @@ -332,7 +336,7 @@ pub fn cancel_connection(name: &str, options: DisconnectOptions) -> Result<()> { }; let status = unsafe { WNet::WNetCancelConnection2W(wide.as_ptr(), flags, i32::from(options.force)) }; - debug!("WNetCancelConnection2W returned {status}"); + debug!(status, "WNetCancelConnection2W returned"); check_wnet(status) } @@ -384,7 +388,11 @@ impl Drop for Connection { if self.armed && let Err(e) = cancel_connection(&self.device, DisconnectOptions::default()) { - debug!("failed to disconnect {} on guard drop: {e}", self.device); + debug!( + device = self.device.as_str(), + error = %e, + "failed to disconnect on guard drop" + ); } } } From e235f750a335a45821722eabac9ed3c589a4a2cd Mon Sep 17 00:00:00 2001 From: Samuel Van der Stappen Date: Mon, 9 Nov 2026 02:30:00 +0000 Subject: [PATCH 2/2] add operation spans and tidy log levels after logging review Wrap every public operation in a debug span carrying its inputs, give all WNet call events a uniform operation/status shape, move per-entry enumeration events to trace with a finishing summary, log the access name connect_auto assigns, warn when a guard cannot disconnect on drop, drop the redundant resolved-user event, and document the logging in the README. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 ++++++++++---- README.md | 23 +++++++++++++-- src/enumerate.rs | 71 +++++++++++++++++++++++++++++++++----------- src/error.rs | 7 ++++- src/query.rs | 19 ++++++------ src/target.rs | 77 +++++++++++++++++++++++++++++++++--------------- 6 files changed, 159 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b741f47..17a1495 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,22 @@ ### Changed -- Log events are now structured: values such as `status`, `remote`, `user`, - `flags`, and `error` are recorded as `tracing` fields instead of being - interpolated into the message, so subscribers can filter and aggregate on - them. Messages are now constant per event. Numeric flags and results are - recorded as integers rather than hex strings, and the `user` field is absent - when connecting as the logged-on user. +- Logging is structured. Every public operation opens a `debug` span named + after the function, with its inputs (`remote`, `user`, `local`, `flags`, + `name`, `drive`, `path`, `server`, and so on) as fields, so every event + inside it carries that context. Usernames therefore appear at debug level; + passwords are still never logged. +- Every Windows call emits one `debug` event, `"WNet call returned"`, with + `operation` and the raw `status` as fields, so `status != 0` finds every + failed call. Flags and results are integers rather than hex strings. +- Enumeration logs each entry at `trace` and a single `debug` summary with the + number of `entries` when it finishes. +- `connect_auto` logs the access name Windows assigned. +- A `Connection` guard that fails to disconnect on drop now logs a `warn` + event, since it cannot return the error. A drive that was already + disconnected stays at `debug`. +- `WNetGetUserW` no longer logs the resolved user name; it is the return value. +- The README documents the span and field names. ## 0.2.1 (2026-11-09) diff --git a/README.md b/README.md index eade558..781ecec 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,26 @@ It deliberately does not create or administer shares, handle printers, expose raw `WNet` controls, or transfer files. See the [boundary ADR](https://github.com/samvdst/sambrs/blob/main/docs/adr/0001-opinionated-smb-client-boundary.md). -Passwords and their temporary UTF-16 buffers are wiped on drop. Operations, -targets, usernames, options, and raw Windows statuses are emitted through -`tracing`; passwords are never logged. +Passwords and their temporary UTF-16 buffers are wiped on drop, and are +never logged. + +### Logging + +sambrs logs through [`tracing`](https://docs.rs/tracing) and leaves output to +your subscriber. Every public operation opens a `debug` span named after the +function (`connect_with`, `connect_auto`, `cancel_connection`, +`get_connection`, `get_user`, `get_universal_name`, `connections`, +`remembered`, `server_shares`) with its inputs as fields: `remote`, `user` +(absent for the logged-on user), `local`, `flags`, `name`, `force`, `forget`, +`drive`, `connection`, `path`, `server`. Usernames therefore appear at debug +level. + +Inside a span, each Windows call emits a `debug` event, `"WNet call +returned"`, with `operation` (the Windows function) and its raw `status`, so +filtering on `status != 0` shows every failed call. Per-entry enumeration +calls stay at `trace`. Failures are returned as `Error`s rather than logged; +the one exception is a `Connection` guard that cannot disconnect on drop, +which emits a `warn` event because it has no other way to report it. ## Installation diff --git a/src/enumerate.rs b/src/enumerate.rs index 942955d..99e4813 100644 --- a/src/enumerate.rs +++ b/src/enumerate.rs @@ -12,7 +12,7 @@ use crate::error::{Error, Result, check_wnet, wnet_extended_error}; use crate::strings::{from_pwstr, len_u32, to_wide}; -use tracing::{debug, trace}; +use tracing::{Span, debug, debug_span, trace}; use windows_sys::Win32::Foundation::{ ERROR_EXTENDED_ERROR, ERROR_MORE_DATA, ERROR_NO_MORE_ITEMS, HANDLE, NO_ERROR, }; @@ -37,6 +37,18 @@ pub struct Resources { /// elements keep it `NETRESOURCEW`-aligned. buf: Vec, finished: bool, + /// Resources yielded so far, reported when the enumeration finishes. + entries: usize, + /// The span of the call that opened this enumeration, re-entered on every + /// step so later events stay attached to it. + span: Span, +} + +impl Resources { + fn finish(&mut self) { + self.finished = true; + debug!(entries = self.entries, "enumeration finished"); + } } impl Iterator for Resources { @@ -46,6 +58,8 @@ impl Iterator for Resources { if self.finished { return None; } + let span = self.span.clone(); + let _entered = span.enter(); // Bounded retries as a defensive measure against a misbehaving // provider that keeps demanding a bigger buffer (mirrors the cap in @@ -63,16 +77,30 @@ impl Iterator for Resources { &raw mut size, ) }; - debug!( - status, - entries = count, - bytes = size, - "WNetEnumResourceW returned" - ); + // One call per resource: routine results stay at trace so a large + // enumeration does not flood debug output; anything else is a + // failure or a buffer retry and stays visible at debug. + if matches!(status, NO_ERROR | ERROR_NO_MORE_ITEMS) { + trace!( + operation = "WNetEnumResourceW", + status, + count, + bytes = size, + "WNet call returned" + ); + } else { + debug!( + operation = "WNetEnumResourceW", + status, + count, + bytes = size, + "WNet call returned" + ); + } match status { NO_ERROR if count == 0 => { trace!("zero-entry success; treating as end of enumeration"); - self.finished = true; + self.finish(); return None; } NO_ERROR => { @@ -86,10 +114,11 @@ impl Iterator for Resources { remote_name: from_pwstr(raw.lpRemoteName), } }; + self.entries += 1; return Some(Ok(resource)); } ERROR_NO_MORE_ITEMS => { - self.finished = true; + self.finish(); return None; } // Buffer too small for a single entry; `size` holds the @@ -114,13 +143,16 @@ impl Iterator for Resources { impl Drop for Resources { fn drop(&mut self) { + let _entered = self.span.enter(); // SAFETY: the handle came from WNetOpenEnumW and is closed only here. let status = unsafe { WNet::WNetCloseEnum(self.handle) }; - debug!(status, "WNetCloseEnum returned"); + debug!(operation = "WNetCloseEnum", status, "WNet call returned"); } } -fn open(scope: u32, root_remote: Option<&str>) -> Result { +/// Open an enumeration inside `span`, which the returned iterator keeps. +fn open(span: Span, scope: u32, root_remote: Option<&str>) -> Result { + let entered = span.entered(); let remote = root_remote.map(to_wide).transpose()?; let root = remote.as_ref().map(|remote| WNet::NETRESOURCEW { dwUsage: WNet::RESOURCEUSAGE_CONTAINER, @@ -139,12 +171,14 @@ fn open(scope: u32, root_remote: Option<&str>) -> Result { &raw mut handle, ) }; - debug!(status, "WNetOpenEnumW returned"); + debug!(operation = "WNetOpenEnumW", status, "WNet call returned"); check_wnet(status)?; Ok(Resources { handle, buf: vec![0u64; 2048], // 16 KiB to start; grows on demand finished: false, + entries: 0, + span: entered.exit(), }) } @@ -154,8 +188,7 @@ fn open(scope: u32, root_remote: Option<&str>) -> Result { /// # Errors /// See [`Error`]. pub fn connections() -> Result { - trace!("enumerating active disk-share connections"); - open(WNet::RESOURCE_CONNECTED, None) + open(debug_span!("connections"), WNet::RESOURCE_CONNECTED, None) } /// Remembered (persistent) connections (`RESOURCE_REMEMBERED`) — restored at @@ -164,8 +197,7 @@ pub fn connections() -> Result { /// # Errors /// See [`Error`]. pub fn remembered() -> Result { - trace!("enumerating remembered disk-share mappings"); - open(WNet::RESOURCE_REMEMBERED, None) + open(debug_span!("remembered"), WNet::RESOURCE_REMEMBERED, None) } /// The disk shares a server exposes (`RESOURCE_GLOBALNET` rooted at `server`, @@ -178,6 +210,9 @@ pub fn remembered() -> Result { /// `ERROR_BAD_NET_NAME` / `ERROR_NO_NET_OR_BAD_PATH` when the server cannot /// be found, or `ERROR_ACCESS_DENIED` when it refuses anonymous enumeration. pub fn server_shares(server: &str) -> Result { - trace!(server, "enumerating disk shares on server"); - open(WNet::RESOURCE_GLOBALNET, Some(server)) + open( + debug_span!("server_shares", server), + WNet::RESOURCE_GLOBALNET, + Some(server), + ) } diff --git a/src/error.rs b/src/error.rs index 385b60e..2ef7cd9 100644 --- a/src/error.rs +++ b/src/error.rs @@ -134,7 +134,12 @@ pub(crate) fn wnet_extended_error() -> Error { crate::strings::len_u32(provider.len()), ) }; - tracing::debug!(status, provider_status = code, "WNetGetLastErrorW returned"); + tracing::debug!( + operation = "WNetGetLastErrorW", + status, + provider_code = code, + "WNet call returned" + ); if status == NO_ERROR { Error::ExtendedError { code, diff --git a/src/query.rs b/src/query.rs index fb8c9b9..628399c 100644 --- a/src/query.rs +++ b/src/query.rs @@ -4,7 +4,7 @@ use crate::error::{Error, Result, wnet_extended_error}; use crate::strings::{from_pwstr, len_u32, to_wide}; -use tracing::{debug, trace}; +use tracing::{debug, debug_span}; use windows_sys::Win32::Foundation::{ERROR_EXTENDED_ERROR, ERROR_MORE_DATA, NO_ERROR}; use windows_sys::Win32::NetworkManagement::WNet; @@ -40,7 +40,7 @@ fn wide_out(operation: &str, mut call: impl FnMut(*mut u16, *mut u32) -> u32) -> /// `ERROR_CONNECTION_UNAVAIL` if it is remembered but not currently /// connected, or `ERROR_BAD_DEVICE` for an invalid device name. pub fn get_connection(drive: &str) -> Result { - trace!(drive, "querying remote share mapped to drive"); + let _span = debug_span!("get_connection", drive).entered(); let device = to_wide(drive)?; // SAFETY: `device` outlives the call; the buffer is sized via `len`. wide_out("WNetGetConnectionW", |buf, len| unsafe { @@ -55,14 +55,12 @@ pub fn get_connection(drive: &str) -> Result { /// # Errors /// `ERROR_NOT_CONNECTED` if the name is not a connected resource. pub fn get_user(connection: &str) -> Result { - trace!(connection, "querying connection user"); + let _span = debug_span!("get_user", connection).entered(); let name = to_wide(connection)?; // SAFETY: `name` outlives the call. - let user = wide_out("WNetGetUserW", |buf, len| unsafe { + wide_out("WNetGetUserW", |buf, len| unsafe { WNet::WNetGetUserW(name.as_ptr(), buf, len) - })?; - debug!(user = user.as_str(), "WNetGetUserW resolved user"); - Ok(user) + }) } /// The UNC path for a local path on a redirected drive, via @@ -73,7 +71,7 @@ pub fn get_user(connection: &str) -> Result { /// `ERROR_NOT_SUPPORTED` or `ERROR_NOT_CONNECTED` when the path is not on a /// network-redirected device. pub fn get_universal_name(local_path: &str) -> Result { - trace!("resolving universal name for mapped path"); + let _span = debug_span!("get_universal_name", path = local_path).entered(); let path = to_wide(local_path)?; // u64 elements keep the buffer aligned for UNIVERSAL_NAME_INFOW. let mut buf = vec![0u64; 128]; @@ -89,7 +87,10 @@ pub fn get_universal_name(local_path: &str) -> Result { &raw mut size, ) }; - debug!(status, "WNetGetUniversalNameW returned"); + debug!( + operation = "WNetGetUniversalNameW", + status, "WNet call returned" + ); match status { NO_ERROR => { // SAFETY: on success the buffer starts with a diff --git a/src/target.rs b/src/target.rs index 5db5006..8c3b065 100644 --- a/src/target.rs +++ b/src/target.rs @@ -1,7 +1,8 @@ use crate::error::{Error, Result, check_wnet}; use crate::options::{ConnectOptions, DisconnectOptions, DriveLetter}; use crate::strings::{WideSecret, from_wide_buf, len_u32, opt_ptr, to_wide}; -use tracing::{debug, trace}; +use tracing::{debug, debug_span, warn}; +use windows_sys::Win32::Foundation::ERROR_NOT_CONNECTED; use windows_sys::Win32::NetworkManagement::WNet; /// The wide-string buffers for one connect call, converted from an @@ -155,12 +156,14 @@ impl SmbTarget { let args = ConnectArgs::new(self)?; let resource = args.resource(); - trace!( + let _span = debug_span!( + "connect_with", remote = self.remote.as_str(), user = self.username.as_deref(), + local = self.local.as_deref(), flags, - "connecting" - ); + ) + .entered(); // SAFETY: all pointers in `resource` and the credential pointers stay // valid for the duration of the call — they borrow from the buffers @@ -174,7 +177,10 @@ impl SmbTarget { ) }; - debug!(status, "WNetAddConnection2W returned"); + debug!( + operation = "WNetAddConnection2W", + status, "WNet call returned" + ); check_wnet(status) } @@ -194,12 +200,14 @@ impl SmbTarget { let args = ConnectArgs::new(self)?; let resource = args.resource(); - trace!( + let _span = debug_span!( + "connect_auto", remote = self.remote.as_str(), user = self.username.as_deref(), + local = self.local.as_deref(), flags, - "auto-connecting" - ); + ) + .entered(); // Sized so any real access name fits on the first call: the name is // either a mapped drive ("Z:", nowhere near 1024) or, for @@ -226,9 +234,16 @@ impl SmbTarget { &raw mut result, ) }; - debug!(status, result, "WNetUseConnectionW returned"); + debug!( + operation = "WNetUseConnectionW", + status, result, "WNet call returned" + ); check_wnet(status)?; - Ok(from_wide_buf(&access_name)) + // Windows may have just mapped a drive of its choosing; record which, + // so a lingering mapping can be traced back here. + let access_name = from_wide_buf(&access_name); + debug!(access_name = access_name.as_str(), "connected"); + Ok(access_name) } /// Connect and return an RAII [`Connection`] guard that disconnects when @@ -318,16 +333,17 @@ impl SmbTarget { /// # Errors /// See [`Error`]. pub fn cancel_connection(name: &str, options: DisconnectOptions) -> Result<()> { + let _span = debug_span!( + "cancel_connection", + name, + force = options.force, + forget = options.forget, + ) + .entered(); if options.forget && !is_drive(name) { return Err(Error::ForgetRequiresDrive); } let wide = to_wide(name)?; - trace!( - name, - force = options.force, - forget = options.forget, - "disconnecting" - ); // SAFETY: `wide` is a valid nul-terminated string outliving the call. let flags = if options.forget { WNet::CONNECT_UPDATE_PROFILE @@ -336,7 +352,10 @@ pub fn cancel_connection(name: &str, options: DisconnectOptions) -> Result<()> { }; let status = unsafe { WNet::WNetCancelConnection2W(wide.as_ptr(), flags, i32::from(options.force)) }; - debug!(status, "WNetCancelConnection2W returned"); + debug!( + operation = "WNetCancelConnection2W", + status, "WNet call returned" + ); check_wnet(status) } @@ -346,7 +365,8 @@ fn is_drive(name: &str) -> bool { /// RAII guard returned by [`SmbTarget::connect_guarded`] and /// [`SmbTarget::connect_auto_guarded`]: cancels the connection when dropped -/// (best effort — a failure on drop is only visible as a `tracing` event). +/// (best effort — a failure on drop is only reported as a `tracing` warning; +/// a drive that was already disconnected is logged at debug level). /// /// A guard always owns a drive mapping ([`Connection::device`]) and cancels /// exactly that drive, never the remote name. The drive was @@ -388,11 +408,22 @@ impl Drop for Connection { if self.armed && let Err(e) = cancel_connection(&self.device, DisconnectOptions::default()) { - debug!( - device = self.device.as_str(), - error = %e, - "failed to disconnect on guard drop" - ); + // Drop cannot return the error, so this event is the only + // report. A drive that is already gone is harmless; anything + // else may leave the drive mapped. + if e.code() == Some(ERROR_NOT_CONNECTED) { + debug!( + device = self.device.as_str(), + error = %e, + "connection already gone on guard drop" + ); + } else { + warn!( + device = self.device.as_str(), + error = %e, + "failed to disconnect on guard drop; the drive may stay mapped" + ); + } } } }