use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use crate::proto::auth::ntlm::{Identity, NtlmServer};
use crate::proto::crypto::{Cipher, PreauthIntegrity, SessionCipher, SigningAlgo};
use crate::proto::messages::{Dialect, FileId};
use tokio::sync::RwLock;
use uuid::Uuid;
use crate::backend::{FileTimes, Handle};
use crate::builder::Access;
use crate::conn::outbound::Outbound;
use crate::conn::pending::{PendingOps, Stop};
use crate::files::{
Closing, DurableReg, DurableTable, FileRef, NotifyBudget, OpenSlot, WatchReg, close_opens,
end_opens, finish_close,
};
use crate::path::SmbPath;
use crate::rpc::pipe::{Pipe, PipeBudget};
use crate::server::ShareBindings;
pub type PendingAuth = Arc<Mutex<(NtlmServer, bool)>>;
pub const MAX_PENDING_AUTHS: usize = 16;
pub struct Connection {
pub server_guid: Uuid,
pub client_guid: tokio::sync::RwLock<Uuid>,
pub dialect: tokio::sync::RwLock<Option<Dialect>>,
pub signing_algo: tokio::sync::RwLock<SigningAlgo>,
pub cipher: tokio::sync::RwLock<Option<Cipher>>,
pub preauth: Mutex<PreauthIntegrity>,
pub max_read_size: tokio::sync::RwLock<u32>,
pub max_write_size: tokio::sync::RwLock<u32>,
pub sessions: RwLock<HashMap<u64, Arc<RwLock<Session>>>>,
pub pending_auths: RwLock<HashMap<u64, PendingAuth>>,
pub session_preauth: RwLock<HashMap<u64, PreauthIntegrity>>,
disconnect: AtomicBool,
closing: AtomicBool,
pub credits: Mutex<crate::conn::credits::CreditWindow>,
pub pending_auth_started: Mutex<HashMap<u64, std::time::Instant>>,
pub client_negotiate: Mutex<Option<crate::handlers::negotiate::ClientNegotiate>>,
pub logon_failures: AtomicU32,
pub open_count: Arc<std::sync::atomic::AtomicUsize>,
pub peer_addr: Option<std::net::SocketAddr>,
pub(crate) outbound: Arc<Outbound>,
pub(crate) pending: PendingOps,
pub(crate) pipe_budget: Arc<PipeBudget>,
pub(crate) notify_budget: Arc<NotifyBudget>,
pub(crate) aapl_read_dir_attr: AtomicBool,
}
impl Connection {
pub fn new(server_guid: Uuid, max_read_size: u32, max_write_size: u32) -> Self {
Self {
server_guid,
client_guid: tokio::sync::RwLock::new(Uuid::nil()),
dialect: tokio::sync::RwLock::new(None),
signing_algo: tokio::sync::RwLock::new(SigningAlgo::HmacSha256),
cipher: tokio::sync::RwLock::new(None),
preauth: Mutex::new(PreauthIntegrity::new()),
max_read_size: tokio::sync::RwLock::new(max_read_size),
max_write_size: tokio::sync::RwLock::new(max_write_size),
sessions: RwLock::new(HashMap::new()),
pending_auths: RwLock::new(HashMap::new()),
session_preauth: RwLock::new(HashMap::new()),
disconnect: AtomicBool::new(false),
closing: AtomicBool::new(false),
credits: Mutex::new(crate::conn::credits::CreditWindow::new()),
pending_auth_started: Mutex::new(HashMap::new()),
client_negotiate: Mutex::new(None),
logon_failures: AtomicU32::new(0),
open_count: Arc::default(),
peer_addr: None,
outbound: Arc::default(),
pending: PendingOps::default(),
pipe_budget: Arc::default(),
notify_budget: Arc::default(),
aapl_read_dir_attr: AtomicBool::new(false),
}
}
pub fn request_disconnect(&self) {
self.disconnect.store(true, Ordering::Release);
}
pub fn disconnect_requested(&self) -> bool {
self.disconnect.load(Ordering::Acquire)
}
pub(crate) fn mark_closing(&self) {
self.closing.store(true, Ordering::Release);
}
pub(crate) fn is_closing(&self) -> bool {
self.closing.load(Ordering::Acquire)
}
pub async fn close_session(&self, session_id: u64, keep: Option<&Arc<DurableTable>>) -> bool {
let keep = keep.map(|table| (table, table.sweeps()));
let removed = self.sessions.write().await.remove(&session_id);
let Some(sess_arc) = removed else {
return false;
};
self.pending
.stop_where(Stop::Retry, |op| op.session_id == session_id);
end_opens(detach_session(&sess_arc).await, keep).await;
true
}
pub async fn close_tree(&self, session_id: u64, tree_id: u32) -> bool {
let sess_arc = {
let sessions = self.sessions.read().await;
sessions.get(&session_id).cloned()
};
let Some(sess_arc) = sess_arc else {
return false;
};
let removed = {
let sess = sess_arc.read().await;
let mut trees = sess.trees.write().await;
trees.remove(&tree_id)
};
let Some(tree_arc) = removed else {
return false;
};
self.pending.stop_where(Stop::Retry, |op| {
op.session_id == session_id && op.tree_id == tree_id
});
close_opens(detach_tree(&tree_arc).await).await;
true
}
pub async fn detach_sessions_for_user(&self, user: &str) -> Vec<Arc<RwLock<Open>>> {
let removed = {
let mut sessions = self.sessions.write().await;
let mut ids = Vec::new();
for (session_id, sess_arc) in sessions.iter() {
let sess = sess_arc.read().await;
if matches!(&sess.identity, Identity::User { user: session_user, .. } if session_user == user)
{
ids.push(*session_id);
}
}
self.pending
.stop_where(Stop::Retry, |op| ids.contains(&op.session_id));
ids.into_iter()
.filter_map(|id| sessions.remove(&id))
.collect::<Vec<_>>()
};
let mut opens = Vec::new();
for sess_arc in removed {
opens.extend(detach_session(&sess_arc).await);
}
opens
}
pub async fn detach_trees_for_share(
&self,
share: &Arc<ShareBindings>,
) -> Vec<Arc<RwLock<Open>>> {
self.detach_matching_trees(|_, tree| Arc::ptr_eq(&tree.share, share))
.await
}
pub async fn detach_trees_for_user_share(
&self,
user: &str,
share: &Arc<ShareBindings>,
) -> Vec<Arc<RwLock<Open>>> {
self.detach_matching_trees(|sess, tree| {
matches!(&sess.identity, Identity::User { user: session_user, .. } if session_user == user)
&& Arc::ptr_eq(&tree.share, share)
})
.await
}
async fn detach_matching_trees(
&self,
matches_tree: impl Fn(&Session, &TreeConnect) -> bool,
) -> Vec<Arc<RwLock<Open>>> {
let sessions: Vec<_> = {
let sessions = self.sessions.read().await;
sessions
.iter()
.map(|(id, s)| (*id, Arc::clone(s)))
.collect()
};
let mut opens = Vec::new();
for (session_id, sess_arc) in sessions {
let removed = {
let sess = sess_arc.read().await;
let mut trees = sess.trees.write().await;
let mut ids = Vec::new();
for (tree_id, tree_arc) in trees.iter() {
let tree = tree_arc.read().await;
if matches_tree(&sess, &tree) {
ids.push(*tree_id);
}
}
self.pending.stop_where(Stop::Retry, |op| {
op.session_id == session_id && ids.contains(&op.tree_id)
});
ids.into_iter()
.filter_map(|id| trees.remove(&id))
.collect::<Vec<_>>()
};
for tree_arc in removed {
opens.extend(detach_tree(&tree_arc).await);
}
}
opens
}
pub async fn close_all(&self, keep: Option<&Arc<DurableTable>>) {
let keep = keep.map(|table| (table, table.sweeps()));
let sessions: Vec<_> = self.sessions.write().await.drain().collect();
let mut opens = Vec::new();
for (_, sess_arc) in sessions {
opens.extend(detach_session(&sess_arc).await);
}
end_opens(opens, keep).await;
}
}
async fn detach_session(sess_arc: &Arc<RwLock<Session>>) -> Vec<Arc<RwLock<Open>>> {
let trees: Vec<_> = {
let sess = sess_arc.read().await;
let mut trees = sess.trees.write().await;
trees.drain().collect()
};
let mut opens = Vec::new();
for (_, tree_arc) in trees {
opens.extend(detach_tree(&tree_arc).await);
}
opens
}
async fn detach_tree(tree_arc: &Arc<RwLock<TreeConnect>>) -> Vec<Arc<RwLock<Open>>> {
let mut tree = tree_arc.write().await;
tree.closed = true;
tree.pipes
.get_mut()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clear();
let opens: Vec<_> = tree.opens.write().await.drain().map(|(_, o)| o).collect();
opens
}
pub struct Session {
pub identity: Identity,
pub session_base_key: [u8; 16],
pub signing_key: [u8; 16],
pub signing_required: bool,
pub encrypt_data: bool,
pub cipher: Option<Arc<SessionCipher>>,
pub trees: RwLock<HashMap<u32, Arc<RwLock<TreeConnect>>>>,
pub preauth_snapshot: Option<[u8; 64]>,
next_tree_id: AtomicU32,
}
impl Session {
pub fn new(
identity: Identity,
session_base_key: [u8; 16],
signing_key: [u8; 16],
signing_required: bool,
preauth_snapshot: Option<[u8; 64]>,
) -> Self {
Self {
identity,
session_base_key,
signing_key,
signing_required,
encrypt_data: false,
cipher: None,
trees: RwLock::new(HashMap::new()),
preauth_snapshot,
next_tree_id: AtomicU32::new(1),
}
}
pub fn alloc_tree_id(&self) -> u32 {
self.next_tree_id.fetch_add(1, Ordering::Relaxed)
}
pub fn is_anonymous(&self) -> bool {
matches!(self.identity, Identity::Anonymous)
}
}
pub struct TreeConnect {
pub id: u32,
pub share: Arc<ShareBindings>,
pub granted_access: Access,
pub opens: RwLock<HashMap<FileId, Arc<RwLock<Open>>>>,
pub(crate) pipes: Mutex<HashMap<FileId, Arc<Pipe>>>,
pub closed: bool,
}
static NEXT_FILE_ID: AtomicU64 = AtomicU64::new(1);
impl TreeConnect {
pub fn new(id: u32, share: Arc<ShareBindings>, granted_access: Access) -> Self {
Self {
id,
share,
granted_access,
opens: RwLock::new(HashMap::new()),
pipes: Mutex::default(),
closed: false,
}
}
pub fn alloc_file_id(&self) -> FileId {
let v = self.alloc_volatile();
FileId::new(v, v)
}
pub fn alloc_volatile(&self) -> u64 {
NEXT_FILE_ID.fetch_add(1, Ordering::Relaxed)
}
}
pub struct Open {
pub file_id: FileId,
pub handle: Option<Box<dyn Handle>>,
pub granted_access: u32,
pub is_directory: bool,
pub(crate) on_stream: bool,
pub delete_on_close: bool,
pub search_state: Option<DirCursor>,
pub fixed_times: FileTimes,
pub create_options: u32,
pub(crate) file: Option<FileRef>,
pub(crate) slot: Option<OpenSlot>,
pub(crate) durable: Option<DurableReg>,
pub(crate) watch: Option<WatchReg>,
pub(crate) wrote: AtomicBool,
pub(crate) resized: AtomicBool,
pub(crate) moved_data: bool,
pub(crate) created: bool,
pub(crate) marked_deleted: AtomicBool,
pub(crate) ea_cursor: std::sync::Mutex<EaCursor>,
pub(crate) eas_changed: AtomicBool,
}
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct EaCursor {
pub next: usize,
pub changes: Option<u64>,
}
impl Open {
pub fn path(&self) -> Option<SmbPath> {
self.file.as_ref().map(FileRef::path)
}
pub fn delete_pending(&self) -> bool {
self.file
.as_ref()
.is_some_and(FileRef::stream_delete_pending)
}
}
impl Drop for Open {
fn drop(&mut self) {
let handle = self.handle.take();
if handle.is_none() && self.file.is_none() {
return;
}
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
return;
};
let closing = Closing::announce(self, false);
let file = self.file.take();
runtime.spawn(finish_close(
handle,
file,
self.delete_on_close,
self.is_directory,
closing,
self.eas_changed.load(Ordering::Acquire),
));
}
}
pub struct DirCursor {
pub entries: Vec<crate::backend::DirEntry>,
pub next: usize,
pub pattern: Option<String>,
pub peek_streams: bool,
}