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