1use std::collections::HashMap;
5use std::io;
6use std::net::SocketAddr;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, Weak};
9
10use crate::proto::auth::ntlm::{Identity, UserCreds};
11use thiserror::Error;
12use tokio::net::TcpListener;
13use tokio::sync::{Notify, RwLock, Semaphore};
14use tokio::task::JoinSet;
15use tracing::{Instrument, debug, error, info, info_span, warn};
16use uuid::Uuid;
17
18use crate::backend::ShareBackend;
19use crate::builder::{
20 Access, Share, ShareNameError, SmbServerBuilder, check_share_name, valid_remark,
21};
22use crate::conn::connection_loop;
23use crate::conn::limits::Limits;
24use crate::conn::listener::{AcceptBackoff, configure_socket};
25use crate::conn::state::Connection;
26use crate::files::{DurableTable, close_opens};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ShareMode {
34 Public,
35 PublicReadOnly,
36 AuthenticatedOnly,
38}
39
40#[derive(Clone)]
41pub struct ShareAcl {
42 pub mode: ShareMode,
43 pub users: HashMap<String, Access>,
44}
45
46impl ShareAcl {
47 pub(crate) fn authorize(&self, identity: &Identity) -> Option<Access> {
50 match self.mode {
51 ShareMode::Public => Some(Access::ReadWrite),
52 ShareMode::PublicReadOnly => Some(Access::Read),
53 ShareMode::AuthenticatedOnly => match identity {
54 Identity::Anonymous => None,
55 Identity::User { user, .. } => self.users.get(user).copied(),
56 },
57 }
58 }
59}
60
61#[derive(Debug, Clone)]
63pub(crate) struct Caller {
64 pub identity: Identity,
65 pub can_encrypt: bool,
67}
68
69impl Caller {
70 pub(crate) fn of(session: &crate::conn::state::Session) -> Self {
71 Self {
72 identity: session.identity.clone(),
73 can_encrypt: session.cipher.is_some(),
74 }
75 }
76}
77
78pub struct ShareBindings {
80 pub name: String,
81 pub backend: Arc<dyn ShareBackend>,
82 pub acl: RwLock<ShareAcl>,
83 pub is_ipc: bool,
86 pub encrypt_data: bool,
88 pub(crate) leases: bool,
90 pub(crate) durable_handles: bool,
92 pub(crate) listed: bool,
94 pub(crate) remark: String,
96 pub(crate) files: crate::files::FileTable,
98 pub(crate) change_notify: bool,
100 pub(crate) watches: crate::files::WatchTable,
102}
103
104impl ShareBindings {
105 pub(crate) fn new(
106 name: String,
107 backend: Arc<dyn ShareBackend>,
108 mode: ShareMode,
109 users: HashMap<String, Access>,
110 is_ipc: bool,
111 leases: bool,
112 durable_handles: bool,
113 ) -> Arc<Self> {
114 let watches = crate::files::WatchTable::new(backend.capabilities().case_sensitive);
115 Arc::new(Self {
116 name,
117 backend,
118 acl: RwLock::new(ShareAcl { mode, users }),
119 is_ipc,
120 encrypt_data: false,
121 leases,
122 durable_handles,
123 listed: true,
124 remark: String::new(),
125 files: crate::files::FileTable::default(),
126 change_notify: !is_ipc,
127 watches,
128 })
129 }
130
131 pub(crate) fn from_share(share: Share) -> Arc<Self> {
132 let watches = crate::files::WatchTable::new(share.backend.capabilities().case_sensitive);
133 Arc::new(Self {
134 name: share.name,
135 backend: share.backend,
136 acl: RwLock::new(ShareAcl {
137 mode: share.mode,
138 users: share.users,
139 }),
140 is_ipc: false,
141 encrypt_data: share.encrypt_data,
142 leases: share.leases,
143 durable_handles: share.durable_handles,
144 listed: share.listed,
145 remark: share.remark,
146 files: crate::files::FileTable::default(),
147 change_notify: share.change_notify,
148 watches,
149 })
150 }
151
152 pub fn ipc() -> Arc<Self> {
154 Self::new(
155 "IPC$".to_string(),
156 Arc::new(crate::backend::NotSupportedBackend),
157 ShareMode::PublicReadOnly,
158 HashMap::new(),
159 true,
160 false,
161 false,
162 )
163 }
164}
165
166#[derive(Debug, Clone)]
171pub struct ServerConfig {
172 pub listen_addr: SocketAddr,
173 pub netbios_name: String,
174 pub max_read_size: u32,
175 pub max_write_size: u32,
176 pub server_guid: Uuid,
177 pub limits: Limits,
178 pub share_listing: bool,
180}
181
182pub struct ServerUsers {
183 pub table: RwLock<HashMap<String, UserCreds>>,
185}
186
187pub struct ServerShares {
188 by_name: RwLock<HashMap<String, (u64, Arc<ShareBindings>)>>,
191 next_seq: AtomicU64,
192}
193
194impl ServerShares {
195 pub fn new(shares: Vec<Arc<ShareBindings>>) -> Self {
196 let mut by_name = HashMap::with_capacity(shares.len());
197 for (seq, share) in (0..).zip(shares) {
198 by_name.insert(share.name.to_ascii_lowercase(), (seq, share));
199 }
200 Self {
201 next_seq: AtomicU64::new(by_name.len() as u64),
202 by_name: RwLock::new(by_name),
203 }
204 }
205
206 pub async fn find(&self, name: &str) -> Option<Arc<ShareBindings>> {
207 self.by_name
208 .read()
209 .await
210 .get(&name.to_ascii_lowercase())
211 .map(|(_, share)| Arc::clone(share))
212 }
213
214 pub async fn insert(&self, share: Arc<ShareBindings>) -> Result<(), ConfigError> {
216 let key = share.name.to_ascii_lowercase();
217 let mut by_name = self.by_name.write().await;
218 if by_name.contains_key(&key) {
219 return Err(ConfigError::DuplicateShare(share.name.clone()));
220 }
221 let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
222 by_name.insert(key, (seq, share));
223 Ok(())
224 }
225
226 pub async fn remove(&self, name: &str) -> Option<Arc<ShareBindings>> {
227 self.by_name
228 .write()
229 .await
230 .remove(&name.to_ascii_lowercase())
231 .map(|(_, share)| share)
232 }
233
234 pub async fn all(&self) -> Vec<Arc<ShareBindings>> {
235 self.by_name
236 .read()
237 .await
238 .values()
239 .map(|(_, share)| Arc::clone(share))
240 .collect()
241 }
242
243 #[cfg(test)]
245 pub(crate) async fn hold(
246 &self,
247 ) -> tokio::sync::RwLockWriteGuard<'_, HashMap<String, (u64, Arc<ShareBindings>)>> {
248 self.by_name.write().await
249 }
250
251 pub(crate) async fn all_in_order(&self) -> Vec<Arc<ShareBindings>> {
253 let mut shares: Vec<_> = self.by_name.read().await.values().cloned().collect();
254 shares.sort_unstable_by_key(|(seq, _)| *seq);
255 shares.into_iter().map(|(_, share)| share).collect()
256 }
257}
258
259pub struct ActiveConnections {
260 next_id: AtomicU64,
261 conns: RwLock<HashMap<u64, Weak<Connection>>>,
262}
263
264impl ActiveConnections {
265 pub fn new() -> Self {
266 Self {
267 next_id: AtomicU64::new(1),
268 conns: RwLock::new(HashMap::new()),
269 }
270 }
271
272 pub async fn register(&self, conn: &Arc<Connection>) -> u64 {
273 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
274 self.conns.write().await.insert(id, Arc::downgrade(conn));
275 id
276 }
277
278 pub async fn unregister(&self, id: u64) {
279 self.conns.write().await.remove(&id);
280 }
281
282 pub async fn live(&self) -> Vec<Arc<Connection>> {
283 let mut live = Vec::new();
284 let mut conns = self.conns.write().await;
285 conns.retain(|_, weak| {
286 if let Some(conn) = weak.upgrade() {
287 live.push(conn);
288 true
289 } else {
290 false
291 }
292 });
293 live
294 }
295}
296
297impl Default for ActiveConnections {
298 fn default() -> Self {
299 Self::new()
300 }
301}
302
303pub struct ServerState {
305 pub config: ServerConfig,
306 pub users: ServerUsers,
307 pub shares: ServerShares,
308 pub active_connections: ActiveConnections,
309 pub shutdown: Arc<Notify>,
312 pub shutting_down: Arc<AtomicBool>,
313 pub auth: crate::auth_policy::AuthPolicy,
315
316 pub max_opens_per_connection: std::sync::atomic::AtomicUsize,
319 pub max_locks_per_open: std::sync::atomic::AtomicUsize,
322 pub(crate) leases: Arc<crate::files::LeaseTable>,
324 pub(crate) durable: Arc<DurableTable>,
326}
327
328impl ServerState {
329 pub fn new(config: ServerConfig, users: ServerUsers, shares: Vec<Arc<ShareBindings>>) -> Self {
330 let durable = Arc::new(DurableTable::new(
331 config.limits.durable_handle_timeout,
332 config.limits.max_disconnected_opens,
333 ));
334 Self {
335 config,
336 users,
337 shares: ServerShares::new(shares),
338 active_connections: ActiveConnections::new(),
339 shutdown: Arc::new(Notify::new()),
340 shutting_down: Arc::new(AtomicBool::new(false)),
341 auth: crate::auth_policy::AuthPolicy::default(),
342 max_opens_per_connection: std::sync::atomic::AtomicUsize::new(
343 crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
344 ),
345 max_locks_per_open: std::sync::atomic::AtomicUsize::new(
346 crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
347 ),
348 leases: Arc::default(),
349 durable,
350 }
351 }
352
353 pub(crate) fn admits(
358 &self,
359 share: &ShareBindings,
360 acl: &ShareAcl,
361 caller: &Caller,
362 ) -> Option<Access> {
363 let settings = &self.auth.settings;
364 if (settings.encrypt_data || share.encrypt_data)
365 && settings.reject_unencrypted_access
366 && !caller.can_encrypt
367 {
368 return None;
369 }
370 acl.authorize(&caller.identity)
371 }
372
373 pub async fn find_share(&self, name: &str) -> Option<Arc<ShareBindings>> {
375 self.shares.find(name).await
376 }
377
378 pub async fn lookup_user(&self, name: &str) -> Option<UserCreds> {
380 self.users.table.read().await.get(name).cloned()
381 }
382
383 pub async fn anonymous_allowed(&self) -> bool {
385 for share in self.shares.all().await {
386 let acl = share.acl.read().await;
387 if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
388 return true;
389 }
390 }
391 false
392 }
393}
394
395#[derive(Debug, Error, PartialEq, Eq)]
396pub enum ConfigError {
397 #[error("user `{0}` does not exist")]
398 UnknownUser(String),
399 #[error("share `{0}` does not exist")]
400 UnknownShare(String),
401 #[error("duplicate share `{0}`")]
402 DuplicateShare(String),
403 #[error("share `{0}` mixes public mode with explicit users")]
404 PublicMixedWithUsers(String),
405 #[error("user name `{0}` is reserved")]
406 ReservedUserName(String),
407 #[error("user name must be non-empty")]
408 EmptyUserName,
409 #[error("share name `{0}` is reserved")]
410 ReservedShareName(String),
411 #[error("share name `{0}` must be non-empty and contain no `\\`, `/` or NUL")]
412 InvalidShareName(String),
413 #[error("remark of share `{0}` must hold no NUL and at most 1024 UTF-16 code units")]
414 InvalidShareRemark(String),
415}
416
417#[derive(Clone)]
418pub struct ConfigHandle {
419 state: Arc<ServerState>,
420}
421
422impl ConfigHandle {
423 pub async fn add_user(
427 &self,
428 name: impl Into<String>,
429 password: impl AsRef<str>,
430 ) -> Result<(), ConfigError> {
431 let name = name.into();
432 validate_user_name(&name)?;
433 let creds = UserCreds::from_password(password.as_ref());
434 let replaced = self
435 .state
436 .users
437 .table
438 .write()
439 .await
440 .insert(name.clone(), creds.clone());
441 if replaced.is_some_and(|old| old.nt_hash != creds.nt_hash) {
442 self.close_user_sessions(&name).await;
443 }
444 Ok(())
445 }
446
447 pub async fn remove_user(&self, name: &str) -> Result<(), ConfigError> {
448 validate_user_name(name)?;
449 let removed = self.state.users.table.write().await.remove(name);
450 if removed.is_none() {
451 return Err(ConfigError::UnknownUser(name.to_string()));
452 }
453
454 for share in self.state.shares.all().await {
455 share.acl.write().await.users.remove(name);
456 }
457
458 self.close_user_sessions(name).await;
459 Ok(())
460 }
461
462 pub async fn add_share(&self, share: Share) -> Result<(), ConfigError> {
463 validate_share_name(&share.name)?;
464 let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
465 if is_public && !share.users.is_empty() {
466 return Err(ConfigError::PublicMixedWithUsers(share.name));
467 }
468 if !valid_remark(&share.remark) {
469 return Err(ConfigError::InvalidShareRemark(share.name));
470 }
471 let users = self.state.users.table.read().await;
472 for user in share.users.keys() {
473 if !users.contains_key(user) {
474 return Err(ConfigError::UnknownUser(user.clone()));
475 }
476 }
477
478 let binding = ShareBindings::from_share(share);
479 self.state.shares.insert(binding).await
480 }
481
482 pub async fn remove_share(&self, name: &str) -> Result<(), ConfigError> {
483 validate_share_name(name)?;
484 let removed = self
485 .state
486 .shares
487 .remove(name)
488 .await
489 .ok_or_else(|| ConfigError::UnknownShare(name.to_string()))?;
490
491 self.close_share_trees(&removed, None).await;
492 Ok(())
493 }
494
495 pub async fn grant_share_user(
500 &self,
501 share_name: &str,
502 user: &str,
503 access: Access,
504 ) -> Result<(), ConfigError> {
505 validate_user_name(user)?;
506 validate_share_name(share_name)?;
507 let users = self.state.users.table.read().await;
508 if !users.contains_key(user) {
509 return Err(ConfigError::UnknownUser(user.to_string()));
510 }
511 drop(users);
512 let share = self
513 .state
514 .find_share(share_name)
515 .await
516 .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
517 let mut acl = share.acl.write().await;
518 if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
519 return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
520 }
521 let previous = acl.users.insert(user.to_string(), access);
522 drop(acl);
523
524 if previous.is_some_and(|old| old.allows_write() && !access.allows_write()) {
525 self.close_share_trees(&share, Some(user)).await;
526 }
527 Ok(())
528 }
529
530 pub async fn revoke_share_user(&self, share_name: &str, user: &str) -> Result<(), ConfigError> {
531 validate_user_name(user)?;
532 validate_share_name(share_name)?;
533 let share = self
534 .state
535 .find_share(share_name)
536 .await
537 .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
538 share.acl.write().await.users.remove(user);
539
540 self.close_share_trees(&share, Some(user)).await;
541 Ok(())
542 }
543
544 pub async fn set_share_mode(
545 &self,
546 share_name: &str,
547 mode: ShareMode,
548 ) -> Result<(), ConfigError> {
549 validate_share_name(share_name)?;
550 let share = self
551 .state
552 .find_share(share_name)
553 .await
554 .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
555 let mut acl = share.acl.write().await;
556 if matches!(mode, ShareMode::Public | ShareMode::PublicReadOnly) && !acl.users.is_empty() {
557 return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
558 }
559 if acl.mode == mode {
560 return Ok(());
561 }
562 acl.mode = mode;
563 drop(acl);
564
565 self.close_share_trees(&share, None).await;
566 Ok(())
567 }
568
569 pub fn set_max_opens_per_connection(&self, limit: usize) {
574 self.state
575 .max_opens_per_connection
576 .store(limit, Ordering::Relaxed);
577 }
578
579 async fn close_user_sessions(&self, user: &str) {
584 let mut opens = Vec::new();
585 for conn in self.state.active_connections.live().await {
586 opens.extend(conn.detach_sessions_for_user(user).await);
587 }
588 opens.extend(self.state.durable.take_for(None, Some(user)));
589 close_opens(opens).await;
590 }
591
592 async fn close_share_trees(&self, share: &Arc<ShareBindings>, user: Option<&str>) {
596 let mut opens = Vec::new();
597 for conn in self.state.active_connections.live().await {
598 opens.extend(match user {
599 Some(user) => conn.detach_trees_for_user_share(user, share).await,
600 None => conn.detach_trees_for_share(share).await,
601 });
602 }
603 opens.extend(self.state.durable.take_for(Some(share), user));
604 close_opens(opens).await;
605 }
606}
607
608fn validate_user_name(name: &str) -> Result<(), ConfigError> {
609 if name.is_empty() {
610 return Err(ConfigError::EmptyUserName);
611 }
612 if name.eq_ignore_ascii_case("anonymous") {
613 return Err(ConfigError::ReservedUserName(name.to_string()));
614 }
615 Ok(())
616}
617
618fn validate_share_name(name: &str) -> Result<(), ConfigError> {
619 match check_share_name(name) {
620 Ok(()) => Ok(()),
621 Err(ShareNameError::Reserved) => Err(ConfigError::ReservedShareName(name.to_string())),
622 Err(ShareNameError::Invalid) => Err(ConfigError::InvalidShareName(name.to_string())),
623 }
624}
625
626pub struct SmbServer {
634 state: Arc<ServerState>,
635 bound: tokio::sync::Mutex<Option<TcpListener>>,
638 local_addr: tokio::sync::Mutex<Option<SocketAddr>>,
640}
641
642impl SmbServer {
643 pub fn builder() -> SmbServerBuilder {
644 SmbServerBuilder::default()
645 }
646
647 pub(crate) fn from_state(state: ServerState) -> Self {
648 Self {
649 state: Arc::new(state),
650 bound: tokio::sync::Mutex::new(None),
651 local_addr: tokio::sync::Mutex::new(None),
652 }
653 }
654
655 pub fn config_handle(&self) -> ConfigHandle {
656 ConfigHandle {
657 state: self.state.clone(),
658 }
659 }
660
661 pub async fn bind(&self) -> io::Result<SocketAddr> {
665 let mut bound = self.bound.lock().await;
666 if let Some(l) = bound.as_ref() {
667 return l.local_addr();
668 }
669 let listener = TcpListener::bind(self.state.config.listen_addr).await?;
670 let addr = listener.local_addr()?;
671 *bound = Some(listener);
672 *self.local_addr.lock().await = Some(addr);
673 Ok(addr)
674 }
675
676 pub async fn local_addr(&self) -> Option<SocketAddr> {
679 *self.local_addr.lock().await
680 }
681
682 pub fn configured_addr(&self) -> SocketAddr {
685 self.state.config.listen_addr
686 }
687
688 pub fn shutdown(&self) {
692 self.state.shutting_down.store(true, Ordering::Release);
693 self.state.shutdown.notify_waiters();
694 }
695
696 pub fn shutdown_handle(&self) -> ShutdownHandle {
699 ShutdownHandle {
700 shutdown: self.state.shutdown.clone(),
701 shutting_down: self.state.shutting_down.clone(),
702 }
703 }
704
705 pub async fn serve(self) -> io::Result<()> {
710 if self.bound.lock().await.is_none() {
711 self.bind().await?;
712 }
713 let listener = self
714 .bound
715 .lock()
716 .await
717 .take()
718 .expect("listener bound above");
719 let local = listener.local_addr().ok();
720 let span = info_span!("smb_server", listen = ?local);
721 async move {
722 info!("server starting");
723 let state = self.state.clone();
724 let shutdown = state.shutdown.clone();
725 let shutting_down = state.shutting_down.clone();
726 let mut backoff = AcceptBackoff::new();
727 let mut connections = JoinSet::new();
728 let limits = &state.config.limits;
729 let slots = Arc::new(Semaphore::new(
730 limits.max_connections.min(Semaphore::MAX_PERMITS),
731 ));
732 let mut at_capacity = false;
733
734 loop {
735 let stopped = shutdown.notified();
736 tokio::pin!(stopped);
737 stopped.as_mut().enable();
738 if shutting_down.load(Ordering::Acquire) {
739 info!("shutdown requested; stopping accept loop");
740 break;
741 }
742 let retry_after = tokio::select! {
743 biased;
744 _ = &mut stopped => {
745 info!("shutdown requested; stopping accept loop");
746 break;
747 }
748 Some(_) = connections.join_next(), if !connections.is_empty() => None,
749 accept = listener.accept() => {
750 match accept {
751 Ok((stream, peer)) => {
752 backoff.succeeded();
753 if shutting_down.load(Ordering::Acquire) {
754 drop(stream);
755 break;
756 }
757 let Ok(slot) = slots.clone().try_acquire_owned() else {
758 if !at_capacity {
759 warn!(
760 max = limits.max_connections,
761 "connection limit reached; closing new connections"
762 );
763 at_capacity = true;
764 }
765 debug!(%peer, "connection refused: limit reached");
766 drop(stream);
767 continue;
768 };
769 if at_capacity {
770 info!("below the connection limit again");
771 at_capacity = false;
772 }
773 configure_socket(&stream, limits.tcp_keepalive);
774 let server_state = state.clone();
775 let span = info_span!("conn", peer = %peer);
776 connections.spawn(async move {
777 let _slot = slot;
778 if let Err(e) = connection_loop(stream, peer, server_state).await {
779 error!(error = %e, "connection loop exited with error");
780 }
781 }.instrument(span));
782 None
783 }
784 Err(e) => {
785 if shutting_down.load(Ordering::Acquire) {
786 break;
787 }
788 Some(backoff.failed(&e))
789 }
790 }
791 }
792 };
793 if let Some(delay) = retry_after {
794 tokio::select! {
795 biased;
796 _ = &mut stopped => {
797 info!("shutdown requested; stopping accept loop");
798 break;
799 }
800 _ = tokio::time::sleep(delay) => {}
801 }
802 }
803 }
804 drop(listener);
805 if !connections.is_empty() {
806 info!(open = connections.len(), "waiting for connections to close");
807 }
808 while connections.join_next().await.is_some() {}
809 close_opens(state.durable.take_for(None, None)).await;
810 state.durable.closed().await;
811 info!("server stopped");
812 Ok::<(), io::Error>(())
813 }
814 .instrument(span)
815 .await
816 }
817
818 #[cfg(any(test, fuzzing))]
819 pub(crate) fn state(&self) -> Arc<ServerState> {
820 self.state.clone()
821 }
822}
823
824#[derive(Clone)]
827pub struct ShutdownHandle {
828 shutdown: Arc<Notify>,
829 shutting_down: Arc<AtomicBool>,
830}
831
832impl ShutdownHandle {
833 pub fn shutdown(&self) {
835 self.shutting_down.store(true, Ordering::Release);
836 self.shutdown.notify_waiters();
837 }
838}