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    pub(crate) encrypt_data: bool,
52    pub(crate) leases: bool,
53    pub(crate) durable_handles: bool,
54    pub(crate) change_notify: bool,
55    pub(crate) listed: bool,
56    pub(crate) remark: String,
57}
58
59impl Share {
60    /// Build a new share with the given name and backend.
61    pub fn new(name: impl Into<String>, backend: impl ShareBackend) -> Self {
62        Self {
63            name: name.into(),
64            backend: Arc::new(backend),
65            mode: ShareMode::AuthenticatedOnly,
66            users: HashMap::new(),
67            encrypt_data: false,
68            leases: true,
69            durable_handles: true,
70            change_notify: true,
71            listed: true,
72            remark: String::new(),
73        }
74    }
75
76    /// Anonymous + authenticated read+write.
77    pub fn public(mut self) -> Self {
78        self.mode = ShareMode::Public;
79        self
80    }
81
82    /// Anonymous + authenticated read-only.
83    pub fn public_read_only(mut self) -> Self {
84        self.mode = ShareMode::PublicReadOnly;
85        self
86    }
87
88    /// Grant `access` to the given (already-registered) user. Multiple calls
89    /// accumulate.
90    pub fn user(mut self, name: impl Into<String>, access: Access) -> Self {
91        self.users.insert(name.into(), access);
92        self
93    }
94
95    /// Encrypt all traffic to this share. SMB 3.x clients that cannot
96    /// encrypt, SMB 2.x clients and anonymous sessions are refused at
97    /// TREE_CONNECT unless `SmbServerBuilder::reject_unencrypted_access` is
98    /// turned off.
99    pub fn encrypt_data(mut self) -> Self {
100        self.encrypt_data = true;
101        self
102    }
103
104    /// Grant read, handle and write caching leases on this share's files. A
105    /// client holding one caches what it reads, keeps files open after its
106    /// applications close them, and caches what it writes while every other
107    /// open of the file holds the same lease or is attribute-only.
108    ///
109    /// Opens on the share that do not hold the lease, from another client
110    /// or from the same client under another lease key or none, break it:
111    /// the client writes back and stops caching writes before such an
112    /// open, drops cached data before a write, a size change, a byte-range
113    /// lock or an overwrite through it, and closes the handles it keeps
114    /// before an open they block, a rename or delete of the file, a rename
115    /// over it, or a rename of a directory above it. Attribute-only opens
116    /// and opens holding the same lease break nothing. An open or rename
117    /// that needs the client to write back or close first waits until the
118    /// client acknowledges the break or closes, or until the break times
119    /// out 35 seconds after the server sent it; a byte-range lock is refused
120    /// instead until the client has written back. On by default.
121    ///
122    /// Changes made outside the server, or through another share over the
123    /// same directory, break no lease: clients keep serving the old data.
124    /// Turn leases off for such a share.
125    pub fn leases(mut self, enabled: bool) -> Self {
126        self.leases = enabled;
127        self
128    }
129
130    /// Keep a client's open files for a while after its connection drops or
131    /// it logs off, with their share modes, byte-range locks and leases, so
132    /// the client can take them back when it reconnects. Only files opened
133    /// with a durable handle request and a lease that caches handles are
134    /// kept, so this does nothing when leases are off. The backend handle
135    /// stays open for [`SmbServerBuilder::durable_handle_timeout`], or the
136    /// time a version 2 request was granted, or until an open, write, size change, byte-range lock, rename or
137    /// delete through an open that does not hold the lease needs what the
138    /// lease caches, which closes the file at once. The same user, from the
139    /// same client, on this share, takes a kept file back with a durable
140    /// handle reconnect that names the file and its lease, and for a version
141    /// 2 open its CreateGuid. Another user gets STATUS_ACCESS_DENIED;
142    /// another client, share, lease or CreateGuid gets
143    /// STATUS_OBJECT_NAME_NOT_FOUND. A kept file whose rights exceed what
144    /// the user's tree on the share grants at the reconnect is closed
145    /// instead. Version 1 and version 2 requests are both served; the
146    /// PERSISTENT flag is ignored. On by default.
147    pub fn durable_handles(mut self, enabled: bool) -> Self {
148        self.durable_handles = enabled;
149        self
150    }
151
152    /// Answer change notification requests: a client watching a folder, as
153    /// Explorer and Finder do for an open window, hears when a file or
154    /// folder in it is created, deleted, renamed, written, truncated or
155    /// overwritten, or has its attributes or times set, through any
156    /// connection to this share. A write is reported when the open that
157    /// wrote it closes. Changes made outside the server, or through another
158    /// share over the same directory, are reported only by a backend that
159    /// watches for them: `LocalFsBackend` does on Linux, for the entries
160    /// directly in a watched folder. When off, such requests fail with
161    /// STATUS_NOT_SUPPORTED. On by default.
162    pub fn change_notify(mut self, enabled: bool) -> Self {
163        self.change_notify = enabled;
164        self
165    }
166
167    /// Whether the share appears when clients list the server's shares.
168    /// An unlisted share is still reachable by name, and a client that may
169    /// connect to it can still look it up by name, so this is not access
170    /// control. Clients hide shares whose name ends in `$` from ordinary
171    /// lists; `net view /all` and `smbclient -L` show them. On by default.
172    pub fn listed(mut self, listed: bool) -> Self {
173        self.listed = listed;
174        self
175    }
176
177    /// Text shown next to the share in share lists: the Comment column of
178    /// Explorer and `smbclient -L`, the Remark column of `net view`. At most
179    /// 1024 UTF-16 code units, without NUL. Empty by default.
180    pub fn remark(mut self, remark: impl Into<String>) -> Self {
181        self.remark = remark.into();
182        self
183    }
184}
185
186/// Longest share remark, in UTF-16 code units.
187const MAX_REMARK_UNITS: usize = 1024;
188
189/// Whether `remark` can be sent as a share's remark: no NUL, and at most
190/// [`MAX_REMARK_UNITS`] UTF-16 code units.
191pub(crate) fn valid_remark(remark: &str) -> bool {
192    !remark.contains('\0') && remark.encode_utf16().count() <= MAX_REMARK_UNITS
193}
194
195// ---------------------------------------------------------------------------
196// BuildError
197// ---------------------------------------------------------------------------
198
199/// Errors raised by `SmbServerBuilder::build`.
200#[derive(Debug, Error)]
201pub enum BuildError {
202    #[error("listen address must be set")]
203    MissingListenAddr,
204    #[error("share `{0}` is declared more than once")]
205    DuplicateShare(String),
206    #[error("share `{0}` mixes .public()/.public_read_only() with explicit .user(...) entries")]
207    PublicMixedWithUsers(String),
208    #[error("share `{share}` references unknown user `{user}`")]
209    UnknownUser { share: String, user: String },
210    #[error("user name `{0}` is reserved (use .public()/.public_read_only() for anonymous)")]
211    ReservedUserName(String),
212    #[error("user name must be non-empty")]
213    EmptyUserName,
214    #[error("share name `{0}` is reserved")]
215    ReservedShareName(String),
216    #[error("share name `{0}` must be non-empty and contain no `\\`, `/` or NUL")]
217    InvalidShareName(String),
218    #[error("remark of share `{0}` must hold no NUL and at most 1024 UTF-16 code units")]
219    InvalidShareRemark(String),
220    #[error("`{setting}` must be {expected}")]
221    OutOfRange {
222        setting: &'static str,
223        expected: &'static str,
224    },
225}
226
227/// Why a share name cannot be configured.
228pub(crate) enum ShareNameError {
229    /// IPC$, which the server provides itself.
230    Reserved,
231    /// Empty, or contains `\`, `/` or NUL, so no UNC path reaches it.
232    Invalid,
233}
234
235/// Checks a share name for [`SmbServerBuilder::build`] and
236/// `ConfigHandle`.
237pub(crate) fn check_share_name(name: &str) -> Result<(), ShareNameError> {
238    if name.eq_ignore_ascii_case("IPC$") {
239        return Err(ShareNameError::Reserved);
240    }
241    if name.is_empty() || name.contains(['\\', '/', '\0']) {
242        return Err(ShareNameError::Invalid);
243    }
244    Ok(())
245}
246
247// ---------------------------------------------------------------------------
248// SmbServerBuilder
249// ---------------------------------------------------------------------------
250
251/// Builder for `SmbServer`. See `SmbServer::builder`.
252pub struct SmbServerBuilder {
253    listen_addr: Option<SocketAddr>,
254    users: HashMap<String, String>, // name -> password
255    user_order: Vec<String>,
256    shares: Vec<Share>,
257    netbios_name: Option<String>,
258    max_read_size: u32,
259    max_write_size: u32,
260    server_guid: Option<Uuid>,
261    limits: Limits,
262    auth: crate::auth_policy::AuthSettings,
263    max_opens_per_connection: usize,
264    max_locks_per_open: usize,
265    share_listing: bool,
266}
267
268impl Default for SmbServerBuilder {
269    fn default() -> Self {
270        Self::new()
271    }
272}
273
274impl SmbServerBuilder {
275    pub(crate) fn new() -> Self {
276        Self {
277            listen_addr: None,
278            users: HashMap::new(),
279            user_order: Vec::new(),
280            shares: Vec::new(),
281            netbios_name: None,
282            max_read_size: 1024 * 1024,
283            max_write_size: 1024 * 1024,
284            server_guid: None,
285            limits: Limits::default(),
286            auth: crate::auth_policy::AuthSettings::default(),
287            max_opens_per_connection: crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
288            max_locks_per_open: crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
289            share_listing: true,
290        }
291    }
292
293    pub fn listen(mut self, addr: SocketAddr) -> Self {
294        self.listen_addr = Some(addr);
295        self
296    }
297
298    pub fn user(mut self, name: impl Into<String>, password: impl Into<String>) -> Self {
299        let n = name.into();
300        if !self.users.contains_key(&n) {
301            self.user_order.push(n.clone());
302        }
303        self.users.insert(n, password.into());
304        self
305    }
306
307    pub fn share(mut self, share: Share) -> Self {
308        self.shares.push(share);
309        self
310    }
311
312    pub fn netbios_name(mut self, name: impl Into<String>) -> Self {
313        self.netbios_name = Some(name.into());
314        self
315    }
316
317    /// Require every authenticated session to sign its requests, and set
318    /// SMB2_NEGOTIATE_SIGNING_REQUIRED in the NEGOTIATE response. Anonymous
319    /// sessions have no key and stay unsigned. Off by default; a client can
320    /// still require signing for its own sessions.
321    pub fn require_signing(mut self, required: bool) -> Self {
322        self.auth.require_signing = required;
323        self
324    }
325
326    /// Encrypt every authenticated session on a connection that negotiated
327    /// a cipher. While `reject_unencrypted_access` is on, clients that
328    /// cannot encrypt get no session, and anonymous sessions get no tree.
329    /// Off by default; with it off, a client that sends encrypted requests
330    /// gets encrypted replies, and `Share::encrypt_data` turns encryption
331    /// on for one share.
332    pub fn encrypt_data(mut self, encrypt: bool) -> Self {
333        self.auth.encrypt_data = encrypt;
334        self
335    }
336
337    /// Whether a session or share that must be encrypted refuses clients
338    /// that cannot encrypt: SMB 2.x, SMB 3.0 and 3.0.2 without the
339    /// encryption capability, SMB 3.1.1 without a common cipher, and
340    /// anonymous sessions. On SMB 3.0 and 3.0.2 it also refuses unencrypted
341    /// requests from clients that can encrypt; SMB 3.1.1 always refuses
342    /// them. On by default. Turned off, clients that cannot encrypt are
343    /// served unencrypted.
344    pub fn reject_unencrypted_access(mut self, reject: bool) -> Self {
345        self.auth.reject_unencrypted_access = reject;
346        self
347    }
348
349    /// Most sessions one connection may hold. SESSION_SETUP past the limit
350    /// fails with STATUS_INSUFFICIENT_RESOURCES. Default 64.
351    pub fn max_sessions_per_connection(mut self, sessions: usize) -> Self {
352        self.auth.max_sessions_per_connection = sessions;
353        self
354    }
355
356    /// Most tree connects one session may hold. TREE_CONNECT past the limit
357    /// fails with STATUS_INSUFFICIENT_RESOURCES. Default 128.
358    pub fn max_trees_per_session(mut self, trees: usize) -> Self {
359        self.auth.max_trees_per_session = trees;
360        self
361    }
362
363    /// Failed-logon throttle. After `max_failures` failed logons for one
364    /// user name, each within `lockout` of the one before, logons with that
365    /// name fail with STATUS_ACCOUNT_LOCKED_OUT until `lockout` has passed
366    /// since the last failure. One client address is locked out the same
367    /// way after ten times `max_failures` failed logons, whatever names they
368    /// used. A connection is closed after `max_failures` failed logons.
369    /// Unknown names are tracked the same way as configured ones.
370    /// `max_failures` 0 turns the throttle off. Default 10 failures and 60
371    /// seconds.
372    pub fn logon_throttle(mut self, max_failures: u32, lockout: Duration) -> Self {
373        self.auth.max_logon_failures = max_failures;
374        self.auth.lockout = lockout;
375        self
376    }
377
378    pub fn max_read_size(mut self, bytes: u32) -> Self {
379        self.max_read_size = bytes;
380        self
381    }
382
383    pub fn max_write_size(mut self, bytes: u32) -> Self {
384        self.max_write_size = bytes;
385        self
386    }
387
388    /// Override the random per-process server GUID. Mostly useful in tests.
389    pub fn server_guid(mut self, guid: Uuid) -> Self {
390        self.server_guid = Some(guid);
391        self
392    }
393
394    /// Most connections served at once, counting every client together;
395    /// per-host limits belong in the firewall. A connection accepted beyond
396    /// the limit is closed straight away. Defaults to 1024.
397    pub fn max_connections(mut self, connections: usize) -> Self {
398        self.limits.max_connections = connections;
399        self
400    }
401
402    /// Time a new connection has to establish a session, and each
403    /// SESSION_SETUP exchange has to finish. A connection still without a
404    /// session at the deadline is closed, and an unfinished exchange is
405    /// dropped. Defaults to 30 seconds.
406    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
407        self.limits.handshake_timeout = timeout;
408        self
409    }
410
411    /// Closes a connection that has sent no request for this long and has no
412    /// open files. Defaults to 15 minutes.
413    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
414        self.limits.idle_timeout = timeout;
415        self
416    }
417
418    /// Time allowed to receive the rest of a request once its first bytes
419    /// have arrived, and to send one response. The connection closes when
420    /// either takes longer. Defaults to 60 seconds.
421    pub fn io_timeout(mut self, timeout: Duration) -> Self {
422        self.limits.io_timeout = timeout;
423        self
424    }
425
426    /// Idle time before TCP keepalive probes start on accepted connections,
427    /// or `None` to leave keepalive off. Defaults to 60 seconds.
428    pub fn tcp_keepalive(mut self, idle: Option<Duration>) -> Self {
429        self.limits.tcp_keepalive = idle;
430        self
431    }
432
433    /// Most files and named pipes one connection may hold open at once. A
434    /// CREATE past the limit fails with STATUS_INSUFFICIENT_RESOURCES.
435    /// Named pipes are also limited to 16 per connection. Defaults to
436    /// [`DEFAULT_MAX_OPENS_PER_CONNECTION`](crate::DEFAULT_MAX_OPENS_PER_CONNECTION).
437    /// [`ConfigHandle::set_max_opens_per_connection`](crate::ConfigHandle::set_max_opens_per_connection)
438    /// changes it at run time.
439    pub fn max_opens_per_connection(mut self, opens: usize) -> Self {
440        self.max_opens_per_connection = opens;
441        self
442    }
443
444    /// Answer clients that list the server's shares: Explorer and `net
445    /// view` on Windows, the Finder and `smbutil view` on macOS, `smbclient
446    /// -L` and file managers on Linux. A client sees the shares its session
447    /// may connect to, the public ones for an anonymous session, and IPC$,
448    /// in the order the shares were added; a share whose traffic is
449    /// encrypted is left out for a session that cannot encrypt. Shares left
450    /// out with [`Share::listed`] are not in the list. Clients list shares through the
451    /// `srvsvc` named pipe on IPC$; one connection may hold 16 named pipes
452    /// at once. On by default; turned off, IPC$ opens no pipe and clients
453    /// get no list.
454    pub fn share_listing(mut self, enabled: bool) -> Self {
455        self.share_listing = enabled;
456        self
457    }
458
459    /// Most byte-range locks one open may hold at once. A LOCK past the
460    /// limit fails with STATUS_INSUFFICIENT_RESOURCES. Defaults to
461    /// [`DEFAULT_MAX_LOCKS_PER_OPEN`](crate::DEFAULT_MAX_LOCKS_PER_OPEN).
462    pub fn max_locks_per_open(mut self, locks: usize) -> Self {
463        self.max_locks_per_open = locks;
464        self
465    }
466
467    /// How long the server keeps an open file for a client whose
468    /// connection dropped or that logged off; see
469    /// [`Share::durable_handles`]. A client that asks for a time in a
470    /// version 2 durable handle request gets it, up to this timeout or 5
471    /// minutes, whichever is longer. Must be between 1 millisecond and 49
472    /// days. Defaults to
473    /// [`DEFAULT_DURABLE_HANDLE_TIMEOUT`](crate::DEFAULT_DURABLE_HANDLE_TIMEOUT),
474    /// 2 minutes.
475    pub fn durable_handle_timeout(mut self, timeout: Duration) -> Self {
476        self.limits.durable_handle_timeout = timeout;
477        self
478    }
479
480    /// Most open files the server keeps for clients whose connection
481    /// dropped or that logged off, counting every client together; one user
482    /// gets at most a quarter of them, rounded up. Past the limit, such a
483    /// client's files are closed. Defaults to
484    /// [`DEFAULT_MAX_DISCONNECTED_OPENS`](crate::DEFAULT_MAX_DISCONNECTED_OPENS),
485    /// 4096.
486    pub fn max_disconnected_opens(mut self, opens: usize) -> Self {
487        self.limits.max_disconnected_opens = opens;
488        self
489    }
490
491    pub fn build(self) -> Result<SmbServer, BuildError> {
492        let limits = &self.limits;
493        if limits.max_connections == 0 {
494            return Err(BuildError::OutOfRange {
495                setting: "max_connections",
496                expected: "at least 1",
497            });
498        }
499        for (setting, size) in [
500            ("max_read_size", self.max_read_size),
501            ("max_write_size", self.max_write_size),
502        ] {
503            if !(MIN_IO_SIZE..=MAX_IO_SIZE).contains(&size) {
504                return Err(BuildError::OutOfRange {
505                    setting,
506                    expected: "between 65536 and 8388608 bytes",
507                });
508            }
509        }
510        for (setting, timeout) in [
511            ("handshake_timeout", Some(limits.handshake_timeout)),
512            ("idle_timeout", Some(limits.idle_timeout)),
513            ("io_timeout", Some(limits.io_timeout)),
514            ("tcp_keepalive", limits.tcp_keepalive),
515        ] {
516            if timeout == Some(Duration::ZERO) {
517                return Err(BuildError::OutOfRange {
518                    setting,
519                    expected: "greater than zero",
520                });
521            }
522        }
523        if !(MIN_DURABLE_HANDLE_TIMEOUT..=MAX_DURABLE_HANDLE_TIMEOUT)
524            .contains(&limits.durable_handle_timeout)
525        {
526            return Err(BuildError::OutOfRange {
527                setting: "durable_handle_timeout",
528                expected: "between 1 millisecond and 49 days",
529            });
530        }
531
532        for name in &self.user_order {
533            if name.is_empty() {
534                return Err(BuildError::EmptyUserName);
535            }
536            if name.eq_ignore_ascii_case("anonymous") {
537                return Err(BuildError::ReservedUserName(name.clone()));
538            }
539        }
540
541        let mut seen_names = std::collections::HashSet::new();
542        for share in &self.shares {
543            match check_share_name(&share.name) {
544                Err(ShareNameError::Reserved) => {
545                    return Err(BuildError::ReservedShareName(share.name.clone()));
546                }
547                Err(ShareNameError::Invalid) => {
548                    return Err(BuildError::InvalidShareName(share.name.clone()));
549                }
550                Ok(()) => {}
551            }
552            if !valid_remark(&share.remark) {
553                return Err(BuildError::InvalidShareRemark(share.name.clone()));
554            }
555            if !seen_names.insert(share.name.to_ascii_lowercase()) {
556                return Err(BuildError::DuplicateShare(share.name.clone()));
557            }
558            let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
559            if is_public && !share.users.is_empty() {
560                return Err(BuildError::PublicMixedWithUsers(share.name.clone()));
561            }
562            // Each per-share user must exist in the global user table.
563            for u in share.users.keys() {
564                if !self.users.contains_key(u) {
565                    return Err(BuildError::UnknownUser {
566                        share: share.name.clone(),
567                        user: u.clone(),
568                    });
569                }
570            }
571        }
572
573        let listen = self.listen_addr.ok_or(BuildError::MissingListenAddr)?;
574
575        let netbios = self.netbios_name.unwrap_or_else(default_netbios_name);
576
577        let mut share_bindings: Vec<Arc<ShareBindings>> = Vec::with_capacity(self.shares.len());
578        for s in self.shares {
579            share_bindings.push(ShareBindings::from_share(s));
580        }
581
582        // Store NT hashes only; plaintext passwords are dropped.
583        let mut user_table = HashMap::new();
584        for name in &self.user_order {
585            let pw = &self.users[name];
586            let creds = crate::proto::auth::ntlm::UserCreds::from_password(pw);
587            user_table.insert(name.clone(), creds);
588        }
589
590        let server_guid = self.server_guid.unwrap_or_else(Uuid::new_v4);
591
592        let cfg = ServerConfig {
593            listen_addr: listen,
594            netbios_name: netbios,
595            max_read_size: self.max_read_size,
596            max_write_size: self.max_write_size,
597            server_guid,
598            limits: self.limits,
599            share_listing: self.share_listing,
600        };
601        let users = ServerUsers {
602            table: tokio::sync::RwLock::new(user_table),
603        };
604
605        let state = ServerState::new(cfg, users, share_bindings);
606        let state = state.with_auth(self.auth);
607        state
608            .max_opens_per_connection
609            .store(self.max_opens_per_connection, Ordering::Relaxed);
610        state
611            .max_locks_per_open
612            .store(self.max_locks_per_open, Ordering::Relaxed);
613        Ok(SmbServer::from_state(state))
614    }
615}
616
617/// Shortest and longest accepted `durable_handle_timeout`. Version 2
618/// responses carry the timeout in whole milliseconds, in 32 bits.
619const MIN_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_millis(1);
620const MAX_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_secs(49 * 24 * 60 * 60);
621
622/// Smallest and largest accepted `max_read_size` and `max_write_size`.
623const MIN_IO_SIZE: u32 = 64 * 1024;
624const MAX_IO_SIZE: u32 = 8 * 1024 * 1024;
625
626/// The host name's first label, uppercased and cut to the 15 characters a
627/// NetBIOS name holds, or `SMBSERVER` when the host name is unknown.
628fn default_netbios_name() -> String {
629    let host = host_name().unwrap_or_default();
630    let label: String = host
631        .split('.')
632        .next()
633        .unwrap_or("")
634        .chars()
635        .take(15)
636        .collect();
637    if label.is_empty() {
638        "SMBSERVER".to_string()
639    } else {
640        label.to_uppercase()
641    }
642}
643
644#[cfg(unix)]
645fn host_name() -> Option<String> {
646    let mut buf = [0u8; 256];
647    // SAFETY: `buf` is valid for writes of `buf.len()` bytes.
648    let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };
649    if rc != 0 {
650        return None;
651    }
652    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
653    String::from_utf8(buf[..end].to_vec()).ok()
654}
655
656#[cfg(windows)]
657fn host_name() -> Option<String> {
658    std::env::var("COMPUTERNAME").ok()
659}
660
661#[cfg(not(any(unix, windows)))]
662fn host_name() -> Option<String> {
663    None
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669    use crate::tests::memfs::MemFsBackend;
670
671    fn build_with_share(name: &str) -> Result<SmbServer, BuildError> {
672        SmbServer::builder()
673            .listen("127.0.0.1:0".parse().unwrap())
674            .share(Share::new(name, MemFsBackend::new()).public())
675            .build()
676    }
677
678    #[test]
679    fn reserved_and_unreachable_share_names_are_rejected() {
680        for name in ["IPC$", "ipc$"] {
681            assert!(matches!(
682                build_with_share(name),
683                Err(BuildError::ReservedShareName(n)) if n == name
684            ));
685        }
686        for name in ["", "a\\b", "a/b", "\\share", "a\0b"] {
687            assert!(matches!(
688                build_with_share(name),
689                Err(BuildError::InvalidShareName(n)) if n == name
690            ));
691        }
692        assert!(build_with_share("share$").is_ok());
693    }
694
695    #[test]
696    fn remarks_hold_no_nul_and_at_most_1024_units() {
697        let build = |remark: String| {
698            SmbServer::builder()
699                .listen("127.0.0.1:0".parse().unwrap())
700                .share(Share::new("s", MemFsBackend::new()).remark(remark).public())
701                .build()
702        };
703        // U+1F9A4 takes two UTF-16 code units.
704        for remark in ["a".repeat(1024), "\u{1F9A4}".repeat(512)] {
705            assert!(build(remark).is_ok());
706        }
707        for remark in [
708            "a".repeat(1025),
709            "\u{1F9A4}".repeat(513),
710            "a\0b".to_string(),
711        ] {
712            assert!(matches!(
713                build(remark),
714                Err(BuildError::InvalidShareRemark(n)) if n == "s"
715            ));
716        }
717    }
718
719    #[test]
720    fn io_sizes_must_fit_a_frame() {
721        let build = |read: u32, write: u32| {
722            SmbServer::builder()
723                .listen("127.0.0.1:0".parse().unwrap())
724                .max_read_size(read)
725                .max_write_size(write)
726                .build()
727        };
728        const MIB: u32 = 1024 * 1024;
729        assert!(build(64 * 1024, 8 * MIB).is_ok());
730        for (read, write, setting) in [
731            (64 * 1024 - 1, MIB, "max_read_size"),
732            (8 * MIB + 1, MIB, "max_read_size"),
733            (MIB, 0, "max_write_size"),
734            (MIB, 16 * MIB, "max_write_size"),
735        ] {
736            assert!(matches!(
737                build(read, write),
738                Err(BuildError::OutOfRange { setting: s, .. }) if s == setting
739            ));
740        }
741    }
742
743    #[test]
744    fn the_durable_handle_timeout_is_bounded() {
745        let build = |timeout| {
746            SmbServer::builder()
747                .listen("127.0.0.1:0".parse().unwrap())
748                .durable_handle_timeout(timeout)
749                .build()
750        };
751        for timeout in [
752            Duration::ZERO,
753            Duration::from_micros(999),
754            MAX_DURABLE_HANDLE_TIMEOUT + Duration::from_nanos(1),
755            Duration::MAX,
756        ] {
757            assert!(
758                matches!(
759                    build(timeout),
760                    Err(BuildError::OutOfRange {
761                        setting: "durable_handle_timeout",
762                        ..
763                    })
764                ),
765                "{timeout:?}"
766            );
767        }
768        for timeout in [MIN_DURABLE_HANDLE_TIMEOUT, MAX_DURABLE_HANDLE_TIMEOUT] {
769            assert!(build(timeout).is_ok(), "{timeout:?}");
770        }
771    }
772
773    #[cfg(target_os = "linux")]
774    #[test]
775    fn default_netbios_name_comes_from_the_host_name() {
776        let host = std::fs::read_to_string("/proc/sys/kernel/hostname").expect("hostname");
777        let label = host.trim().split('.').next().expect("label");
778        let expected: String = label.chars().take(15).collect::<String>().to_uppercase();
779        let server = SmbServer::builder()
780            .listen("127.0.0.1:0".parse().unwrap())
781            .build()
782            .expect("build");
783        assert_eq!(server.state().config.netbios_name, expected);
784    }
785}