Skip to main content

smb_server/
builder.rs

1//! Public builder API for `SmbServer` and `Share`.
2
3use std::collections::HashMap;
4use std::net::SocketAddr;
5use std::sync::Arc;
6use std::sync::atomic::Ordering;
7use std::time::Duration;
8
9use thiserror::Error;
10use uuid::Uuid;
11
12use crate::backend::ShareBackend;
13use crate::conn::limits::Limits;
14use crate::server::{ServerConfig, ServerState, ServerUsers, ShareBindings, ShareMode, SmbServer};
15
16// ---------------------------------------------------------------------------
17// Access
18// ---------------------------------------------------------------------------
19
20/// Access level granted to a user on a share, or to anonymous on a public
21/// share.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Access {
24    Read,
25    ReadWrite,
26}
27
28impl Access {
29    pub fn allows_write(self) -> bool {
30        matches!(self, Access::ReadWrite)
31    }
32
33    pub fn clamp_to(self, cap: Access) -> Access {
34        match (self, cap) {
35            (Access::ReadWrite, Access::ReadWrite) => Access::ReadWrite,
36            _ => Access::Read,
37        }
38    }
39}
40
41// ---------------------------------------------------------------------------
42// Share
43// ---------------------------------------------------------------------------
44
45/// One share definition, attached to a single backend.
46pub struct Share {
47    pub(crate) name: String,
48    pub(crate) backend: Arc<dyn ShareBackend>,
49    pub(crate) mode: ShareMode,
50    pub(crate) users: HashMap<String, Access>,
51}
52
53impl Share {
54    /// Build a new share with the given name and backend.
55    pub fn new(name: impl Into<String>, backend: impl ShareBackend) -> Self {
56        Self {
57            name: name.into(),
58            backend: Arc::new(backend),
59            mode: ShareMode::AuthenticatedOnly,
60            users: HashMap::new(),
61        }
62    }
63
64    /// Anonymous + authenticated read+write.
65    pub fn public(mut self) -> Self {
66        self.mode = ShareMode::Public;
67        self
68    }
69
70    /// Anonymous + authenticated read-only.
71    pub fn public_read_only(mut self) -> Self {
72        self.mode = ShareMode::PublicReadOnly;
73        self
74    }
75
76    /// Grant `access` to the given (already-registered) user. Multiple calls
77    /// accumulate.
78    pub fn user(mut self, name: impl Into<String>, access: Access) -> Self {
79        self.users.insert(name.into(), access);
80        self
81    }
82}
83
84// ---------------------------------------------------------------------------
85// BuildError
86// ---------------------------------------------------------------------------
87
88/// Errors raised by `SmbServerBuilder::build`.
89#[derive(Debug, Error)]
90pub enum BuildError {
91    #[error("listen address must be set")]
92    MissingListenAddr,
93    #[error("share `{0}` is declared more than once")]
94    DuplicateShare(String),
95    #[error("share `{0}` mixes .public()/.public_read_only() with explicit .user(...) entries")]
96    PublicMixedWithUsers(String),
97    #[error("share `{share}` references unknown user `{user}`")]
98    UnknownUser { share: String, user: String },
99    #[error("user name `{0}` is reserved (use .public()/.public_read_only() for anonymous)")]
100    ReservedUserName(String),
101    #[error("user name must be non-empty")]
102    EmptyUserName,
103    #[error("share name `{0}` is reserved")]
104    ReservedShareName(String),
105    #[error("share name `{0}` must be non-empty and contain no `\\` or `/`")]
106    InvalidShareName(String),
107    #[error("`{setting}` must be {expected}")]
108    OutOfRange {
109        setting: &'static str,
110        expected: &'static str,
111    },
112}
113
114/// Why a share name cannot be configured.
115pub(crate) enum ShareNameError {
116    /// IPC$, which the server provides itself.
117    Reserved,
118    /// Empty, or contains `\` or `/`, so no UNC path reaches it.
119    Invalid,
120}
121
122/// Checks a share name for [`SmbServerBuilder::build`] and
123/// `ConfigHandle`.
124pub(crate) fn check_share_name(name: &str) -> Result<(), ShareNameError> {
125    if name.eq_ignore_ascii_case("IPC$") {
126        return Err(ShareNameError::Reserved);
127    }
128    if name.is_empty() || name.contains(['\\', '/']) {
129        return Err(ShareNameError::Invalid);
130    }
131    Ok(())
132}
133
134// ---------------------------------------------------------------------------
135// SmbServerBuilder
136// ---------------------------------------------------------------------------
137
138/// Builder for `SmbServer`. See `SmbServer::builder`.
139pub struct SmbServerBuilder {
140    listen_addr: Option<SocketAddr>,
141    users: HashMap<String, String>, // name -> password
142    user_order: Vec<String>,
143    shares: Vec<Share>,
144    netbios_name: Option<String>,
145    max_read_size: u32,
146    max_write_size: u32,
147    server_guid: Option<Uuid>,
148    limits: Limits,
149    auth: crate::auth_policy::AuthSettings,
150    max_opens_per_connection: usize,
151    max_locks_per_open: usize,
152}
153
154impl Default for SmbServerBuilder {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159
160impl SmbServerBuilder {
161    pub(crate) fn new() -> Self {
162        Self {
163            listen_addr: None,
164            users: HashMap::new(),
165            user_order: Vec::new(),
166            shares: Vec::new(),
167            netbios_name: None,
168            max_read_size: 1024 * 1024,
169            max_write_size: 1024 * 1024,
170            server_guid: None,
171            limits: Limits::default(),
172            auth: crate::auth_policy::AuthSettings::default(),
173            max_opens_per_connection: crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
174            max_locks_per_open: crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
175        }
176    }
177
178    pub fn listen(mut self, addr: SocketAddr) -> Self {
179        self.listen_addr = Some(addr);
180        self
181    }
182
183    pub fn user(mut self, name: impl Into<String>, password: impl Into<String>) -> Self {
184        let n = name.into();
185        if !self.users.contains_key(&n) {
186            self.user_order.push(n.clone());
187        }
188        self.users.insert(n, password.into());
189        self
190    }
191
192    pub fn share(mut self, share: Share) -> Self {
193        self.shares.push(share);
194        self
195    }
196
197    pub fn netbios_name(mut self, name: impl Into<String>) -> Self {
198        self.netbios_name = Some(name.into());
199        self
200    }
201
202    /// Require every authenticated session to sign its requests, and set
203    /// SMB2_NEGOTIATE_SIGNING_REQUIRED in the NEGOTIATE response. Anonymous
204    /// sessions have no key and stay unsigned. Off by default; a client can
205    /// still require signing for its own sessions.
206    pub fn require_signing(mut self, required: bool) -> Self {
207        self.auth.require_signing = required;
208        self
209    }
210
211    /// Most sessions one connection may hold. SESSION_SETUP past the limit
212    /// fails with STATUS_INSUFFICIENT_RESOURCES. Default 64.
213    pub fn max_sessions_per_connection(mut self, sessions: usize) -> Self {
214        self.auth.max_sessions_per_connection = sessions;
215        self
216    }
217
218    /// Most tree connects one session may hold. TREE_CONNECT past the limit
219    /// fails with STATUS_INSUFFICIENT_RESOURCES. Default 128.
220    pub fn max_trees_per_session(mut self, trees: usize) -> Self {
221        self.auth.max_trees_per_session = trees;
222        self
223    }
224
225    /// Failed-logon throttle. After `max_failures` failed logons for one
226    /// user name, each within `lockout` of the one before, logons with that
227    /// name fail with STATUS_ACCOUNT_LOCKED_OUT until `lockout` has passed
228    /// since the last failure. One client address is locked out the same
229    /// way after ten times `max_failures` failed logons, whatever names they
230    /// used. A connection is closed after `max_failures` failed logons.
231    /// Unknown names are tracked the same way as configured ones.
232    /// `max_failures` 0 turns the throttle off. Default 10 failures and 60
233    /// seconds.
234    pub fn logon_throttle(mut self, max_failures: u32, lockout: Duration) -> Self {
235        self.auth.max_logon_failures = max_failures;
236        self.auth.lockout = lockout;
237        self
238    }
239
240    pub fn max_read_size(mut self, bytes: u32) -> Self {
241        self.max_read_size = bytes;
242        self
243    }
244
245    pub fn max_write_size(mut self, bytes: u32) -> Self {
246        self.max_write_size = bytes;
247        self
248    }
249
250    /// Override the random per-process server GUID. Mostly useful in tests.
251    pub fn server_guid(mut self, guid: Uuid) -> Self {
252        self.server_guid = Some(guid);
253        self
254    }
255
256    /// Most connections served at once, counting every client together;
257    /// per-host limits belong in the firewall. A connection accepted beyond
258    /// the limit is closed straight away. Defaults to 1024.
259    pub fn max_connections(mut self, connections: usize) -> Self {
260        self.limits.max_connections = connections;
261        self
262    }
263
264    /// Time a new connection has to establish a session, and each
265    /// SESSION_SETUP exchange has to finish. A connection still without a
266    /// session at the deadline is closed, and an unfinished exchange is
267    /// dropped. Defaults to 30 seconds.
268    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
269        self.limits.handshake_timeout = timeout;
270        self
271    }
272
273    /// Closes a connection that has sent no request for this long and has no
274    /// open files. Defaults to 15 minutes.
275    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
276        self.limits.idle_timeout = timeout;
277        self
278    }
279
280    /// Time allowed to receive the rest of a request once its first bytes
281    /// have arrived, and to send one response. The connection closes when
282    /// either takes longer. Defaults to 60 seconds.
283    pub fn io_timeout(mut self, timeout: Duration) -> Self {
284        self.limits.io_timeout = timeout;
285        self
286    }
287
288    /// Idle time before TCP keepalive probes start on accepted connections,
289    /// or `None` to leave keepalive off. Defaults to 60 seconds.
290    pub fn tcp_keepalive(mut self, idle: Option<Duration>) -> Self {
291        self.limits.tcp_keepalive = idle;
292        self
293    }
294
295    /// Most files one connection may hold open at once. A CREATE past the
296    /// limit fails with STATUS_INSUFFICIENT_RESOURCES. Defaults to
297    /// [`DEFAULT_MAX_OPENS_PER_CONNECTION`](crate::DEFAULT_MAX_OPENS_PER_CONNECTION).
298    /// [`ConfigHandle::set_max_opens_per_connection`](crate::ConfigHandle::set_max_opens_per_connection)
299    /// changes it at run time.
300    pub fn max_opens_per_connection(mut self, opens: usize) -> Self {
301        self.max_opens_per_connection = opens;
302        self
303    }
304
305    /// Most byte-range locks one open may hold at once. A LOCK past the
306    /// limit fails with STATUS_INSUFFICIENT_RESOURCES. Defaults to
307    /// [`DEFAULT_MAX_LOCKS_PER_OPEN`](crate::DEFAULT_MAX_LOCKS_PER_OPEN).
308    pub fn max_locks_per_open(mut self, locks: usize) -> Self {
309        self.max_locks_per_open = locks;
310        self
311    }
312
313    pub fn build(self) -> Result<SmbServer, BuildError> {
314        let limits = &self.limits;
315        if limits.max_connections == 0 {
316            return Err(BuildError::OutOfRange {
317                setting: "max_connections",
318                expected: "at least 1",
319            });
320        }
321        for (setting, size) in [
322            ("max_read_size", self.max_read_size),
323            ("max_write_size", self.max_write_size),
324        ] {
325            if !(MIN_IO_SIZE..=MAX_IO_SIZE).contains(&size) {
326                return Err(BuildError::OutOfRange {
327                    setting,
328                    expected: "between 65536 and 8388608 bytes",
329                });
330            }
331        }
332        for (setting, timeout) in [
333            ("handshake_timeout", Some(limits.handshake_timeout)),
334            ("idle_timeout", Some(limits.idle_timeout)),
335            ("io_timeout", Some(limits.io_timeout)),
336            ("tcp_keepalive", limits.tcp_keepalive),
337        ] {
338            if timeout == Some(Duration::ZERO) {
339                return Err(BuildError::OutOfRange {
340                    setting,
341                    expected: "greater than zero",
342                });
343            }
344        }
345
346        for name in &self.user_order {
347            if name.is_empty() {
348                return Err(BuildError::EmptyUserName);
349            }
350            if name.eq_ignore_ascii_case("anonymous") {
351                return Err(BuildError::ReservedUserName(name.clone()));
352            }
353        }
354
355        let mut seen_names = std::collections::HashSet::new();
356        for share in &self.shares {
357            match check_share_name(&share.name) {
358                Err(ShareNameError::Reserved) => {
359                    return Err(BuildError::ReservedShareName(share.name.clone()));
360                }
361                Err(ShareNameError::Invalid) => {
362                    return Err(BuildError::InvalidShareName(share.name.clone()));
363                }
364                Ok(()) => {}
365            }
366            if !seen_names.insert(share.name.to_ascii_lowercase()) {
367                return Err(BuildError::DuplicateShare(share.name.clone()));
368            }
369            let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
370            if is_public && !share.users.is_empty() {
371                return Err(BuildError::PublicMixedWithUsers(share.name.clone()));
372            }
373            // Each per-share user must exist in the global user table.
374            for u in share.users.keys() {
375                if !self.users.contains_key(u) {
376                    return Err(BuildError::UnknownUser {
377                        share: share.name.clone(),
378                        user: u.clone(),
379                    });
380                }
381            }
382        }
383
384        let listen = self.listen_addr.ok_or(BuildError::MissingListenAddr)?;
385
386        let netbios = self.netbios_name.unwrap_or_else(default_netbios_name);
387
388        let mut share_bindings: Vec<Arc<ShareBindings>> = Vec::with_capacity(self.shares.len());
389        for s in self.shares {
390            share_bindings.push(ShareBindings::new(
391                s.name, s.backend, s.mode, s.users, false,
392            ));
393        }
394
395        // Store NT hashes only; plaintext passwords are dropped.
396        let mut user_table = HashMap::new();
397        for name in &self.user_order {
398            let pw = &self.users[name];
399            let creds = crate::proto::auth::ntlm::UserCreds::from_password(pw);
400            user_table.insert(name.clone(), creds);
401        }
402
403        let server_guid = self.server_guid.unwrap_or_else(Uuid::new_v4);
404
405        let cfg = ServerConfig {
406            listen_addr: listen,
407            netbios_name: netbios,
408            max_read_size: self.max_read_size,
409            max_write_size: self.max_write_size,
410            server_guid,
411            limits: self.limits,
412        };
413        let users = ServerUsers {
414            table: tokio::sync::RwLock::new(user_table),
415        };
416
417        let state = ServerState::new(cfg, users, share_bindings);
418        let state = state.with_auth(self.auth);
419        state
420            .max_opens_per_connection
421            .store(self.max_opens_per_connection, Ordering::Relaxed);
422        state
423            .max_locks_per_open
424            .store(self.max_locks_per_open, Ordering::Relaxed);
425        Ok(SmbServer::from_state(state))
426    }
427}
428
429/// Smallest and largest accepted `max_read_size` and `max_write_size`.
430const MIN_IO_SIZE: u32 = 64 * 1024;
431const MAX_IO_SIZE: u32 = 8 * 1024 * 1024;
432
433/// The host name's first label, uppercased and cut to the 15 characters a
434/// NetBIOS name holds, or `SMBSERVER` when the host name is unknown.
435fn default_netbios_name() -> String {
436    let host = host_name().unwrap_or_default();
437    let label: String = host
438        .split('.')
439        .next()
440        .unwrap_or("")
441        .chars()
442        .take(15)
443        .collect();
444    if label.is_empty() {
445        "SMBSERVER".to_string()
446    } else {
447        label.to_uppercase()
448    }
449}
450
451#[cfg(unix)]
452fn host_name() -> Option<String> {
453    let mut buf = [0u8; 256];
454    // SAFETY: `buf` is valid for writes of `buf.len()` bytes.
455    let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };
456    if rc != 0 {
457        return None;
458    }
459    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
460    String::from_utf8(buf[..end].to_vec()).ok()
461}
462
463#[cfg(windows)]
464fn host_name() -> Option<String> {
465    std::env::var("COMPUTERNAME").ok()
466}
467
468#[cfg(not(any(unix, windows)))]
469fn host_name() -> Option<String> {
470    None
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476    use crate::tests::memfs::MemFsBackend;
477
478    fn build_with_share(name: &str) -> Result<SmbServer, BuildError> {
479        SmbServer::builder()
480            .listen("127.0.0.1:0".parse().unwrap())
481            .share(Share::new(name, MemFsBackend::new()).public())
482            .build()
483    }
484
485    #[test]
486    fn reserved_and_unreachable_share_names_are_rejected() {
487        for name in ["IPC$", "ipc$"] {
488            assert!(matches!(
489                build_with_share(name),
490                Err(BuildError::ReservedShareName(n)) if n == name
491            ));
492        }
493        for name in ["", "a\\b", "a/b", "\\share"] {
494            assert!(matches!(
495                build_with_share(name),
496                Err(BuildError::InvalidShareName(n)) if n == name
497            ));
498        }
499        assert!(build_with_share("share$").is_ok());
500    }
501
502    #[test]
503    fn io_sizes_must_fit_a_frame() {
504        let build = |read: u32, write: u32| {
505            SmbServer::builder()
506                .listen("127.0.0.1:0".parse().unwrap())
507                .max_read_size(read)
508                .max_write_size(write)
509                .build()
510        };
511        const MIB: u32 = 1024 * 1024;
512        assert!(build(64 * 1024, 8 * MIB).is_ok());
513        for (read, write, setting) in [
514            (64 * 1024 - 1, MIB, "max_read_size"),
515            (8 * MIB + 1, MIB, "max_read_size"),
516            (MIB, 0, "max_write_size"),
517            (MIB, 16 * MIB, "max_write_size"),
518        ] {
519            assert!(matches!(
520                build(read, write),
521                Err(BuildError::OutOfRange { setting: s, .. }) if s == setting
522            ));
523        }
524    }
525
526    #[cfg(target_os = "linux")]
527    #[test]
528    fn default_netbios_name_comes_from_the_host_name() {
529        let host = std::fs::read_to_string("/proc/sys/kernel/hostname").expect("hostname");
530        let label = host.trim().split('.').next().expect("label");
531        let expected: String = label.chars().take(15).collect::<String>().to_uppercase();
532        let server = SmbServer::builder()
533            .listen("127.0.0.1:0".parse().unwrap())
534            .build()
535            .expect("build");
536        assert_eq!(server.state().config.netbios_name, expected);
537    }
538}