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 {
83 self.mode = ShareMode::Public;
84 self
85 }
86
87 pub fn public_read_only(mut self) -> Self {
90 self.mode = ShareMode::PublicReadOnly;
91 self
92 }
93
94 pub fn user(mut self, name: impl Into<String>, access: Access) -> Self {
97 self.users.insert(name.into(), access);
98 self
99 }
100
101 pub fn encrypt_data(mut self) -> Self {
106 self.encrypt_data = true;
107 self
108 }
109
110 pub fn leases(mut self, enabled: bool) -> Self {
132 self.leases = enabled;
133 self
134 }
135
136 pub fn durable_handles(mut self, enabled: bool) -> Self {
154 self.durable_handles = enabled;
155 self
156 }
157
158 pub fn change_notify(mut self, enabled: bool) -> Self {
169 self.change_notify = enabled;
170 self
171 }
172
173 pub fn listed(mut self, listed: bool) -> Self {
179 self.listed = listed;
180 self
181 }
182
183 pub fn remark(mut self, remark: impl Into<String>) -> Self {
187 self.remark = remark.into();
188 self
189 }
190}
191
192const MAX_REMARK_UNITS: usize = 1024;
194
195pub(crate) fn valid_remark(remark: &str) -> bool {
198 !remark.contains('\0') && remark.encode_utf16().count() <= MAX_REMARK_UNITS
199}
200
201#[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
255pub(crate) enum ShareNameError {
257 Reserved,
259 Invalid,
261}
262
263pub(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
275pub struct SmbServerBuilder {
281 listen_addr: Option<SocketAddr>,
282 users: HashMap<String, String>, 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 pub fn require_signing(mut self, required: bool) -> Self {
355 self.auth.require_signing = required;
356 self
357 }
358
359 pub fn encrypt_data(mut self, encrypt: bool) -> Self {
367 self.auth.encrypt_data = encrypt;
368 self
369 }
370
371 pub fn reject_unencrypted_access(mut self, reject: bool) -> Self {
379 self.auth.reject_unencrypted_access = reject;
380 self
381 }
382
383 pub fn max_sessions_per_connection(mut self, sessions: usize) -> Self {
386 self.auth.max_sessions_per_connection = sessions;
387 self
388 }
389
390 pub fn max_trees_per_session(mut self, trees: usize) -> Self {
393 self.auth.max_trees_per_session = trees;
394 self
395 }
396
397 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 pub fn server_guid(mut self, guid: Uuid) -> Self {
424 self.server_guid = Some(guid);
425 self
426 }
427
428 pub fn max_connections(mut self, connections: usize) -> Self {
432 self.limits.max_connections = connections;
433 self
434 }
435
436 pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
441 self.limits.handshake_timeout = timeout;
442 self
443 }
444
445 pub fn idle_timeout(mut self, timeout: Duration) -> Self {
448 self.limits.idle_timeout = timeout;
449 self
450 }
451
452 pub fn io_timeout(mut self, timeout: Duration) -> Self {
456 self.limits.io_timeout = timeout;
457 self
458 }
459
460 pub fn tcp_keepalive(mut self, idle: Option<Duration>) -> Self {
463 self.limits.tcp_keepalive = idle;
464 self
465 }
466
467 pub fn max_opens_per_connection(mut self, opens: usize) -> Self {
474 self.max_opens_per_connection = opens;
475 self
476 }
477
478 pub fn share_listing(mut self, enabled: bool) -> Self {
489 self.share_listing = enabled;
490 self
491 }
492
493 pub fn max_locks_per_open(mut self, locks: usize) -> Self {
497 self.max_locks_per_open = locks;
498 self
499 }
500
501 pub fn durable_handle_timeout(mut self, timeout: Duration) -> Self {
510 self.limits.durable_handle_timeout = timeout;
511 self
512 }
513
514 pub fn max_disconnected_opens(mut self, opens: usize) -> Self {
521 self.limits.max_disconnected_opens = opens;
522 self
523 }
524
525 #[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 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 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
671const MIN_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_millis(1);
674const MAX_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_secs(49 * 24 * 60 * 60);
675
676const MIN_IO_SIZE: u32 = 64 * 1024;
678const MAX_IO_SIZE: u32 = 8 * 1024 * 1024;
679
680fn 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 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 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}