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