1use 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#[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
41pub 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 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 pub fn public(mut self) -> Self {
78 self.mode = ShareMode::Public;
79 self
80 }
81
82 pub fn public_read_only(mut self) -> Self {
84 self.mode = ShareMode::PublicReadOnly;
85 self
86 }
87
88 pub fn user(mut self, name: impl Into<String>, access: Access) -> Self {
91 self.users.insert(name.into(), access);
92 self
93 }
94
95 pub fn encrypt_data(mut self) -> Self {
100 self.encrypt_data = true;
101 self
102 }
103
104 pub fn leases(mut self, enabled: bool) -> Self {
126 self.leases = enabled;
127 self
128 }
129
130 pub fn durable_handles(mut self, enabled: bool) -> Self {
148 self.durable_handles = enabled;
149 self
150 }
151
152 pub fn change_notify(mut self, enabled: bool) -> Self {
163 self.change_notify = enabled;
164 self
165 }
166
167 pub fn listed(mut self, listed: bool) -> Self {
173 self.listed = listed;
174 self
175 }
176
177 pub fn remark(mut self, remark: impl Into<String>) -> Self {
181 self.remark = remark.into();
182 self
183 }
184}
185
186const MAX_REMARK_UNITS: usize = 1024;
188
189pub(crate) fn valid_remark(remark: &str) -> bool {
192 !remark.contains('\0') && remark.encode_utf16().count() <= MAX_REMARK_UNITS
193}
194
195#[derive(Debug, Error)]
201pub enum BuildError {
202 #[error("listen address must be set")]
203 MissingListenAddr,
204 #[error("share `{0}` is declared more than once")]
205 DuplicateShare(String),
206 #[error("share `{0}` mixes .public()/.public_read_only() with explicit .user(...) entries")]
207 PublicMixedWithUsers(String),
208 #[error("share `{share}` references unknown user `{user}`")]
209 UnknownUser { share: String, user: String },
210 #[error("user name `{0}` is reserved (use .public()/.public_read_only() for anonymous)")]
211 ReservedUserName(String),
212 #[error("user name must be non-empty")]
213 EmptyUserName,
214 #[error("share name `{0}` is reserved")]
215 ReservedShareName(String),
216 #[error("share name `{0}` must be non-empty and contain no `\\`, `/` or NUL")]
217 InvalidShareName(String),
218 #[error("remark of share `{0}` must hold no NUL and at most 1024 UTF-16 code units")]
219 InvalidShareRemark(String),
220 #[error("`{setting}` must be {expected}")]
221 OutOfRange {
222 setting: &'static str,
223 expected: &'static str,
224 },
225}
226
227pub(crate) enum ShareNameError {
229 Reserved,
231 Invalid,
233}
234
235pub(crate) fn check_share_name(name: &str) -> Result<(), ShareNameError> {
238 if name.eq_ignore_ascii_case("IPC$") {
239 return Err(ShareNameError::Reserved);
240 }
241 if name.is_empty() || name.contains(['\\', '/', '\0']) {
242 return Err(ShareNameError::Invalid);
243 }
244 Ok(())
245}
246
247pub struct SmbServerBuilder {
253 listen_addr: Option<SocketAddr>,
254 users: HashMap<String, String>, user_order: Vec<String>,
256 shares: Vec<Share>,
257 netbios_name: Option<String>,
258 max_read_size: u32,
259 max_write_size: u32,
260 server_guid: Option<Uuid>,
261 limits: Limits,
262 auth: crate::auth_policy::AuthSettings,
263 max_opens_per_connection: usize,
264 max_locks_per_open: usize,
265 share_listing: bool,
266}
267
268impl Default for SmbServerBuilder {
269 fn default() -> Self {
270 Self::new()
271 }
272}
273
274impl SmbServerBuilder {
275 pub(crate) fn new() -> Self {
276 Self {
277 listen_addr: None,
278 users: HashMap::new(),
279 user_order: Vec::new(),
280 shares: Vec::new(),
281 netbios_name: None,
282 max_read_size: 1024 * 1024,
283 max_write_size: 1024 * 1024,
284 server_guid: None,
285 limits: Limits::default(),
286 auth: crate::auth_policy::AuthSettings::default(),
287 max_opens_per_connection: crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
288 max_locks_per_open: crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
289 share_listing: true,
290 }
291 }
292
293 pub fn listen(mut self, addr: SocketAddr) -> Self {
294 self.listen_addr = Some(addr);
295 self
296 }
297
298 pub fn user(mut self, name: impl Into<String>, password: impl Into<String>) -> Self {
299 let n = name.into();
300 if !self.users.contains_key(&n) {
301 self.user_order.push(n.clone());
302 }
303 self.users.insert(n, password.into());
304 self
305 }
306
307 pub fn share(mut self, share: Share) -> Self {
308 self.shares.push(share);
309 self
310 }
311
312 pub fn netbios_name(mut self, name: impl Into<String>) -> Self {
313 self.netbios_name = Some(name.into());
314 self
315 }
316
317 pub fn require_signing(mut self, required: bool) -> Self {
322 self.auth.require_signing = required;
323 self
324 }
325
326 pub fn encrypt_data(mut self, encrypt: bool) -> Self {
333 self.auth.encrypt_data = encrypt;
334 self
335 }
336
337 pub fn reject_unencrypted_access(mut self, reject: bool) -> Self {
345 self.auth.reject_unencrypted_access = reject;
346 self
347 }
348
349 pub fn max_sessions_per_connection(mut self, sessions: usize) -> Self {
352 self.auth.max_sessions_per_connection = sessions;
353 self
354 }
355
356 pub fn max_trees_per_session(mut self, trees: usize) -> Self {
359 self.auth.max_trees_per_session = trees;
360 self
361 }
362
363 pub fn logon_throttle(mut self, max_failures: u32, lockout: Duration) -> Self {
373 self.auth.max_logon_failures = max_failures;
374 self.auth.lockout = lockout;
375 self
376 }
377
378 pub fn max_read_size(mut self, bytes: u32) -> Self {
379 self.max_read_size = bytes;
380 self
381 }
382
383 pub fn max_write_size(mut self, bytes: u32) -> Self {
384 self.max_write_size = bytes;
385 self
386 }
387
388 pub fn server_guid(mut self, guid: Uuid) -> Self {
390 self.server_guid = Some(guid);
391 self
392 }
393
394 pub fn max_connections(mut self, connections: usize) -> Self {
398 self.limits.max_connections = connections;
399 self
400 }
401
402 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
407 self.limits.handshake_timeout = timeout;
408 self
409 }
410
411 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
414 self.limits.idle_timeout = timeout;
415 self
416 }
417
418 pub fn io_timeout(mut self, timeout: Duration) -> Self {
422 self.limits.io_timeout = timeout;
423 self
424 }
425
426 pub fn tcp_keepalive(mut self, idle: Option<Duration>) -> Self {
429 self.limits.tcp_keepalive = idle;
430 self
431 }
432
433 pub fn max_opens_per_connection(mut self, opens: usize) -> Self {
440 self.max_opens_per_connection = opens;
441 self
442 }
443
444 pub fn share_listing(mut self, enabled: bool) -> Self {
455 self.share_listing = enabled;
456 self
457 }
458
459 pub fn max_locks_per_open(mut self, locks: usize) -> Self {
463 self.max_locks_per_open = locks;
464 self
465 }
466
467 pub fn durable_handle_timeout(mut self, timeout: Duration) -> Self {
476 self.limits.durable_handle_timeout = timeout;
477 self
478 }
479
480 pub fn max_disconnected_opens(mut self, opens: usize) -> Self {
487 self.limits.max_disconnected_opens = opens;
488 self
489 }
490
491 pub fn build(self) -> Result<SmbServer, BuildError> {
492 let limits = &self.limits;
493 if limits.max_connections == 0 {
494 return Err(BuildError::OutOfRange {
495 setting: "max_connections",
496 expected: "at least 1",
497 });
498 }
499 for (setting, size) in [
500 ("max_read_size", self.max_read_size),
501 ("max_write_size", self.max_write_size),
502 ] {
503 if !(MIN_IO_SIZE..=MAX_IO_SIZE).contains(&size) {
504 return Err(BuildError::OutOfRange {
505 setting,
506 expected: "between 65536 and 8388608 bytes",
507 });
508 }
509 }
510 for (setting, timeout) in [
511 ("handshake_timeout", Some(limits.handshake_timeout)),
512 ("idle_timeout", Some(limits.idle_timeout)),
513 ("io_timeout", Some(limits.io_timeout)),
514 ("tcp_keepalive", limits.tcp_keepalive),
515 ] {
516 if timeout == Some(Duration::ZERO) {
517 return Err(BuildError::OutOfRange {
518 setting,
519 expected: "greater than zero",
520 });
521 }
522 }
523 if !(MIN_DURABLE_HANDLE_TIMEOUT..=MAX_DURABLE_HANDLE_TIMEOUT)
524 .contains(&limits.durable_handle_timeout)
525 {
526 return Err(BuildError::OutOfRange {
527 setting: "durable_handle_timeout",
528 expected: "between 1 millisecond and 49 days",
529 });
530 }
531
532 for name in &self.user_order {
533 if name.is_empty() {
534 return Err(BuildError::EmptyUserName);
535 }
536 if name.eq_ignore_ascii_case("anonymous") {
537 return Err(BuildError::ReservedUserName(name.clone()));
538 }
539 }
540
541 let mut seen_names = std::collections::HashSet::new();
542 for share in &self.shares {
543 match check_share_name(&share.name) {
544 Err(ShareNameError::Reserved) => {
545 return Err(BuildError::ReservedShareName(share.name.clone()));
546 }
547 Err(ShareNameError::Invalid) => {
548 return Err(BuildError::InvalidShareName(share.name.clone()));
549 }
550 Ok(()) => {}
551 }
552 if !valid_remark(&share.remark) {
553 return Err(BuildError::InvalidShareRemark(share.name.clone()));
554 }
555 if !seen_names.insert(share.name.to_ascii_lowercase()) {
556 return Err(BuildError::DuplicateShare(share.name.clone()));
557 }
558 let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
559 if is_public && !share.users.is_empty() {
560 return Err(BuildError::PublicMixedWithUsers(share.name.clone()));
561 }
562 for u in share.users.keys() {
564 if !self.users.contains_key(u) {
565 return Err(BuildError::UnknownUser {
566 share: share.name.clone(),
567 user: u.clone(),
568 });
569 }
570 }
571 }
572
573 let listen = self.listen_addr.ok_or(BuildError::MissingListenAddr)?;
574
575 let netbios = self.netbios_name.unwrap_or_else(default_netbios_name);
576
577 let mut share_bindings: Vec<Arc<ShareBindings>> = Vec::with_capacity(self.shares.len());
578 for s in self.shares {
579 share_bindings.push(ShareBindings::from_share(s));
580 }
581
582 let mut user_table = HashMap::new();
584 for name in &self.user_order {
585 let pw = &self.users[name];
586 let creds = crate::proto::auth::ntlm::UserCreds::from_password(pw);
587 user_table.insert(name.clone(), creds);
588 }
589
590 let server_guid = self.server_guid.unwrap_or_else(Uuid::new_v4);
591
592 let cfg = ServerConfig {
593 listen_addr: listen,
594 netbios_name: netbios,
595 max_read_size: self.max_read_size,
596 max_write_size: self.max_write_size,
597 server_guid,
598 limits: self.limits,
599 share_listing: self.share_listing,
600 };
601 let users = ServerUsers {
602 table: tokio::sync::RwLock::new(user_table),
603 };
604
605 let state = ServerState::new(cfg, users, share_bindings);
606 let state = state.with_auth(self.auth);
607 state
608 .max_opens_per_connection
609 .store(self.max_opens_per_connection, Ordering::Relaxed);
610 state
611 .max_locks_per_open
612 .store(self.max_locks_per_open, Ordering::Relaxed);
613 Ok(SmbServer::from_state(state))
614 }
615}
616
617const MIN_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_millis(1);
620const MAX_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_secs(49 * 24 * 60 * 60);
621
622const MIN_IO_SIZE: u32 = 64 * 1024;
624const MAX_IO_SIZE: u32 = 8 * 1024 * 1024;
625
626fn default_netbios_name() -> String {
629 let host = host_name().unwrap_or_default();
630 let label: String = host
631 .split('.')
632 .next()
633 .unwrap_or("")
634 .chars()
635 .take(15)
636 .collect();
637 if label.is_empty() {
638 "SMBSERVER".to_string()
639 } else {
640 label.to_uppercase()
641 }
642}
643
644#[cfg(unix)]
645fn host_name() -> Option<String> {
646 let mut buf = [0u8; 256];
647 let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };
649 if rc != 0 {
650 return None;
651 }
652 let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
653 String::from_utf8(buf[..end].to_vec()).ok()
654}
655
656#[cfg(windows)]
657fn host_name() -> Option<String> {
658 std::env::var("COMPUTERNAME").ok()
659}
660
661#[cfg(not(any(unix, windows)))]
662fn host_name() -> Option<String> {
663 None
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669 use crate::tests::memfs::MemFsBackend;
670
671 fn build_with_share(name: &str) -> Result<SmbServer, BuildError> {
672 SmbServer::builder()
673 .listen("127.0.0.1:0".parse().unwrap())
674 .share(Share::new(name, MemFsBackend::new()).public())
675 .build()
676 }
677
678 #[test]
679 fn reserved_and_unreachable_share_names_are_rejected() {
680 for name in ["IPC$", "ipc$"] {
681 assert!(matches!(
682 build_with_share(name),
683 Err(BuildError::ReservedShareName(n)) if n == name
684 ));
685 }
686 for name in ["", "a\\b", "a/b", "\\share", "a\0b"] {
687 assert!(matches!(
688 build_with_share(name),
689 Err(BuildError::InvalidShareName(n)) if n == name
690 ));
691 }
692 assert!(build_with_share("share$").is_ok());
693 }
694
695 #[test]
696 fn remarks_hold_no_nul_and_at_most_1024_units() {
697 let build = |remark: String| {
698 SmbServer::builder()
699 .listen("127.0.0.1:0".parse().unwrap())
700 .share(Share::new("s", MemFsBackend::new()).remark(remark).public())
701 .build()
702 };
703 for remark in ["a".repeat(1024), "\u{1F9A4}".repeat(512)] {
705 assert!(build(remark).is_ok());
706 }
707 for remark in [
708 "a".repeat(1025),
709 "\u{1F9A4}".repeat(513),
710 "a\0b".to_string(),
711 ] {
712 assert!(matches!(
713 build(remark),
714 Err(BuildError::InvalidShareRemark(n)) if n == "s"
715 ));
716 }
717 }
718
719 #[test]
720 fn io_sizes_must_fit_a_frame() {
721 let build = |read: u32, write: u32| {
722 SmbServer::builder()
723 .listen("127.0.0.1:0".parse().unwrap())
724 .max_read_size(read)
725 .max_write_size(write)
726 .build()
727 };
728 const MIB: u32 = 1024 * 1024;
729 assert!(build(64 * 1024, 8 * MIB).is_ok());
730 for (read, write, setting) in [
731 (64 * 1024 - 1, MIB, "max_read_size"),
732 (8 * MIB + 1, MIB, "max_read_size"),
733 (MIB, 0, "max_write_size"),
734 (MIB, 16 * MIB, "max_write_size"),
735 ] {
736 assert!(matches!(
737 build(read, write),
738 Err(BuildError::OutOfRange { setting: s, .. }) if s == setting
739 ));
740 }
741 }
742
743 #[test]
744 fn the_durable_handle_timeout_is_bounded() {
745 let build = |timeout| {
746 SmbServer::builder()
747 .listen("127.0.0.1:0".parse().unwrap())
748 .durable_handle_timeout(timeout)
749 .build()
750 };
751 for timeout in [
752 Duration::ZERO,
753 Duration::from_micros(999),
754 MAX_DURABLE_HANDLE_TIMEOUT + Duration::from_nanos(1),
755 Duration::MAX,
756 ] {
757 assert!(
758 matches!(
759 build(timeout),
760 Err(BuildError::OutOfRange {
761 setting: "durable_handle_timeout",
762 ..
763 })
764 ),
765 "{timeout:?}"
766 );
767 }
768 for timeout in [MIN_DURABLE_HANDLE_TIMEOUT, MAX_DURABLE_HANDLE_TIMEOUT] {
769 assert!(build(timeout).is_ok(), "{timeout:?}");
770 }
771 }
772
773 #[cfg(target_os = "linux")]
774 #[test]
775 fn default_netbios_name_comes_from_the_host_name() {
776 let host = std::fs::read_to_string("/proc/sys/kernel/hostname").expect("hostname");
777 let label = host.trim().split('.').next().expect("label");
778 let expected: String = label.chars().take(15).collect::<String>().to_uppercase();
779 let server = SmbServer::builder()
780 .listen("127.0.0.1:0".parse().unwrap())
781 .build()
782 .expect("build");
783 assert_eq!(server.state().config.netbios_name, expected);
784 }
785}