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