mod durable;
mod lease;
mod leases;
mod table;
mod watch;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::RwLock;
use tracing::debug;
use crate::access_mask::{FILE_APPEND_DATA, FILE_WRITE_DATA};
use crate::backend::{FileInfo, Handle};
use crate::conn::state::Open;
use crate::handlers::shared::restore_fixed_times;
use crate::ntstatus;
use crate::proto::messages::change_notify::{FILE_ACTION_MODIFIED, FILE_ACTION_MODIFIED_STREAM};
use crate::stream::data_stream_info;
pub(crate) use durable::{Claim, Durability, DurableReg, DurableTable, Unclaimed, v2_timeout};
pub use durable::{DEFAULT_DURABLE_HANDLE_TIMEOUT, DEFAULT_MAX_DISCONNECTED_OPENS};
pub(crate) use lease::{Granted, LeaseId, LeaseRequest, LeaseState, LeaseVersion, Trigger};
#[cfg(test)]
pub(crate) use leases::LEASE_BREAK_TIMEOUT;
pub(crate) use leases::{AfterSend, BreakWait, LeaseRef, LeaseTable, MAX_BREAK_WAIT};
pub(crate) use table::{FileRef, FileTable, OpenRequest, Refused, Sharing};
#[cfg(test)]
pub(crate) use watch::MAX_WATCHES_PER_CONNECTION;
pub(crate) use watch::{
Answer, CONTENT_CHANGED, Change, EA_CHANGED, NotifyBudget, STREAM_BASE_CHANGED, STREAM_CHANGED,
WatchReg, WatchTable,
};
pub const DEFAULT_MAX_OPENS_PER_CONNECTION: usize = 16384;
pub const DEFAULT_MAX_LOCKS_PER_OPEN: usize = 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Closing {
ReadOnly,
Unwritten,
RestoresTimes,
Wrote,
StreamWrote { moved: bool },
StreamResized,
}
impl Closing {
pub(crate) fn announce(open: &Open, restores_times: bool) -> Self {
let fixed = open.fixed_times;
let wrote = open.wrote.load(Ordering::Acquire);
let closing = if open.on_stream {
if wrote || open.moved_data {
Self::StreamWrote {
moved: open.moved_data,
}
} else if open.resized.load(Ordering::Acquire) {
Self::StreamResized
} else {
Self::ReadOnly
}
} else if wrote {
Self::Wrote
} else if restores_times
&& (fixed.last_access_time.is_some() || fixed.last_write_time.is_some())
{
Self::RestoresTimes
} else if !open.is_directory
&& (open.created || open.granted_access & (FILE_WRITE_DATA | FILE_APPEND_DATA) != 0)
{
Self::Unwritten
} else {
Self::ReadOnly
};
if let Some(file) = &open.file {
let watches = &file.share().watches;
match closing {
_ if open.eas_changed.load(Ordering::Acquire) => watches.touch(&file.path()),
Self::ReadOnly => {}
Self::Unwritten => watches.closed(&file.path()),
Self::RestoresTimes
| Self::Wrote
| Self::StreamWrote { .. }
| Self::StreamResized => watches.touch(&file.path()),
}
}
closing
}
}
pub(crate) struct OpenSlot(Arc<AtomicUsize>);
impl OpenSlot {
pub(crate) fn acquire(count: &Arc<AtomicUsize>, limit: usize) -> Option<Self> {
count
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
(n < limit).then_some(n + 1)
})
.ok()
.map(|_| Self(Arc::clone(count)))
}
}
impl Drop for OpenSlot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
pub(crate) async fn close_open(open_arc: &Arc<RwLock<Open>>, want_attrs: bool) -> Option<FileInfo> {
let mut open = open_arc.write().await;
drop(open.watch.take());
let closing = Closing::announce(&open, true);
let eas_changed = open.eas_changed.load(Ordering::Acquire);
restore_fixed_times(&open).await;
let handle = open.handle.take();
let file = open.file.take();
if handle.is_none() && file.is_none() {
return None;
}
let info = match &handle {
Some(handle) if want_attrs => handle.stat().await.ok(),
_ => None,
};
let info = match info {
Some(info) if open.on_stream => Some(data_stream_info(info)),
info => info,
};
open.slot.take();
let delete_on_close = open.delete_on_close;
let is_directory = open.is_directory;
drop(open);
finish_close(
handle,
file,
delete_on_close,
is_directory,
closing,
eas_changed,
)
.await;
info
}
pub(crate) async fn finish_close(
handle: Option<Box<dyn Handle>>,
file: Option<FileRef>,
delete_on_close: bool,
is_directory: bool,
closing: Closing,
eas_changed: bool,
) {
let contents = match closing {
Closing::Wrote | Closing::StreamWrote { moved: true } => CONTENT_CHANGED,
Closing::StreamWrote { moved: false } => STREAM_BASE_CHANGED,
_ => 0,
};
let filter = contents | if eas_changed { EA_CHANGED } else { 0 };
let file_filter = (filter != 0).then_some(filter);
let on_stream = file.as_ref().is_some_and(|f| f.stream().is_some());
let deletes = delete_on_close && !file.as_ref().is_some_and(FileRef::stream_delete_pending);
let stream_changed = on_stream
&& (deletes
|| matches!(
closing,
Closing::StreamWrote { .. } | Closing::StreamResized
));
let share = file.as_ref().map(|f| Arc::clone(f.share()));
let exclusive = match &share {
Some(share) if delete_on_close && is_directory => Some(share.files.rename_lock().await),
_ => None,
};
let delete_on_close = delete_on_close
&& (!is_directory
|| match &handle {
Some(handle) => handle.dir_is_empty().await.unwrap_or(false),
None => false,
});
if let Some(handle) = handle
&& let Err(e) = handle.close().await
{
let path = file.as_ref().map(FileRef::path).unwrap_or_default();
debug!(error = %e, path = %path, "backend close failed");
}
let (Some(file), Some(share)) = (file, &share) else {
return;
};
let marks_deleted = delete_on_close && is_directory;
let marked = if marks_deleted {
file.open_paths()
} else {
Vec::new()
};
let reports = file_filter.is_some() || stream_changed;
let names = if exclusive.is_none() && reports && !share.watches.is_empty() {
Some(share.files.names_lock().await)
} else {
None
};
let heard = names.is_some() || exclusive.is_some();
let path = file.path();
let stream = file.stream();
let mut changes = Vec::new();
if let Some(filter) = file_filter {
changes.push(Change {
path: &path,
stream: None,
action: FILE_ACTION_MODIFIED,
filter,
seen: true,
});
}
if stream_changed {
changes.push(Change {
path: &path,
stream: stream.as_ref(),
action: FILE_ACTION_MODIFIED_STREAM,
filter: STREAM_CHANGED,
seen: false,
});
}
match file.release(delete_on_close) {
Some(pending) => {
if heard && pending.is_stream() && !changes.is_empty() {
share.watches.report(&changes);
}
drop(names);
drop(exclusive);
pending.run().await;
}
None => {
if heard && !changes.is_empty() {
share.watches.report(&changes);
}
for path in &marked {
share.watches.end_at(path, ntstatus::STATUS_DELETE_PENDING);
}
}
}
}
pub(crate) async fn close_opens(opens: Vec<Arc<RwLock<Open>>>) {
end_opens(opens, None).await;
}
pub(crate) async fn end_opens(
opens: Vec<Arc<RwLock<Open>>>,
keep: Option<(&Arc<DurableTable>, u64)>,
) {
let tasks: Vec<_> = opens
.into_iter()
.map(|open| {
let keep = keep.map(|(table, since)| (Arc::clone(table), since));
tokio::spawn(async move {
let open = match keep {
Some((table, since)) => table.preserve(open, since).await,
None => Some(open),
};
if let Some(open) = open {
close_open(&open, false).await;
}
})
})
.collect();
for task in tasks {
let _ = task.await;
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
use crate::access_mask::DELETE;
use crate::backend::{FileTimes, OpenIntent, OpenOptions};
use crate::builder::Access;
use crate::conn::state::{Connection, Session, TreeConnect};
use crate::error::SmbError;
use crate::path::SmbPath;
use crate::proto::auth::ntlm::Identity;
use crate::proto::messages::FileId;
use crate::server::{ShareBindings, ShareMode};
use crate::tests::memfs::MemFsBackend;
fn share() -> Arc<ShareBindings> {
share_on(MemFsBackend::new())
}
fn share_on(backend: MemFsBackend) -> Arc<ShareBindings> {
ShareBindings::new(
"s".to_string(),
Arc::new(backend),
ShareMode::Public,
HashMap::new(),
false,
true,
true,
)
}
async fn drop_without_close(
share: &Arc<ShareBindings>,
path: &str,
directory: bool,
) -> SmbPath {
let path: SmbPath = path.parse().unwrap();
let opts = OpenOptions {
directory,
intent: OpenIntent::OpenOrCreate,
..OpenOptions::default()
};
let (handle, _) = share.backend.open(&path, opts).await.unwrap();
let info = handle.stat().await.unwrap();
let sharing = Sharing {
access: DELETE,
share: 0,
};
let file = FileRef::register(share, &info, &path, sharing.into())
.unwrap()
.0;
drop(Open {
file_id: FileId::default(),
handle: Some(handle),
granted_access: DELETE,
is_directory: directory,
on_stream: false,
delete_on_close: true,
search_state: None,
fixed_times: FileTimes::default(),
create_options: 0,
file: Some(file),
slot: None,
durable: None,
watch: None,
wrote: Default::default(),
created: false,
marked_deleted: Default::default(),
ea_cursor: Default::default(),
eas_changed: Default::default(),
resized: Default::default(),
moved_data: false,
});
let in_table = || {
share.files.path_is_open(&path, false) || share.files.delete_pending_at(&path, false)
};
for _ in 0..100 {
if !in_table() {
break;
}
tokio::task::yield_now().await;
}
assert!(!in_table());
path
}
#[tokio::test]
async fn a_dropped_delete_on_close_open_removes_the_file() {
let s = share();
let path = drop_without_close(&s, "f", false).await;
let missing = s.backend.open(&path, OpenOptions::default()).await;
assert!(matches!(missing, Err(SmbError::NotFound)));
}
#[tokio::test]
async fn a_dropped_delete_on_close_open_keeps_a_directory_with_entries() {
let s = share_on(MemFsBackend::new().with_file("d\\f", b"x"));
let path = drop_without_close(&s, "d", true).await;
let opts = OpenOptions {
directory: true,
..OpenOptions::default()
};
assert!(s.backend.open(&path, opts).await.is_ok());
}
#[tokio::test]
async fn sweeps_match_the_share_not_its_name() {
let removed = share();
let added = share();
let conn = Connection::new(uuid::Uuid::nil(), 1 << 16, 1 << 16);
let session = Session::new(Identity::Anonymous, [0; 16], [0; 16], false, None);
let tree = TreeConnect::new(1, Arc::clone(&added), Access::ReadWrite);
session
.trees
.write()
.await
.insert(1, Arc::new(RwLock::new(tree)));
let session = Arc::new(RwLock::new(session));
conn.sessions.write().await.insert(1, Arc::clone(&session));
assert!(conn.detach_trees_for_share(&removed).await.is_empty());
assert_eq!(session.read().await.trees.read().await.len(), 1);
conn.detach_trees_for_share(&added).await;
assert!(session.read().await.trees.read().await.is_empty());
}
}