Skip to main content

smb_server/
server.rs

1//! Top-level `SmbServer` lifecycle: builder integration, accept loop,
2//! graceful shutdown.
3
4use 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};
27use crate::proto::messages::copychunk::RESUME_TAG_LEN;
28use crate::utils::fill_random;
29
30// ---------------------------------------------------------------------------
31// ShareMode / ShareBindings
32// ---------------------------------------------------------------------------
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ShareMode {
36    Public,
37    PublicReadOnly,
38    /// Default: closed share. Only users in the explicit `users` map allowed.
39    AuthenticatedOnly,
40}
41
42#[derive(Clone)]
43pub struct ShareAcl {
44    pub mode: ShareMode,
45    pub users: HashMap<String, Access>,
46}
47
48impl ShareAcl {
49    /// The access `identity` gets to the share, or `None` when it may not
50    /// connect: public shares admit everyone, other shares their users.
51    pub(crate) fn authorize(&self, identity: &Identity) -> Option<Access> {
52        match self.mode {
53            ShareMode::Public => Some(Access::ReadWrite),
54            ShareMode::PublicReadOnly => Some(Access::Read),
55            ShareMode::AuthenticatedOnly => match identity {
56                Identity::Anonymous => None,
57                Identity::User { user, .. } => self.users.get(user).copied(),
58            },
59        }
60    }
61}
62
63/// A session as share admission sees it.
64#[derive(Debug, Clone)]
65pub(crate) struct Caller {
66    pub identity: Identity,
67    /// The session has encryption keys.
68    pub can_encrypt: bool,
69}
70
71impl Caller {
72    pub(crate) fn of(session: &crate::conn::state::Session) -> Self {
73        Self {
74            identity: session.identity.clone(),
75            can_encrypt: session.cipher.is_some(),
76        }
77    }
78}
79
80/// Compiled binding for a single share: the per-server-state form of `Share`.
81pub struct ShareBindings {
82    pub name: String,
83    pub backend: Arc<dyn ShareBackend>,
84    pub acl: RwLock<ShareAcl>,
85    /// `IPC$` synthetic share. Accepted at TREE_CONNECT; its opens are
86    /// named pipes.
87    pub is_ipc: bool,
88    /// Share.EncryptData: traffic to the share is encrypted.
89    pub encrypt_data: bool,
90    /// Leases are granted on the share's files.
91    pub(crate) leases: bool,
92    /// Opens asking for a durable handle get one.
93    pub(crate) durable_handles: bool,
94    /// The share appears when clients list the server's shares.
95    pub(crate) listed: bool,
96    /// The comment shown next to the share in share lists.
97    pub(crate) remark: String,
98    /// Every file on the share that has an open, on any connection.
99    pub(crate) files: crate::files::FileTable,
100    /// CHANGE_NOTIFY is answered on the share.
101    pub(crate) change_notify: bool,
102    /// Named streams are served: the share allows them and the backend
103    /// stores them.
104    pub(crate) named_streams: bool,
105    /// Extended attributes are served: the share allows them and the
106    /// backend stores them.
107    pub(crate) extended_attributes: bool,
108    /// Clients may ask the server to copy file data on the share.
109    pub(crate) server_side_copy: bool,
110    /// Clients may ask the server to clone ranges of files on the share:
111    /// server-side copy is on and the backend clones ranges.
112    pub(crate) block_cloning: bool,
113    /// The directories clients watch for changes, on any connection.
114    pub(crate) watches: crate::files::WatchTable,
115}
116
117impl ShareBindings {
118    pub(crate) fn new(
119        name: String,
120        backend: Arc<dyn ShareBackend>,
121        mode: ShareMode,
122        users: HashMap<String, Access>,
123        is_ipc: bool,
124        leases: bool,
125        durable_handles: bool,
126    ) -> Arc<Self> {
127        let capabilities = backend.capabilities();
128        let watches = crate::files::WatchTable::new(capabilities.case_sensitive);
129        Arc::new(Self {
130            name,
131            backend,
132            acl: RwLock::new(ShareAcl { mode, users }),
133            is_ipc,
134            encrypt_data: false,
135            leases,
136            durable_handles,
137            listed: true,
138            remark: String::new(),
139            files: crate::files::FileTable::default(),
140            change_notify: !is_ipc,
141            named_streams: !is_ipc && capabilities.named_streams,
142            extended_attributes: !is_ipc && capabilities.extended_attributes,
143            server_side_copy: !is_ipc,
144            block_cloning: !is_ipc && capabilities.block_cloning,
145            watches,
146        })
147    }
148
149    pub(crate) fn from_share(share: Share) -> Arc<Self> {
150        let capabilities = share.backend.capabilities();
151        let watches = crate::files::WatchTable::new(capabilities.case_sensitive);
152        Arc::new(Self {
153            name: share.name,
154            backend: share.backend,
155            acl: RwLock::new(ShareAcl {
156                mode: share.mode,
157                users: share.users,
158            }),
159            is_ipc: false,
160            encrypt_data: share.encrypt_data,
161            leases: share.leases,
162            durable_handles: share.durable_handles,
163            listed: share.listed,
164            remark: share.remark,
165            files: crate::files::FileTable::default(),
166            change_notify: share.change_notify,
167            named_streams: share.named_streams && capabilities.named_streams,
168            extended_attributes: share.extended_attributes && capabilities.extended_attributes,
169            server_side_copy: share.server_side_copy,
170            block_cloning: share.server_side_copy && capabilities.block_cloning,
171            watches,
172        })
173    }
174
175    /// Synthetic IPC$ share, whose opens are named pipes.
176    pub fn ipc() -> Arc<Self> {
177        Self::new(
178            "IPC$".to_string(),
179            Arc::new(crate::backend::NotSupportedBackend),
180            ShareMode::PublicReadOnly,
181            HashMap::new(),
182            true,
183            false,
184            false,
185        )
186    }
187}
188
189// ---------------------------------------------------------------------------
190// ServerConfig / ServerUsers / ServerState
191// ---------------------------------------------------------------------------
192
193#[derive(Debug, Clone)]
194pub struct ServerConfig {
195    pub listen_addr: SocketAddr,
196    pub netbios_name: String,
197    pub max_read_size: u32,
198    pub max_write_size: u32,
199    pub server_guid: Uuid,
200    pub limits: Limits,
201    /// IPC$ serves the srvsvc pipe, so clients can list the shares.
202    pub share_listing: bool,
203    /// The model string of `AAPL` replies; `None` when the server ignores
204    /// the `AAPL` create context.
205    pub(crate) apple_model: Option<String>,
206    /// `AAPL` replies offer OSX_COPYFILE.
207    pub(crate) apple_copyfile: bool,
208    /// The server is announced on the local network while it serves.
209    #[cfg(feature = "discovery")]
210    pub(crate) discovery: Option<crate::discovery::Settings>,
211}
212
213pub struct ServerUsers {
214    /// Username -> precomputed NT hash record.
215    pub table: RwLock<HashMap<String, UserCreds>>,
216}
217
218pub struct ServerShares {
219    /// Each share by its lowercased name, with its place in the order the
220    /// shares were added.
221    by_name: RwLock<HashMap<String, (u64, Arc<ShareBindings>)>>,
222    next_seq: AtomicU64,
223}
224
225impl ServerShares {
226    pub fn new(shares: Vec<Arc<ShareBindings>>) -> Self {
227        let mut by_name = HashMap::with_capacity(shares.len());
228        for (seq, share) in (0..).zip(shares) {
229            by_name.insert(share.name.to_ascii_lowercase(), (seq, share));
230        }
231        Self {
232            next_seq: AtomicU64::new(by_name.len() as u64),
233            by_name: RwLock::new(by_name),
234        }
235    }
236
237    pub async fn find(&self, name: &str) -> Option<Arc<ShareBindings>> {
238        self.by_name
239            .read()
240            .await
241            .get(&name.to_ascii_lowercase())
242            .map(|(_, share)| Arc::clone(share))
243    }
244
245    /// Adds `share` after every share there is.
246    pub async fn insert(&self, share: Arc<ShareBindings>) -> Result<(), ConfigError> {
247        let key = share.name.to_ascii_lowercase();
248        let mut by_name = self.by_name.write().await;
249        if by_name.contains_key(&key) {
250            return Err(ConfigError::DuplicateShare(share.name.clone()));
251        }
252        let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
253        by_name.insert(key, (seq, share));
254        Ok(())
255    }
256
257    pub async fn remove(&self, name: &str) -> Option<Arc<ShareBindings>> {
258        self.by_name
259            .write()
260            .await
261            .remove(&name.to_ascii_lowercase())
262            .map(|(_, share)| share)
263    }
264
265    pub async fn all(&self) -> Vec<Arc<ShareBindings>> {
266        self.by_name
267            .read()
268            .await
269            .values()
270            .map(|(_, share)| Arc::clone(share))
271            .collect()
272    }
273
274    /// Holds the share table for writing, so lookups wait.
275    #[cfg(test)]
276    pub(crate) async fn hold(
277        &self,
278    ) -> tokio::sync::RwLockWriteGuard<'_, HashMap<String, (u64, Arc<ShareBindings>)>> {
279        self.by_name.write().await
280    }
281
282    /// Every share, in the order the shares were added (MS-SRVS 3.1.4.8).
283    pub(crate) async fn all_in_order(&self) -> Vec<Arc<ShareBindings>> {
284        let mut shares: Vec<_> = self.by_name.read().await.values().cloned().collect();
285        shares.sort_unstable_by_key(|(seq, _)| *seq);
286        shares.into_iter().map(|(_, share)| share).collect()
287    }
288}
289
290pub struct ActiveConnections {
291    next_id: AtomicU64,
292    conns: RwLock<HashMap<u64, Weak<Connection>>>,
293}
294
295impl ActiveConnections {
296    pub fn new() -> Self {
297        Self {
298            next_id: AtomicU64::new(1),
299            conns: RwLock::new(HashMap::new()),
300        }
301    }
302
303    pub async fn register(&self, conn: &Arc<Connection>) -> u64 {
304        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
305        self.conns.write().await.insert(id, Arc::downgrade(conn));
306        id
307    }
308
309    pub async fn unregister(&self, id: u64) {
310        self.conns.write().await.remove(&id);
311    }
312
313    pub async fn live(&self) -> Vec<Arc<Connection>> {
314        let mut live = Vec::new();
315        let mut conns = self.conns.write().await;
316        conns.retain(|_, weak| {
317            if let Some(conn) = weak.upgrade() {
318                live.push(conn);
319                true
320            } else {
321                false
322            }
323        });
324        live
325    }
326}
327
328impl Default for ActiveConnections {
329    fn default() -> Self {
330        Self::new()
331    }
332}
333
334/// Server state shared across connections.
335pub struct ServerState {
336    pub config: ServerConfig,
337    pub users: ServerUsers,
338    pub shares: ServerShares,
339    pub active_connections: ActiveConnections,
340    /// Notified by `shutdown()`. The accept loop stops; each connection
341    /// closes once it has answered the frame it is receiving, if any.
342    pub shutdown: Arc<Notify>,
343    pub shutting_down: Arc<AtomicBool>,
344    /// Signing policy, session and tree limits, and the logon throttle.
345    pub auth: crate::auth_policy::AuthPolicy,
346
347    /// Opens one connection may hold at once. CREATE past it fails with
348    /// STATUS_INSUFFICIENT_RESOURCES.
349    pub max_opens_per_connection: std::sync::atomic::AtomicUsize,
350    /// Byte-range locks one open may hold at once. LOCK past it fails with
351    /// STATUS_INSUFFICIENT_RESOURCES.
352    pub max_locks_per_open: std::sync::atomic::AtomicUsize,
353    /// Every lease held on a file of any share.
354    pub(crate) leases: Arc<crate::files::LeaseTable>,
355    /// Every durable open, and the ones kept after their session ended.
356    pub(crate) durable: Arc<DurableTable>,
357    /// The last 8 bytes of every resume key this server hands out.
358    pub(crate) resume_tag: [u8; RESUME_TAG_LEN],
359}
360
361impl ServerState {
362    pub fn new(config: ServerConfig, users: ServerUsers, shares: Vec<Arc<ShareBindings>>) -> Self {
363        let durable = Arc::new(DurableTable::new(
364            config.limits.durable_handle_timeout,
365            config.limits.max_disconnected_opens,
366        ));
367        let mut resume_tag = [0; RESUME_TAG_LEN];
368        fill_random(&mut resume_tag).expect("the OS random number generator works");
369        Self {
370            config,
371            users,
372            shares: ServerShares::new(shares),
373            active_connections: ActiveConnections::new(),
374            shutdown: Arc::new(Notify::new()),
375            shutting_down: Arc::new(AtomicBool::new(false)),
376            auth: crate::auth_policy::AuthPolicy::default(),
377            max_opens_per_connection: std::sync::atomic::AtomicUsize::new(
378                crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
379            ),
380            max_locks_per_open: std::sync::atomic::AtomicUsize::new(
381                crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
382            ),
383            leases: Arc::default(),
384            durable,
385            resume_tag,
386        }
387    }
388
389    /// The access `caller` gets at TREE_CONNECT to `share`, whose ACL is
390    /// `acl`, or `None` when it is refused: the ACL must admit the caller,
391    /// and while unencrypted access is refused, a share whose traffic is
392    /// encrypted refuses a session that cannot encrypt (MS-SMB2 3.3.5.7).
393    pub(crate) fn admits(
394        &self,
395        share: &ShareBindings,
396        acl: &ShareAcl,
397        caller: &Caller,
398    ) -> Option<Access> {
399        let settings = &self.auth.settings;
400        if (settings.encrypt_data || share.encrypt_data)
401            && settings.reject_unencrypted_access
402            && !caller.can_encrypt
403        {
404            return None;
405        }
406        acl.authorize(&caller.identity)
407    }
408
409    /// Find a share by case-insensitive name.
410    pub async fn find_share(&self, name: &str) -> Option<Arc<ShareBindings>> {
411        self.shares.find(name).await
412    }
413
414    /// Look up a user's NT hash by name.
415    pub async fn lookup_user(&self, name: &str) -> Option<UserCreds> {
416        self.users.table.read().await.get(name).cloned()
417    }
418
419    /// Whether anonymous logon is permitted (i.e. at least one share is public).
420    pub async fn anonymous_allowed(&self) -> bool {
421        for share in self.shares.all().await {
422            let acl = share.acl.read().await;
423            if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
424                return true;
425            }
426        }
427        false
428    }
429}
430
431#[derive(Debug, Error, PartialEq, Eq)]
432pub enum ConfigError {
433    #[error("user `{0}` does not exist")]
434    UnknownUser(String),
435    #[error("share `{0}` does not exist")]
436    UnknownShare(String),
437    #[error("duplicate share `{0}`")]
438    DuplicateShare(String),
439    #[error("share `{0}` mixes public mode with explicit users")]
440    PublicMixedWithUsers(String),
441    #[error("user name `{0}` is reserved")]
442    ReservedUserName(String),
443    #[error("user name must be non-empty")]
444    EmptyUserName,
445    #[error("share name `{0}` is reserved")]
446    ReservedShareName(String),
447    #[error("share name `{0}` must be non-empty and contain no `\\`, `/` or NUL")]
448    InvalidShareName(String),
449    #[error("remark of share `{0}` must hold no NUL and at most 1024 UTF-16 code units")]
450    InvalidShareRemark(String),
451}
452
453#[derive(Clone)]
454pub struct ConfigHandle {
455    state: Arc<ServerState>,
456}
457
458impl ConfigHandle {
459    /// Add a user, or replace the password of an existing one. Replacing a
460    /// password ends the user's sessions and closes the user's durable
461    /// opens kept after their session ended.
462    pub async fn add_user(
463        &self,
464        name: impl Into<String>,
465        password: impl AsRef<str>,
466    ) -> Result<(), ConfigError> {
467        let name = name.into();
468        validate_user_name(&name)?;
469        let creds = UserCreds::from_password(password.as_ref());
470        let replaced = self
471            .state
472            .users
473            .table
474            .write()
475            .await
476            .insert(name.clone(), creds.clone());
477        if replaced.is_some_and(|old| old.nt_hash != creds.nt_hash) {
478            self.close_user_sessions(&name).await;
479        }
480        Ok(())
481    }
482
483    pub async fn remove_user(&self, name: &str) -> Result<(), ConfigError> {
484        validate_user_name(name)?;
485        let removed = self.state.users.table.write().await.remove(name);
486        if removed.is_none() {
487            return Err(ConfigError::UnknownUser(name.to_string()));
488        }
489
490        for share in self.state.shares.all().await {
491            share.acl.write().await.users.remove(name);
492        }
493
494        self.close_user_sessions(name).await;
495        Ok(())
496    }
497
498    pub async fn add_share(&self, share: Share) -> Result<(), ConfigError> {
499        validate_share_name(&share.name)?;
500        let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
501        if is_public && !share.users.is_empty() {
502            return Err(ConfigError::PublicMixedWithUsers(share.name));
503        }
504        if !valid_remark(&share.remark) {
505            return Err(ConfigError::InvalidShareRemark(share.name));
506        }
507        let users = self.state.users.table.read().await;
508        for user in share.users.keys() {
509            if !users.contains_key(user) {
510                return Err(ConfigError::UnknownUser(user.clone()));
511            }
512        }
513
514        let binding = ShareBindings::from_share(share);
515        self.state.shares.insert(binding).await
516    }
517
518    pub async fn remove_share(&self, name: &str) -> Result<(), ConfigError> {
519        validate_share_name(name)?;
520        let removed = self
521            .state
522            .shares
523            .remove(name)
524            .await
525            .ok_or_else(|| ConfigError::UnknownShare(name.to_string()))?;
526
527        self.close_share_trees(&removed, None).await;
528        Ok(())
529    }
530
531    /// Grant `user` `access` to a share. Lowering a user's access ends the
532    /// user's trees on the share, so it applies to open connections too, and
533    /// closes the user's durable opens on the share kept after their session
534    /// ended.
535    pub async fn grant_share_user(
536        &self,
537        share_name: &str,
538        user: &str,
539        access: Access,
540    ) -> Result<(), ConfigError> {
541        validate_user_name(user)?;
542        validate_share_name(share_name)?;
543        let users = self.state.users.table.read().await;
544        if !users.contains_key(user) {
545            return Err(ConfigError::UnknownUser(user.to_string()));
546        }
547        drop(users);
548        let share = self
549            .state
550            .find_share(share_name)
551            .await
552            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
553        let mut acl = share.acl.write().await;
554        if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
555            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
556        }
557        let previous = acl.users.insert(user.to_string(), access);
558        drop(acl);
559
560        if previous.is_some_and(|old| old.allows_write() && !access.allows_write()) {
561            self.close_share_trees(&share, Some(user)).await;
562        }
563        Ok(())
564    }
565
566    pub async fn revoke_share_user(&self, share_name: &str, user: &str) -> Result<(), ConfigError> {
567        validate_user_name(user)?;
568        validate_share_name(share_name)?;
569        let share = self
570            .state
571            .find_share(share_name)
572            .await
573            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
574        share.acl.write().await.users.remove(user);
575
576        self.close_share_trees(&share, Some(user)).await;
577        Ok(())
578    }
579
580    pub async fn set_share_mode(
581        &self,
582        share_name: &str,
583        mode: ShareMode,
584    ) -> Result<(), ConfigError> {
585        validate_share_name(share_name)?;
586        let share = self
587            .state
588            .find_share(share_name)
589            .await
590            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
591        let mut acl = share.acl.write().await;
592        if matches!(mode, ShareMode::Public | ShareMode::PublicReadOnly) && !acl.users.is_empty() {
593            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
594        }
595        if acl.mode == mode {
596            return Ok(());
597        }
598        acl.mode = mode;
599        drop(acl);
600
601        self.close_share_trees(&share, None).await;
602        Ok(())
603    }
604
605    /// Set how many files and named pipes one connection may hold open at
606    /// once. A CREATE past the limit fails with STATUS_INSUFFICIENT_RESOURCES;
607    /// opens already held stay open. The default is
608    /// [`DEFAULT_MAX_OPENS_PER_CONNECTION`](crate::DEFAULT_MAX_OPENS_PER_CONNECTION).
609    pub fn set_max_opens_per_connection(&self, limit: usize) {
610        self.state
611            .max_opens_per_connection
612            .store(limit, Ordering::Relaxed);
613    }
614
615    /// Ends every session of `user` on every connection, and closes the
616    /// user's durable opens kept after their session ended. All of them are
617    /// cut off before any open is closed, and closing waits for requests
618    /// still using an open.
619    async fn close_user_sessions(&self, user: &str) {
620        let mut opens = Vec::new();
621        for conn in self.state.active_connections.live().await {
622            opens.extend(conn.detach_sessions_for_user(user).await);
623        }
624        opens.extend(self.state.durable.take_for(None, Some(user)));
625        close_opens(opens).await;
626    }
627
628    /// Ends the trees on `share`, only those of `user` when given, on every
629    /// connection, and closes the matching durable opens kept after their
630    /// session ended, cutting all of them off before closing any open.
631    async fn close_share_trees(&self, share: &Arc<ShareBindings>, user: Option<&str>) {
632        let mut opens = Vec::new();
633        for conn in self.state.active_connections.live().await {
634            opens.extend(match user {
635                Some(user) => conn.detach_trees_for_user_share(user, share).await,
636                None => conn.detach_trees_for_share(share).await,
637            });
638        }
639        opens.extend(self.state.durable.take_for(Some(share), user));
640        close_opens(opens).await;
641    }
642}
643
644fn validate_user_name(name: &str) -> Result<(), ConfigError> {
645    if name.is_empty() {
646        return Err(ConfigError::EmptyUserName);
647    }
648    if name.eq_ignore_ascii_case("anonymous") {
649        return Err(ConfigError::ReservedUserName(name.to_string()));
650    }
651    Ok(())
652}
653
654fn validate_share_name(name: &str) -> Result<(), ConfigError> {
655    match check_share_name(name) {
656        Ok(()) => Ok(()),
657        Err(ShareNameError::Reserved) => Err(ConfigError::ReservedShareName(name.to_string())),
658        Err(ShareNameError::Invalid) => Err(ConfigError::InvalidShareName(name.to_string())),
659    }
660}
661
662// ---------------------------------------------------------------------------
663// SmbServer
664// ---------------------------------------------------------------------------
665
666/// A built but not-yet-running SMB server.
667///
668/// Use `serve()` to bind the configured listener and run until shutdown.
669pub struct SmbServer {
670    state: Arc<ServerState>,
671    /// Listener opened by `bind()`, or by `serve()` if `bind()` was not
672    /// called.
673    bound: tokio::sync::Mutex<Option<TcpListener>>,
674    /// Bound address, set by `bind()`.
675    local_addr: tokio::sync::Mutex<Option<SocketAddr>>,
676    /// What announces the server when discovery is on.
677    #[cfg(feature = "discovery")]
678    discovery_backend: Arc<dyn crate::discovery::Backend>,
679}
680
681impl SmbServer {
682    pub fn builder() -> SmbServerBuilder {
683        SmbServerBuilder::default()
684    }
685
686    pub(crate) fn from_state(state: ServerState) -> Self {
687        Self {
688            state: Arc::new(state),
689            bound: tokio::sync::Mutex::new(None),
690            local_addr: tokio::sync::Mutex::new(None),
691            #[cfg(feature = "discovery")]
692            discovery_backend: Arc::new(crate::discovery::System),
693        }
694    }
695
696    #[cfg(all(test, feature = "discovery"))]
697    pub(crate) fn with_discovery_backend(
698        mut self,
699        backend: Arc<dyn crate::discovery::Backend>,
700    ) -> Self {
701        self.discovery_backend = backend;
702        self
703    }
704
705    pub fn config_handle(&self) -> ConfigHandle {
706        ConfigHandle {
707            state: self.state.clone(),
708        }
709    }
710
711    /// Bind the listen address without starting the accept loop. Returns
712    /// the bound address, which gives the real port when the configured port
713    /// is 0.
714    pub async fn bind(&self) -> io::Result<SocketAddr> {
715        let mut bound = self.bound.lock().await;
716        if let Some(l) = bound.as_ref() {
717            return l.local_addr();
718        }
719        let listener = TcpListener::bind(self.state.config.listen_addr).await?;
720        let addr = listener.local_addr()?;
721        *bound = Some(listener);
722        *self.local_addr.lock().await = Some(addr);
723        Ok(addr)
724    }
725
726    /// Returns the actual bound address. `None` if `bind()`/`serve()` have
727    /// not yet been called.
728    pub async fn local_addr(&self) -> Option<SocketAddr> {
729        *self.local_addr.lock().await
730    }
731
732    /// Listen address as configured. Use `local_addr()` for the bound
733    /// address.
734    pub fn configured_addr(&self) -> SocketAddr {
735        self.state.config.listen_addr
736    }
737
738    /// Initiate a graceful shutdown. Stops the accept loop and closes each
739    /// connection once its current request is answered. Takes effect even
740    /// when called before `serve()`.
741    pub fn shutdown(&self) {
742        self.state.shutting_down.store(true, Ordering::Release);
743        self.state.shutdown.notify_waiters();
744    }
745
746    /// Returns a clonable handle that can request shutdown after `serve()`
747    /// has consumed the `SmbServer` value.
748    pub fn shutdown_handle(&self) -> ShutdownHandle {
749        ShutdownHandle {
750            shutdown: self.state.shutdown.clone(),
751            shutting_down: self.state.shutting_down.clone(),
752        }
753    }
754
755    /// Run the accept loop until `shutdown()` is called. Returns once every
756    /// connection has closed and every durable open kept after its session
757    /// ended is closed, including closes that expiry or a lease break had
758    /// already started.
759    pub async fn serve(self) -> io::Result<()> {
760        if self.bound.lock().await.is_none() {
761            self.bind().await?;
762        }
763        let listener = self
764            .bound
765            .lock()
766            .await
767            .take()
768            .expect("listener bound above");
769        let local = listener.local_addr().ok();
770        let span = info_span!("smb_server", listen = ?local);
771        async move {
772            info!("server starting");
773            let state = self.state.clone();
774            let shutdown = state.shutdown.clone();
775            let shutting_down = state.shutting_down.clone();
776            let mut backoff = AcceptBackoff::new();
777            let mut connections = JoinSet::new();
778            let limits = &state.config.limits;
779            let slots = Arc::new(Semaphore::new(
780                limits.max_connections.min(Semaphore::MAX_PERMITS),
781            ));
782            let mut at_capacity = false;
783            #[cfg(feature = "discovery")]
784            let announcer = state
785                .config
786                .discovery
787                .as_ref()
788                .filter(|_| !shutting_down.load(Ordering::Acquire))
789                .and_then(|settings| {
790                    crate::discovery::Announcer::start(
791                        settings,
792                        &listener,
793                        self.discovery_backend.clone(),
794                    )
795                });
796
797            loop {
798                let stopped = shutdown.notified();
799                tokio::pin!(stopped);
800                stopped.as_mut().enable();
801                if shutting_down.load(Ordering::Acquire) {
802                    info!("shutdown requested; stopping accept loop");
803                    break;
804                }
805                let retry_after = tokio::select! {
806                    biased;
807                    _ = &mut stopped => {
808                        info!("shutdown requested; stopping accept loop");
809                        break;
810                    }
811                    Some(_) = connections.join_next(), if !connections.is_empty() => None,
812                    accept = listener.accept() => {
813                        match accept {
814                            Ok((stream, peer)) => {
815                                backoff.succeeded();
816                                if shutting_down.load(Ordering::Acquire) {
817                                    drop(stream);
818                                    break;
819                                }
820                                let Ok(slot) = slots.clone().try_acquire_owned() else {
821                                    if !at_capacity {
822                                        warn!(
823                                            max = limits.max_connections,
824                                            "connection limit reached; closing new connections"
825                                        );
826                                        at_capacity = true;
827                                    }
828                                    debug!(%peer, "connection refused: limit reached");
829                                    drop(stream);
830                                    continue;
831                                };
832                                if at_capacity {
833                                    info!("below the connection limit again");
834                                    at_capacity = false;
835                                }
836                                configure_socket(&stream, limits.tcp_keepalive);
837                                let server_state = state.clone();
838                                let span = info_span!("conn", peer = %peer);
839                                connections.spawn(async move {
840                                    let _slot = slot;
841                                    if let Err(e) = connection_loop(stream, peer, server_state).await {
842                                        error!(error = %e, "connection loop exited with error");
843                                    }
844                                }.instrument(span));
845                                None
846                            }
847                            Err(e) => {
848                                if shutting_down.load(Ordering::Acquire) {
849                                    break;
850                                }
851                                Some(backoff.failed(&e))
852                            }
853                        }
854                    }
855                };
856                if let Some(delay) = retry_after {
857                    tokio::select! {
858                        biased;
859                        _ = &mut stopped => {
860                            info!("shutdown requested; stopping accept loop");
861                            break;
862                        }
863                        _ = tokio::time::sleep(delay) => {}
864                    }
865                }
866            }
867            drop(listener);
868            let drained = async {
869                if !connections.is_empty() {
870                    info!(open = connections.len(), "waiting for connections to close");
871                }
872                while connections.join_next().await.is_some() {}
873                close_opens(state.durable.take_for(None, None)).await;
874                state.durable.closed().await;
875            };
876            #[cfg(feature = "discovery")]
877            tokio::join!(drained, async {
878                if let Some(announcer) = announcer {
879                    announcer.stop().await;
880                }
881            });
882            #[cfg(not(feature = "discovery"))]
883            drained.await;
884            info!("server stopped");
885            Ok::<(), io::Error>(())
886        }
887        .instrument(span)
888        .await
889    }
890
891    #[cfg(any(test, fuzzing))]
892    pub(crate) fn state(&self) -> Arc<ServerState> {
893        self.state.clone()
894    }
895}
896
897/// Cheaply-clonable shutdown handle. Outlives `SmbServer::serve` consuming
898/// the server.
899#[derive(Clone)]
900pub struct ShutdownHandle {
901    shutdown: Arc<Notify>,
902    shutting_down: Arc<AtomicBool>,
903}
904
905impl ShutdownHandle {
906    /// Request a graceful shutdown.
907    pub fn shutdown(&self) {
908        self.shutting_down.store(true, Ordering::Release);
909        self.shutdown.notify_waiters();
910    }
911}