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