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::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::{Access, Share, ShareNameError, SmbServerBuilder, check_share_name};
20use crate::conn::connection_loop;
21use crate::conn::limits::Limits;
22use crate::conn::listener::{AcceptBackoff, configure_socket};
23use crate::conn::state::Connection;
24use crate::files::close_opens;
25
26// ---------------------------------------------------------------------------
27// ShareMode / ShareBindings
28// ---------------------------------------------------------------------------
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ShareMode {
32    Public,
33    PublicReadOnly,
34    /// Default: closed share. Only users in the explicit `users` map allowed.
35    AuthenticatedOnly,
36}
37
38#[derive(Clone)]
39pub struct ShareAcl {
40    pub mode: ShareMode,
41    pub users: HashMap<String, Access>,
42}
43
44/// Compiled binding for a single share: the per-server-state form of `Share`.
45pub struct ShareBindings {
46    pub name: String,
47    pub backend: Arc<dyn ShareBackend>,
48    pub acl: RwLock<ShareAcl>,
49    /// `IPC$` synthetic share. Accepted at TREE_CONNECT; opens on it fail.
50    pub is_ipc: bool,
51    /// Every file on the share that has an open, on any connection.
52    pub(crate) files: crate::files::FileTable,
53}
54
55impl ShareBindings {
56    pub(crate) fn new(
57        name: String,
58        backend: Arc<dyn ShareBackend>,
59        mode: ShareMode,
60        users: HashMap<String, Access>,
61        is_ipc: bool,
62    ) -> Arc<Self> {
63        Arc::new(Self {
64            name,
65            backend,
66            acl: RwLock::new(ShareAcl { mode, users }),
67            is_ipc,
68            files: crate::files::FileTable::default(),
69        })
70    }
71
72    /// Synthetic IPC$ share. Opens on it fail.
73    pub fn ipc() -> Arc<Self> {
74        Self::new(
75            "IPC$".to_string(),
76            Arc::new(crate::backend::NotSupportedBackend),
77            ShareMode::PublicReadOnly,
78            HashMap::new(),
79            true,
80        )
81    }
82}
83
84// ---------------------------------------------------------------------------
85// ServerConfig / ServerUsers / ServerState
86// ---------------------------------------------------------------------------
87
88#[derive(Debug, Clone)]
89pub struct ServerConfig {
90    pub listen_addr: SocketAddr,
91    pub netbios_name: String,
92    pub max_read_size: u32,
93    pub max_write_size: u32,
94    pub server_guid: Uuid,
95    pub limits: Limits,
96}
97
98pub struct ServerUsers {
99    /// Username -> precomputed NT hash record.
100    pub table: RwLock<HashMap<String, UserCreds>>,
101}
102
103pub struct ServerShares {
104    by_name: RwLock<HashMap<String, Arc<ShareBindings>>>,
105}
106
107impl ServerShares {
108    pub fn new(shares: Vec<Arc<ShareBindings>>) -> Self {
109        let mut by_name = HashMap::with_capacity(shares.len());
110        for share in shares {
111            by_name.insert(share.name.to_ascii_lowercase(), share);
112        }
113        Self {
114            by_name: RwLock::new(by_name),
115        }
116    }
117
118    pub async fn find(&self, name: &str) -> Option<Arc<ShareBindings>> {
119        self.by_name
120            .read()
121            .await
122            .get(&name.to_ascii_lowercase())
123            .cloned()
124    }
125
126    pub async fn insert(&self, share: Arc<ShareBindings>) -> Result<(), ConfigError> {
127        let key = share.name.to_ascii_lowercase();
128        let mut by_name = self.by_name.write().await;
129        if by_name.contains_key(&key) {
130            return Err(ConfigError::DuplicateShare(share.name.clone()));
131        }
132        by_name.insert(key, share);
133        Ok(())
134    }
135
136    pub async fn remove(&self, name: &str) -> Option<Arc<ShareBindings>> {
137        self.by_name
138            .write()
139            .await
140            .remove(&name.to_ascii_lowercase())
141    }
142
143    pub async fn all(&self) -> Vec<Arc<ShareBindings>> {
144        self.by_name.read().await.values().cloned().collect()
145    }
146}
147
148pub struct ActiveConnections {
149    next_id: AtomicU64,
150    conns: RwLock<HashMap<u64, Weak<Connection>>>,
151}
152
153impl ActiveConnections {
154    pub fn new() -> Self {
155        Self {
156            next_id: AtomicU64::new(1),
157            conns: RwLock::new(HashMap::new()),
158        }
159    }
160
161    pub async fn register(&self, conn: &Arc<Connection>) -> u64 {
162        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
163        self.conns.write().await.insert(id, Arc::downgrade(conn));
164        id
165    }
166
167    pub async fn unregister(&self, id: u64) {
168        self.conns.write().await.remove(&id);
169    }
170
171    pub async fn live(&self) -> Vec<Arc<Connection>> {
172        let mut live = Vec::new();
173        let mut conns = self.conns.write().await;
174        conns.retain(|_, weak| {
175            if let Some(conn) = weak.upgrade() {
176                live.push(conn);
177                true
178            } else {
179                false
180            }
181        });
182        live
183    }
184}
185
186impl Default for ActiveConnections {
187    fn default() -> Self {
188        Self::new()
189    }
190}
191
192/// Server state shared across connections.
193pub struct ServerState {
194    pub config: ServerConfig,
195    pub users: ServerUsers,
196    pub shares: ServerShares,
197    pub active_connections: ActiveConnections,
198    /// Notified by `shutdown()`. The accept loop stops; each connection
199    /// closes once it has answered the frame it is receiving, if any.
200    pub shutdown: Arc<Notify>,
201    pub shutting_down: Arc<AtomicBool>,
202    /// Signing policy, session and tree limits, and the logon throttle.
203    pub auth: crate::auth_policy::AuthPolicy,
204
205    /// Opens one connection may hold at once. CREATE past it fails with
206    /// STATUS_INSUFFICIENT_RESOURCES.
207    pub max_opens_per_connection: std::sync::atomic::AtomicUsize,
208    /// Byte-range locks one open may hold at once. LOCK past it fails with
209    /// STATUS_INSUFFICIENT_RESOURCES.
210    pub max_locks_per_open: std::sync::atomic::AtomicUsize,
211}
212
213impl ServerState {
214    pub fn new(config: ServerConfig, users: ServerUsers, shares: Vec<Arc<ShareBindings>>) -> Self {
215        Self {
216            config,
217            users,
218            shares: ServerShares::new(shares),
219            active_connections: ActiveConnections::new(),
220            shutdown: Arc::new(Notify::new()),
221            shutting_down: Arc::new(AtomicBool::new(false)),
222            auth: crate::auth_policy::AuthPolicy::default(),
223            max_opens_per_connection: std::sync::atomic::AtomicUsize::new(
224                crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
225            ),
226            max_locks_per_open: std::sync::atomic::AtomicUsize::new(
227                crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
228            ),
229        }
230    }
231
232    /// Find a share by case-insensitive name.
233    pub async fn find_share(&self, name: &str) -> Option<Arc<ShareBindings>> {
234        self.shares.find(name).await
235    }
236
237    /// Look up a user's NT hash by name.
238    pub async fn lookup_user(&self, name: &str) -> Option<UserCreds> {
239        self.users.table.read().await.get(name).cloned()
240    }
241
242    /// Whether anonymous logon is permitted (i.e. at least one share is public).
243    pub async fn anonymous_allowed(&self) -> bool {
244        for share in self.shares.all().await {
245            let acl = share.acl.read().await;
246            if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
247                return true;
248            }
249        }
250        false
251    }
252}
253
254#[derive(Debug, Error, PartialEq, Eq)]
255pub enum ConfigError {
256    #[error("user `{0}` does not exist")]
257    UnknownUser(String),
258    #[error("share `{0}` does not exist")]
259    UnknownShare(String),
260    #[error("duplicate share `{0}`")]
261    DuplicateShare(String),
262    #[error("share `{0}` mixes public mode with explicit users")]
263    PublicMixedWithUsers(String),
264    #[error("user name `{0}` is reserved")]
265    ReservedUserName(String),
266    #[error("user name must be non-empty")]
267    EmptyUserName,
268    #[error("share name `{0}` is reserved")]
269    ReservedShareName(String),
270    #[error("share name `{0}` must be non-empty and contain no `\\` or `/`")]
271    InvalidShareName(String),
272}
273
274#[derive(Clone)]
275pub struct ConfigHandle {
276    state: Arc<ServerState>,
277}
278
279impl ConfigHandle {
280    /// Add a user, or replace the password of an existing one. Replacing a
281    /// password ends the user's sessions.
282    pub async fn add_user(
283        &self,
284        name: impl Into<String>,
285        password: impl AsRef<str>,
286    ) -> Result<(), ConfigError> {
287        let name = name.into();
288        validate_user_name(&name)?;
289        let creds = UserCreds::from_password(password.as_ref());
290        let replaced = self
291            .state
292            .users
293            .table
294            .write()
295            .await
296            .insert(name.clone(), creds.clone());
297        if replaced.is_some_and(|old| old.nt_hash != creds.nt_hash) {
298            self.close_user_sessions(&name).await;
299        }
300        Ok(())
301    }
302
303    pub async fn remove_user(&self, name: &str) -> Result<(), ConfigError> {
304        validate_user_name(name)?;
305        let removed = self.state.users.table.write().await.remove(name);
306        if removed.is_none() {
307            return Err(ConfigError::UnknownUser(name.to_string()));
308        }
309
310        for share in self.state.shares.all().await {
311            share.acl.write().await.users.remove(name);
312        }
313
314        self.close_user_sessions(name).await;
315        Ok(())
316    }
317
318    pub async fn add_share(&self, share: Share) -> Result<(), ConfigError> {
319        validate_share_name(&share.name)?;
320        let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
321        if is_public && !share.users.is_empty() {
322            return Err(ConfigError::PublicMixedWithUsers(share.name));
323        }
324        let users = self.state.users.table.read().await;
325        for user in share.users.keys() {
326            if !users.contains_key(user) {
327                return Err(ConfigError::UnknownUser(user.clone()));
328            }
329        }
330
331        let binding = ShareBindings::new(share.name, share.backend, share.mode, share.users, false);
332        self.state.shares.insert(binding).await
333    }
334
335    pub async fn remove_share(&self, name: &str) -> Result<(), ConfigError> {
336        validate_share_name(name)?;
337        let removed = self
338            .state
339            .shares
340            .remove(name)
341            .await
342            .ok_or_else(|| ConfigError::UnknownShare(name.to_string()))?;
343
344        self.close_share_trees(&removed, None).await;
345        Ok(())
346    }
347
348    /// Grant `user` `access` to a share. Lowering a user's access ends the
349    /// user's trees on the share, so it applies to open connections too.
350    pub async fn grant_share_user(
351        &self,
352        share_name: &str,
353        user: &str,
354        access: Access,
355    ) -> Result<(), ConfigError> {
356        validate_user_name(user)?;
357        validate_share_name(share_name)?;
358        let users = self.state.users.table.read().await;
359        if !users.contains_key(user) {
360            return Err(ConfigError::UnknownUser(user.to_string()));
361        }
362        drop(users);
363        let share = self
364            .state
365            .find_share(share_name)
366            .await
367            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
368        let mut acl = share.acl.write().await;
369        if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
370            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
371        }
372        let previous = acl.users.insert(user.to_string(), access);
373        drop(acl);
374
375        if previous.is_some_and(|old| old.allows_write() && !access.allows_write()) {
376            self.close_share_trees(&share, Some(user)).await;
377        }
378        Ok(())
379    }
380
381    pub async fn revoke_share_user(&self, share_name: &str, user: &str) -> Result<(), ConfigError> {
382        validate_user_name(user)?;
383        validate_share_name(share_name)?;
384        let share = self
385            .state
386            .find_share(share_name)
387            .await
388            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
389        share.acl.write().await.users.remove(user);
390
391        self.close_share_trees(&share, Some(user)).await;
392        Ok(())
393    }
394
395    pub async fn set_share_mode(
396        &self,
397        share_name: &str,
398        mode: ShareMode,
399    ) -> Result<(), ConfigError> {
400        validate_share_name(share_name)?;
401        let share = self
402            .state
403            .find_share(share_name)
404            .await
405            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
406        let mut acl = share.acl.write().await;
407        if matches!(mode, ShareMode::Public | ShareMode::PublicReadOnly) && !acl.users.is_empty() {
408            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
409        }
410        if acl.mode == mode {
411            return Ok(());
412        }
413        acl.mode = mode;
414        drop(acl);
415
416        self.close_share_trees(&share, None).await;
417        Ok(())
418    }
419
420    /// Set how many files one connection may hold open at once. A CREATE
421    /// past the limit fails with STATUS_INSUFFICIENT_RESOURCES; opens already
422    /// held stay open. The default is
423    /// [`DEFAULT_MAX_OPENS_PER_CONNECTION`](crate::DEFAULT_MAX_OPENS_PER_CONNECTION).
424    pub fn set_max_opens_per_connection(&self, limit: usize) {
425        self.state
426            .max_opens_per_connection
427            .store(limit, Ordering::Relaxed);
428    }
429
430    /// Ends every session of `user` on every connection. All of them are
431    /// cut off before any open is closed, and closing waits for requests
432    /// still using an open.
433    async fn close_user_sessions(&self, user: &str) {
434        let mut opens = Vec::new();
435        for conn in self.state.active_connections.live().await {
436            opens.extend(conn.detach_sessions_for_user(user).await);
437        }
438        close_opens(opens).await;
439    }
440
441    /// Ends the trees on `share`, only those of `user` when given, on every
442    /// connection, cutting all of them off before closing any open.
443    async fn close_share_trees(&self, share: &Arc<ShareBindings>, user: Option<&str>) {
444        let mut opens = Vec::new();
445        for conn in self.state.active_connections.live().await {
446            opens.extend(match user {
447                Some(user) => conn.detach_trees_for_user_share(user, share).await,
448                None => conn.detach_trees_for_share(share).await,
449            });
450        }
451        close_opens(opens).await;
452    }
453}
454
455fn validate_user_name(name: &str) -> Result<(), ConfigError> {
456    if name.is_empty() {
457        return Err(ConfigError::EmptyUserName);
458    }
459    if name.eq_ignore_ascii_case("anonymous") {
460        return Err(ConfigError::ReservedUserName(name.to_string()));
461    }
462    Ok(())
463}
464
465fn validate_share_name(name: &str) -> Result<(), ConfigError> {
466    match check_share_name(name) {
467        Ok(()) => Ok(()),
468        Err(ShareNameError::Reserved) => Err(ConfigError::ReservedShareName(name.to_string())),
469        Err(ShareNameError::Invalid) => Err(ConfigError::InvalidShareName(name.to_string())),
470    }
471}
472
473// ---------------------------------------------------------------------------
474// SmbServer
475// ---------------------------------------------------------------------------
476
477/// A built but not-yet-running SMB server.
478///
479/// Use `serve()` to bind the configured listener and run until shutdown.
480pub struct SmbServer {
481    state: Arc<ServerState>,
482    /// Listener opened by `bind()`, or by `serve()` if `bind()` was not
483    /// called.
484    bound: tokio::sync::Mutex<Option<TcpListener>>,
485    /// Bound address, set by `bind()`.
486    local_addr: tokio::sync::Mutex<Option<SocketAddr>>,
487}
488
489impl SmbServer {
490    pub fn builder() -> SmbServerBuilder {
491        SmbServerBuilder::default()
492    }
493
494    pub(crate) fn from_state(state: ServerState) -> Self {
495        Self {
496            state: Arc::new(state),
497            bound: tokio::sync::Mutex::new(None),
498            local_addr: tokio::sync::Mutex::new(None),
499        }
500    }
501
502    pub fn config_handle(&self) -> ConfigHandle {
503        ConfigHandle {
504            state: self.state.clone(),
505        }
506    }
507
508    /// Bind the listen address without starting the accept loop. Returns
509    /// the bound address, which gives the real port when the configured port
510    /// is 0.
511    pub async fn bind(&self) -> io::Result<SocketAddr> {
512        let mut bound = self.bound.lock().await;
513        if let Some(l) = bound.as_ref() {
514            return l.local_addr();
515        }
516        let listener = TcpListener::bind(self.state.config.listen_addr).await?;
517        let addr = listener.local_addr()?;
518        *bound = Some(listener);
519        *self.local_addr.lock().await = Some(addr);
520        Ok(addr)
521    }
522
523    /// Returns the actual bound address. `None` if `bind()`/`serve()` have
524    /// not yet been called.
525    pub async fn local_addr(&self) -> Option<SocketAddr> {
526        *self.local_addr.lock().await
527    }
528
529    /// Listen address as configured. Use `local_addr()` for the bound
530    /// address.
531    pub fn configured_addr(&self) -> SocketAddr {
532        self.state.config.listen_addr
533    }
534
535    /// Initiate a graceful shutdown. Stops the accept loop and closes each
536    /// connection once its current request is answered. Takes effect even
537    /// when called before `serve()`.
538    pub fn shutdown(&self) {
539        self.state.shutting_down.store(true, Ordering::Release);
540        self.state.shutdown.notify_waiters();
541    }
542
543    /// Returns a clonable handle that can request shutdown after `serve()`
544    /// has consumed the `SmbServer` value.
545    pub fn shutdown_handle(&self) -> ShutdownHandle {
546        ShutdownHandle {
547            shutdown: self.state.shutdown.clone(),
548            shutting_down: self.state.shutting_down.clone(),
549        }
550    }
551
552    /// Run the accept loop until `shutdown()` is called. Returns once every
553    /// connection has closed.
554    pub async fn serve(self) -> io::Result<()> {
555        if self.bound.lock().await.is_none() {
556            self.bind().await?;
557        }
558        let listener = self
559            .bound
560            .lock()
561            .await
562            .take()
563            .expect("listener bound above");
564        let local = listener.local_addr().ok();
565        let span = info_span!("smb_server", listen = ?local);
566        async move {
567            info!("server starting");
568            let state = self.state.clone();
569            let shutdown = state.shutdown.clone();
570            let shutting_down = state.shutting_down.clone();
571            let mut backoff = AcceptBackoff::new();
572            let mut connections = JoinSet::new();
573            let limits = &state.config.limits;
574            let slots = Arc::new(Semaphore::new(
575                limits.max_connections.min(Semaphore::MAX_PERMITS),
576            ));
577            let mut at_capacity = false;
578
579            loop {
580                let stopped = shutdown.notified();
581                tokio::pin!(stopped);
582                stopped.as_mut().enable();
583                if shutting_down.load(Ordering::Acquire) {
584                    info!("shutdown requested; stopping accept loop");
585                    break;
586                }
587                let retry_after = tokio::select! {
588                    biased;
589                    _ = &mut stopped => {
590                        info!("shutdown requested; stopping accept loop");
591                        break;
592                    }
593                    Some(_) = connections.join_next(), if !connections.is_empty() => None,
594                    accept = listener.accept() => {
595                        match accept {
596                            Ok((stream, peer)) => {
597                                backoff.succeeded();
598                                if shutting_down.load(Ordering::Acquire) {
599                                    drop(stream);
600                                    break;
601                                }
602                                let Ok(slot) = slots.clone().try_acquire_owned() else {
603                                    if !at_capacity {
604                                        warn!(
605                                            max = limits.max_connections,
606                                            "connection limit reached; closing new connections"
607                                        );
608                                        at_capacity = true;
609                                    }
610                                    debug!(%peer, "connection refused: limit reached");
611                                    drop(stream);
612                                    continue;
613                                };
614                                if at_capacity {
615                                    info!("below the connection limit again");
616                                    at_capacity = false;
617                                }
618                                configure_socket(&stream, limits.tcp_keepalive);
619                                let server_state = state.clone();
620                                let span = info_span!("conn", peer = %peer);
621                                connections.spawn(async move {
622                                    let _slot = slot;
623                                    if let Err(e) = connection_loop(stream, peer, server_state).await {
624                                        error!(error = %e, "connection loop exited with error");
625                                    }
626                                }.instrument(span));
627                                None
628                            }
629                            Err(e) => {
630                                if shutting_down.load(Ordering::Acquire) {
631                                    break;
632                                }
633                                Some(backoff.failed(&e))
634                            }
635                        }
636                    }
637                };
638                if let Some(delay) = retry_after {
639                    tokio::select! {
640                        biased;
641                        _ = &mut stopped => {
642                            info!("shutdown requested; stopping accept loop");
643                            break;
644                        }
645                        _ = tokio::time::sleep(delay) => {}
646                    }
647                }
648            }
649            drop(listener);
650            if !connections.is_empty() {
651                info!(open = connections.len(), "waiting for connections to close");
652            }
653            while connections.join_next().await.is_some() {}
654            info!("server stopped");
655            Ok::<(), io::Error>(())
656        }
657        .instrument(span)
658        .await
659    }
660
661    #[cfg(any(test, fuzzing))]
662    pub(crate) fn state(&self) -> Arc<ServerState> {
663        self.state.clone()
664    }
665}
666
667/// Cheaply-clonable shutdown handle. Outlives `SmbServer::serve` consuming
668/// the server.
669#[derive(Clone)]
670pub struct ShutdownHandle {
671    shutdown: Arc<Notify>,
672    shutting_down: Arc<AtomicBool>,
673}
674
675impl ShutdownHandle {
676    /// Request a graceful shutdown.
677    pub fn shutdown(&self) {
678        self.shutting_down.store(true, Ordering::Release);
679        self.shutdown.notify_waiters();
680    }
681}