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