Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# Changelog

## 0.2.2 (unreleased)

### Changed

- 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)

### Added
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sambrs"
version = "0.2.1"
version = "0.2.2"
authors = ["Samuel Van der Stappen <shogun_einst.0i@icloud.com>"]
license = "MIT"
edition = "2024"
Expand Down
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
66 changes: 53 additions & 13 deletions src/enumerate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand All @@ -37,6 +37,18 @@ pub struct Resources {
/// elements keep it `NETRESOURCEW`-aligned.
buf: Vec<u64>,
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 {
Expand All @@ -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
Expand All @@ -63,11 +77,30 @@ impl Iterator for Resources {
&raw mut size,
)
};
debug!("WNetEnumResourceW returned {status} (entries={count}, bytes={size})");
// 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 => {
Expand All @@ -81,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
Expand All @@ -109,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!("WNetCloseEnum returned {status}");
debug!(operation = "WNetCloseEnum", status, "WNet call returned");
}
}

fn open(scope: u32, root_remote: Option<&str>) -> Result<Resources> {
/// Open an enumeration inside `span`, which the returned iterator keeps.
fn open(span: Span, scope: u32, root_remote: Option<&str>) -> Result<Resources> {
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,
Expand All @@ -134,12 +171,14 @@ fn open(scope: u32, root_remote: Option<&str>) -> Result<Resources> {
&raw mut handle,
)
};
debug!("WNetOpenEnumW returned {status}");
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(),
})
}

Expand All @@ -149,8 +188,7 @@ fn open(scope: u32, root_remote: Option<&str>) -> Result<Resources> {
/// # Errors
/// See [`Error`].
pub fn connections() -> Result<Resources> {
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
Expand All @@ -159,8 +197,7 @@ pub fn connections() -> Result<Resources> {
/// # Errors
/// See [`Error`].
pub fn remembered() -> Result<Resources> {
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`,
Expand All @@ -173,6 +210,9 @@ pub fn remembered() -> Result<Resources> {
/// `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<Resources> {
trace!("enumerating disk shares on {server}");
open(WNet::RESOURCE_GLOBALNET, Some(server))
open(
debug_span!("server_shares", server),
WNet::RESOURCE_GLOBALNET,
Some(server),
)
}
7 changes: 6 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,12 @@ pub(crate) fn wnet_extended_error() -> Error {
crate::strings::len_u32(provider.len()),
)
};
tracing::debug!("WNetGetLastErrorW returned {status} (provider status {code})");
tracing::debug!(
operation = "WNetGetLastErrorW",
status,
provider_code = code,
"WNet call returned"
);
if status == NO_ERROR {
Error::ExtendedError {
code,
Expand Down
21 changes: 11 additions & 10 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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.
Expand All @@ -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<String> {
trace!("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 {
Expand All @@ -55,14 +55,12 @@ pub fn get_connection(drive: &str) -> Result<String> {
/// # Errors
/// `ERROR_NOT_CONNECTED` if the name is not a connected resource.
pub fn get_user(connection: &str) -> Result<String> {
trace!("querying user for {connection}");
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!("WNetGetUserW resolved user {user}");
Ok(user)
})
}

/// The UNC path for a local path on a redirected drive, via
Expand All @@ -73,7 +71,7 @@ pub fn get_user(connection: &str) -> Result<String> {
/// `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<String> {
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];
Expand All @@ -89,7 +87,10 @@ pub fn get_universal_name(local_path: &str) -> Result<String> {
&raw mut size,
)
};
debug!("WNetGetUniversalNameW returned {status}");
debug!(
operation = "WNetGetUniversalNameW",
status, "WNet call returned"
);
match status {
NO_ERROR => {
// SAFETY: on success the buffer starts with a
Expand Down
Loading
Loading