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};
14use tracing::{Instrument, error, info, info_span};
15use uuid::Uuid;
16
17use crate::backend::ShareBackend;
18use crate::builder::{Access, Share, SmbServerBuilder};
19use crate::conn::connection_loop;
20use crate::conn::state::Connection;
21use crate::utils::now_filetime;
22
23// ---------------------------------------------------------------------------
24// ShareMode / ShareBindings
25// ---------------------------------------------------------------------------
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ShareMode {
29    Public,
30    PublicReadOnly,
31    /// Default — closed share. Only users in the explicit `users` map allowed.
32    AuthenticatedOnly,
33}
34
35#[derive(Clone)]
36pub struct ShareAcl {
37    pub mode: ShareMode,
38    pub users: HashMap<String, Access>,
39}
40
41/// Compiled binding for a single share — the per-server-state form of `Share`.
42pub struct ShareBindings {
43    pub name: String,
44    pub backend: Arc<dyn ShareBackend>,
45    pub acl: RwLock<ShareAcl>,
46    /// `IPC$` synthetic share. Accepted at TREE_CONNECT for client compatibility
47    /// (Windows always probes IPC$ before mounting an actual share). All
48    /// downstream ops on an IPC$ tree return `STATUS_NOT_SUPPORTED`.
49    pub is_ipc: bool,
50}
51
52impl ShareBindings {
53    pub(crate) fn new(
54        name: String,
55        backend: Arc<dyn ShareBackend>,
56        mode: ShareMode,
57        users: HashMap<String, Access>,
58        is_ipc: bool,
59    ) -> Arc<Self> {
60        Arc::new(Self {
61            name,
62            backend,
63            acl: RwLock::new(ShareAcl { mode, users }),
64            is_ipc,
65        })
66    }
67
68    /// Synthetic IPC$ share. The backend is a no-op; clients that try to
69    /// CREATE on it get `STATUS_NOT_SUPPORTED` from the CREATE handler.
70    pub fn ipc() -> Arc<Self> {
71        Self::new(
72            "IPC$".to_string(),
73            Arc::new(crate::backend::NotSupportedBackend),
74            ShareMode::PublicReadOnly,
75            HashMap::new(),
76            true,
77        )
78    }
79}
80
81// ---------------------------------------------------------------------------
82// ServerConfig / ServerUsers / ServerState
83// ---------------------------------------------------------------------------
84
85#[derive(Debug, Clone)]
86pub struct ServerConfig {
87    pub listen_addr: SocketAddr,
88    pub netbios_name: String,
89    pub max_read_size: u32,
90    pub max_write_size: u32,
91    pub server_guid: Uuid,
92}
93
94pub struct ServerUsers {
95    /// Username → precomputed NT hash record.
96    pub table: RwLock<HashMap<String, UserCreds>>,
97}
98
99pub struct ServerShares {
100    by_name: RwLock<HashMap<String, Arc<ShareBindings>>>,
101}
102
103impl ServerShares {
104    pub fn new(shares: Vec<Arc<ShareBindings>>) -> Self {
105        let mut by_name = HashMap::with_capacity(shares.len());
106        for share in shares {
107            by_name.insert(share.name.to_ascii_lowercase(), share);
108        }
109        Self {
110            by_name: RwLock::new(by_name),
111        }
112    }
113
114    pub async fn find(&self, name: &str) -> Option<Arc<ShareBindings>> {
115        self.by_name
116            .read()
117            .await
118            .get(&name.to_ascii_lowercase())
119            .cloned()
120    }
121
122    pub async fn insert(&self, share: Arc<ShareBindings>) -> Result<(), ConfigError> {
123        let key = share.name.to_ascii_lowercase();
124        let mut by_name = self.by_name.write().await;
125        if by_name.contains_key(&key) {
126            return Err(ConfigError::DuplicateShare(share.name.clone()));
127        }
128        by_name.insert(key, share);
129        Ok(())
130    }
131
132    pub async fn remove(&self, name: &str) -> Option<Arc<ShareBindings>> {
133        self.by_name
134            .write()
135            .await
136            .remove(&name.to_ascii_lowercase())
137    }
138
139    pub async fn all(&self) -> Vec<Arc<ShareBindings>> {
140        self.by_name.read().await.values().cloned().collect()
141    }
142}
143
144pub struct ActiveConnections {
145    next_id: AtomicU64,
146    conns: RwLock<HashMap<u64, Weak<Connection>>>,
147}
148
149impl ActiveConnections {
150    pub fn new() -> Self {
151        Self {
152            next_id: AtomicU64::new(1),
153            conns: RwLock::new(HashMap::new()),
154        }
155    }
156
157    pub async fn register(&self, conn: &Arc<Connection>) -> u64 {
158        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
159        self.conns.write().await.insert(id, Arc::downgrade(conn));
160        id
161    }
162
163    pub async fn unregister(&self, id: u64) {
164        self.conns.write().await.remove(&id);
165    }
166
167    pub async fn live(&self) -> Vec<Arc<Connection>> {
168        let mut live = Vec::new();
169        let mut conns = self.conns.write().await;
170        conns.retain(|_, weak| {
171            if let Some(conn) = weak.upgrade() {
172                live.push(conn);
173                true
174            } else {
175                false
176            }
177        });
178        live
179    }
180}
181
182impl Default for ActiveConnections {
183    fn default() -> Self {
184        Self::new()
185    }
186}
187
188/// Top-level immutable-ish state shared across connections.
189pub struct ServerState {
190    pub config: ServerConfig,
191    pub users: ServerUsers,
192    pub shares: ServerShares,
193    pub active_connections: ActiveConnections,
194    pub server_start_filetime: u64,
195    /// Set when `shutdown()` is invoked; the accept loop stops on the next
196    /// iteration and connection loops abandon their next read.
197    pub shutdown: Arc<Notify>,
198    pub shutting_down: Arc<AtomicBool>,
199}
200
201impl ServerState {
202    pub fn new(config: ServerConfig, users: ServerUsers, shares: Vec<Arc<ShareBindings>>) -> Self {
203        Self {
204            config,
205            users,
206            shares: ServerShares::new(shares),
207            active_connections: ActiveConnections::new(),
208            server_start_filetime: now_filetime(),
209            shutdown: Arc::new(Notify::new()),
210            shutting_down: Arc::new(AtomicBool::new(false)),
211        }
212    }
213
214    /// Find a share by case-insensitive name.
215    pub async fn find_share(&self, name: &str) -> Option<Arc<ShareBindings>> {
216        self.shares.find(name).await
217    }
218
219    /// Look up a user's NT hash by name.
220    pub async fn lookup_user(&self, name: &str) -> Option<UserCreds> {
221        self.users.table.read().await.get(name).cloned()
222    }
223
224    /// Whether anonymous logon is permitted (i.e. at least one share is public).
225    pub async fn anonymous_allowed(&self) -> bool {
226        for share in self.shares.all().await {
227            let acl = share.acl.read().await;
228            if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
229                return true;
230            }
231        }
232        false
233    }
234}
235
236#[derive(Debug, Error, PartialEq, Eq)]
237pub enum ConfigError {
238    #[error("user `{0}` does not exist")]
239    UnknownUser(String),
240    #[error("share `{0}` does not exist")]
241    UnknownShare(String),
242    #[error("duplicate share `{0}`")]
243    DuplicateShare(String),
244    #[error("share `{0}` mixes public mode with explicit users")]
245    PublicMixedWithUsers(String),
246    #[error("user name `{0}` is reserved")]
247    ReservedUserName(String),
248    #[error("user name must be non-empty")]
249    EmptyUserName,
250    #[error("share name `{0}` is reserved")]
251    ReservedShareName(String),
252}
253
254#[derive(Clone)]
255pub struct ConfigHandle {
256    state: Arc<ServerState>,
257}
258
259impl ConfigHandle {
260    pub async fn add_user(
261        &self,
262        name: impl Into<String>,
263        password: impl AsRef<str>,
264    ) -> Result<(), ConfigError> {
265        let name = name.into();
266        validate_user_name(&name)?;
267        let creds = UserCreds::from_password(password.as_ref());
268        self.state.users.table.write().await.insert(name, creds);
269        Ok(())
270    }
271
272    pub async fn remove_user(&self, name: &str) -> Result<(), ConfigError> {
273        validate_user_name(name)?;
274        let removed = self.state.users.table.write().await.remove(name);
275        if removed.is_none() {
276            return Err(ConfigError::UnknownUser(name.to_string()));
277        }
278
279        for share in self.state.shares.all().await {
280            share.acl.write().await.users.remove(name);
281        }
282
283        for conn in self.state.active_connections.live().await {
284            conn.close_sessions_for_user(name).await;
285        }
286        Ok(())
287    }
288
289    pub async fn add_share(&self, share: Share) -> Result<(), ConfigError> {
290        validate_share_name(&share.name)?;
291        let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
292        if is_public && !share.users.is_empty() {
293            return Err(ConfigError::PublicMixedWithUsers(share.name));
294        }
295        let users = self.state.users.table.read().await;
296        for user in share.users.keys() {
297            if !users.contains_key(user) {
298                return Err(ConfigError::UnknownUser(user.clone()));
299            }
300        }
301
302        let binding = ShareBindings::new(share.name, share.backend, share.mode, share.users, false);
303        self.state.shares.insert(binding).await
304    }
305
306    pub async fn remove_share(&self, name: &str) -> Result<(), ConfigError> {
307        validate_share_name(name)?;
308        let removed = self.state.shares.remove(name).await;
309        if removed.is_none() {
310            return Err(ConfigError::UnknownShare(name.to_string()));
311        }
312
313        for conn in self.state.active_connections.live().await {
314            conn.close_trees_for_share(name).await;
315        }
316        Ok(())
317    }
318
319    pub async fn grant_share_user(
320        &self,
321        share_name: &str,
322        user: &str,
323        access: Access,
324    ) -> Result<(), ConfigError> {
325        validate_user_name(user)?;
326        validate_share_name(share_name)?;
327        let users = self.state.users.table.read().await;
328        if !users.contains_key(user) {
329            return Err(ConfigError::UnknownUser(user.to_string()));
330        }
331        let share = self
332            .state
333            .find_share(share_name)
334            .await
335            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
336        let mut acl = share.acl.write().await;
337        if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
338            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
339        }
340        acl.users.insert(user.to_string(), access);
341        Ok(())
342    }
343
344    pub async fn revoke_share_user(&self, share_name: &str, user: &str) -> Result<(), ConfigError> {
345        validate_user_name(user)?;
346        validate_share_name(share_name)?;
347        let share = self
348            .state
349            .find_share(share_name)
350            .await
351            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
352        share.acl.write().await.users.remove(user);
353
354        for conn in self.state.active_connections.live().await {
355            conn.close_trees_for_user_share(user, share_name).await;
356        }
357        Ok(())
358    }
359
360    pub async fn set_share_mode(
361        &self,
362        share_name: &str,
363        mode: ShareMode,
364    ) -> Result<(), ConfigError> {
365        validate_share_name(share_name)?;
366        let share = self
367            .state
368            .find_share(share_name)
369            .await
370            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
371        let mut acl = share.acl.write().await;
372        if matches!(mode, ShareMode::Public | ShareMode::PublicReadOnly) && !acl.users.is_empty() {
373            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
374        }
375        if acl.mode == mode {
376            return Ok(());
377        }
378        acl.mode = mode;
379        drop(acl);
380
381        for conn in self.state.active_connections.live().await {
382            conn.close_trees_for_share(share_name).await;
383        }
384        Ok(())
385    }
386}
387
388fn validate_user_name(name: &str) -> Result<(), ConfigError> {
389    if name.is_empty() {
390        return Err(ConfigError::EmptyUserName);
391    }
392    if name.eq_ignore_ascii_case("anonymous") {
393        return Err(ConfigError::ReservedUserName(name.to_string()));
394    }
395    Ok(())
396}
397
398fn validate_share_name(name: &str) -> Result<(), ConfigError> {
399    if name.eq_ignore_ascii_case("IPC$") {
400        return Err(ConfigError::ReservedShareName(name.to_string()));
401    }
402    Ok(())
403}
404
405// ---------------------------------------------------------------------------
406// SmbServer
407// ---------------------------------------------------------------------------
408
409/// A built but not-yet-running SMB server.
410///
411/// Use `serve()` to bind the configured listener and run until shutdown.
412pub struct SmbServer {
413    state: Arc<ServerState>,
414    /// The listener is bound lazily inside `serve()` so we can return a
415    /// useful `local_addr` only after binding. Pre-bind helpers: `serve` is
416    /// the only path that opens the socket.
417    bound: tokio::sync::Mutex<Option<TcpListener>>,
418    /// Resolved local address once `bind_local()` has been called. Tests
419    /// expect to ask for the address before serving (port 0 case).
420    local_addr: tokio::sync::Mutex<Option<SocketAddr>>,
421}
422
423impl SmbServer {
424    pub fn builder() -> SmbServerBuilder {
425        SmbServerBuilder::default()
426    }
427
428    pub(crate) fn from_state(state: ServerState) -> Self {
429        Self {
430            state: Arc::new(state),
431            bound: tokio::sync::Mutex::new(None),
432            local_addr: tokio::sync::Mutex::new(None),
433        }
434    }
435
436    pub fn config_handle(&self) -> ConfigHandle {
437        ConfigHandle {
438            state: self.state.clone(),
439        }
440    }
441
442    /// Bind the configured listen address without yet entering the accept
443    /// loop. Required for tests that need the actual port (e.g. when the
444    /// builder used port 0).
445    pub async fn bind(&self) -> io::Result<SocketAddr> {
446        let mut bound = self.bound.lock().await;
447        if let Some(l) = bound.as_ref() {
448            return l.local_addr();
449        }
450        let listener = TcpListener::bind(self.state.config.listen_addr).await?;
451        let addr = listener.local_addr()?;
452        *bound = Some(listener);
453        *self.local_addr.lock().await = Some(addr);
454        Ok(addr)
455    }
456
457    /// Returns the actual bound address. `None` if `bind()`/`serve()` have
458    /// not yet been called.
459    pub async fn local_addr(&self) -> Option<SocketAddr> {
460        *self.local_addr.lock().await
461    }
462
463    /// Configured listen address (the *intended* address; may be `0.0.0.0:0`
464    /// before binding).
465    pub fn configured_addr(&self) -> SocketAddr {
466        self.state.config.listen_addr
467    }
468
469    /// Initiate a graceful shutdown. Stops the accept loop and lets in-flight
470    /// connection tasks complete.
471    pub fn shutdown(&self) {
472        self.state.shutting_down.store(true, Ordering::Release);
473        self.state.shutdown.notify_waiters();
474    }
475
476    /// Returns a clonable handle that can request shutdown after `serve()`
477    /// has consumed the `SmbServer` value.
478    pub fn shutdown_handle(&self) -> ShutdownHandle {
479        ShutdownHandle {
480            shutdown: self.state.shutdown.clone(),
481            shutting_down: self.state.shutting_down.clone(),
482        }
483    }
484
485    /// Run the accept loop until `shutdown()` is called.
486    pub async fn serve(self) -> io::Result<()> {
487        // Ensure the listener is bound. (The user may also have called
488        // `bind()` to pre-extract `local_addr()` for a test.)
489        if self.bound.lock().await.is_none() {
490            self.bind().await?;
491        }
492        let listener = self
493            .bound
494            .lock()
495            .await
496            .take()
497            .expect("listener bound above");
498        let local = listener.local_addr().ok();
499        let span = info_span!("smb_server", listen = ?local);
500        async move {
501            info!("server starting");
502            let state = self.state.clone();
503            let shutdown = state.shutdown.clone();
504            let shutting_down = state.shutting_down.clone();
505
506            loop {
507                tokio::select! {
508                    biased;
509                    _ = shutdown.notified() => {
510                        info!("shutdown requested; stopping accept loop");
511                        break;
512                    }
513                    accept = listener.accept() => {
514                        match accept {
515                            Ok((stream, peer)) => {
516                                if shutting_down.load(Ordering::Acquire) {
517                                    drop(stream);
518                                    break;
519                                }
520                                let server_state = state.clone();
521                                let span = info_span!("conn", peer = %peer);
522                                tokio::spawn(async move {
523                                    if let Err(e) = connection_loop(stream, server_state).await {
524                                        error!(error = %e, "connection loop exited with error");
525                                    }
526                                }.instrument(span));
527                            }
528                            Err(e) => {
529                                error!(error = %e, "accept failed");
530                                if shutting_down.load(Ordering::Acquire) {
531                                    break;
532                                }
533                            }
534                        }
535                    }
536                }
537            }
538            info!("server stopped");
539            Ok::<(), io::Error>(())
540        }
541        .instrument(span)
542        .await
543    }
544
545    /// Access shared state for in-crate tests/integrations.
546    #[doc(hidden)]
547    pub fn state(&self) -> Arc<ServerState> {
548        self.state.clone()
549    }
550}
551
552/// Cheaply-clonable shutdown handle. Outlives `SmbServer::serve` consuming
553/// the server.
554#[derive(Clone)]
555pub struct ShutdownHandle {
556    shutdown: Arc<Notify>,
557    shutting_down: Arc<AtomicBool>,
558}
559
560impl ShutdownHandle {
561    /// Request a graceful shutdown.
562    pub fn shutdown(&self) {
563        self.shutting_down.store(true, Ordering::Release);
564        self.shutdown.notify_waiters();
565    }
566}