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