smb-server 0.12.0

SMB2/3 file-sharing server library with pluggable storage backends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! Public builder API for `SmbServer` and `Share`.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;

use thiserror::Error;
use uuid::Uuid;

use crate::backend::ShareBackend;
use crate::conn::limits::Limits;
use crate::server::{ServerConfig, ServerState, ServerUsers, ShareBindings, ShareMode, SmbServer};

// ---------------------------------------------------------------------------
// Access
// ---------------------------------------------------------------------------

/// Access level granted to a user on a share, or to anonymous on a public
/// share.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Access {
    Read,
    ReadWrite,
}

impl Access {
    pub fn allows_write(self) -> bool {
        matches!(self, Access::ReadWrite)
    }

    pub fn clamp_to(self, cap: Access) -> Access {
        match (self, cap) {
            (Access::ReadWrite, Access::ReadWrite) => Access::ReadWrite,
            _ => Access::Read,
        }
    }
}

// ---------------------------------------------------------------------------
// Share
// ---------------------------------------------------------------------------

/// One share definition, attached to a single backend.
pub struct Share {
    pub(crate) name: String,
    pub(crate) backend: Arc<dyn ShareBackend>,
    pub(crate) mode: ShareMode,
    pub(crate) users: HashMap<String, Access>,
    pub(crate) encrypt_data: bool,
    pub(crate) leases: bool,
    pub(crate) durable_handles: bool,
    pub(crate) change_notify: bool,
    pub(crate) named_streams: bool,
    pub(crate) extended_attributes: bool,
    pub(crate) server_side_copy: bool,
    pub(crate) listed: bool,
    pub(crate) remark: String,
}

impl Share {
    /// Build a new share with the given name and backend.
    pub fn new(name: impl Into<String>, backend: impl ShareBackend) -> Self {
        Self {
            name: name.into(),
            backend: Arc::new(backend),
            mode: ShareMode::AuthenticatedOnly,
            users: HashMap::new(),
            encrypt_data: false,
            leases: true,
            durable_handles: true,
            change_notify: true,
            named_streams: true,
            extended_attributes: true,
            server_side_copy: true,
            listed: true,
            remark: String::new(),
        }
    }

    /// Anonymous + authenticated read+write. A logon as `guest` with an
    /// empty password, which the Finder sends for Connect As Guest, gets the
    /// same access as an anonymous session unless a user of that name is
    /// configured; the name matches in any case. Guest and anonymous traffic
    /// is neither signed nor encrypted, so a client that requires signing
    /// gets no guest session.
    pub fn public(mut self) -> Self {
        self.mode = ShareMode::Public;
        self
    }

    /// Anonymous + authenticated read-only. Guest logons get the same
    /// access as anonymous sessions, as with [`Share::public`].
    pub fn public_read_only(mut self) -> Self {
        self.mode = ShareMode::PublicReadOnly;
        self
    }

    /// Grant `access` to the given (already-registered) user. Multiple calls
    /// accumulate.
    pub fn user(mut self, name: impl Into<String>, access: Access) -> Self {
        self.users.insert(name.into(), access);
        self
    }

    /// Encrypt all traffic to this share. SMB 3.x clients that cannot
    /// encrypt, SMB 2.x clients, and anonymous and guest sessions are
    /// refused at TREE_CONNECT unless
    /// `SmbServerBuilder::reject_unencrypted_access` is turned off.
    pub fn encrypt_data(mut self) -> Self {
        self.encrypt_data = true;
        self
    }

    /// Grant read, handle and write caching leases on this share's files. A
    /// client holding one caches what it reads, keeps files open after its
    /// applications close them, and caches what it writes while every other
    /// open of the file holds the same lease or is attribute-only.
    ///
    /// Opens on the share that do not hold the lease, from another client
    /// or from the same client under another lease key or none, break it:
    /// the client writes back and stops caching writes before such an
    /// open, drops cached data before a write, a size change, a byte-range
    /// lock or an overwrite through it, and closes the handles it keeps
    /// before an open they block, a rename or delete of the file, a rename
    /// over it, or a rename of a directory above it. Attribute-only opens
    /// and opens holding the same lease break nothing. An open or rename
    /// that needs the client to write back or close first waits until the
    /// client acknowledges the break or closes, or until the break times
    /// out 35 seconds after the server sent it; a byte-range lock is refused
    /// instead until the client has written back. On by default.
    ///
    /// Each named stream of a file or directory has leases of its own:
    /// opens, writes, locks and leases of the file's other streams break
    /// none of them, and a lease key held on one stream fails with
    /// STATUS_INVALID_PARAMETER on another, as on another file. A rename or
    /// delete of the file leaves them alone; an overwrite of the file, which
    /// deletes its streams, breaks their handle caching without waiting.
    ///
    /// Changes made outside the server, or through another share over the
    /// same directory, break no lease: clients keep serving the old data.
    /// Turn leases off for such a share.
    pub fn leases(mut self, enabled: bool) -> Self {
        self.leases = enabled;
        self
    }

    /// Keep a client's open files for a while after its connection drops or
    /// it logs off, with their share modes, byte-range locks and leases, so
    /// the client can take them back when it reconnects. Only files opened
    /// with a durable handle request and a lease that caches handles are
    /// kept, so this does nothing when leases are off. The backend handle
    /// stays open for [`SmbServerBuilder::durable_handle_timeout`], or the
    /// time a version 2 request was granted, or until an open, write, size change, byte-range lock, rename or
    /// delete through an open that does not hold the lease needs what the
    /// lease caches, which closes the file at once. A kept open of a named
    /// stream also closes when its file is renamed, or deleted while no
    /// connected open holds the same lease. The same user, from the
    /// same client, on this share, takes a kept file back with a durable
    /// handle reconnect that names the file, or its named stream, and its
    /// lease, and for a version 2 open its CreateGuid. Another user gets
    /// STATUS_ACCESS_DENIED; another client, share, lease or CreateGuid
    /// gets STATUS_OBJECT_NAME_NOT_FOUND. A kept file whose rights exceed
    /// what the user's tree on the share grants at the reconnect is closed
    /// instead. Version 1 and version 2 requests are both served; the
    /// PERSISTENT flag is ignored. On by default.
    pub fn durable_handles(mut self, enabled: bool) -> Self {
        self.durable_handles = enabled;
        self
    }

    /// Answer change notification requests: a client watching a folder, as
    /// Explorer and Finder do for an open window, hears when a file or
    /// folder in it is created, deleted, renamed, written, truncated or
    /// overwritten, or has its attributes, times or extended attributes
    /// set, through any connection to this share. A write, and a set of
    /// extended attributes, is reported when the open that made it closes.
    /// Changes made outside the server, or through another
    /// share over the same directory, are reported only by a backend that
    /// watches for them: `LocalFsBackend` does on Linux, for the entries
    /// directly in a watched folder. When off, such a request reports
    /// nothing and waits until it is cancelled or its handle closes. On by
    /// default.
    pub fn change_notify(mut self, enabled: bool) -> Self {
        self.change_notify = enabled;
        self
    }

    /// Serve named streams (`file.txt:name`) on the share when its backend
    /// stores them ([`BackendCapabilities::named_streams`]). The share then
    /// reports FILE_NAMED_STREAMS, and macOS clients keep extended
    /// attributes, Finder tags and resource forks in streams rather than in
    /// `._` files. When off, a CREATE that names a stream fails with
    /// STATUS_OBJECT_NAME_INVALID. On by default.
    ///
    /// [`BackendCapabilities::named_streams`]: crate::BackendCapabilities::named_streams
    pub fn named_streams(mut self, enabled: bool) -> Self {
        self.named_streams = enabled;
        self
    }

    /// Serve the extended attributes of files and directories on the share
    /// when its backend stores them
    /// ([`BackendCapabilities::extended_attributes`]), as Linux clients
    /// use for `user.*` attributes on a cifs mount. The share then reports
    /// FILE_SUPPORTS_EXTENDED_ATTRIBUTES. When off, the share answers as a
    /// volume that keeps none: FileFullEaInformation queries and sets fail
    /// with STATUS_INVALID_DEVICE_REQUEST, FileEaInformation reports 0, and
    /// a CREATE that carries some fails with STATUS_EAS_NOT_SUPPORTED.
    /// Named streams do not depend on it. On by default.
    ///
    /// [`BackendCapabilities::extended_attributes`]: crate::BackendCapabilities::extended_attributes
    pub fn extended_attributes(mut self, enabled: bool) -> Self {
        self.extended_attributes = enabled;
        self
    }

    /// Copy file data on the server when a client asks for it. Windows
    /// Explorer, Linux `cp` and the macOS Finder send such a request for a
    /// copy within a share; Windows and Linux also for a copy between two
    /// shares of one session, which needs this on both. When off, the
    /// requests fail with STATUS_NOT_SUPPORTED, a macOS whole-file copy of a
    /// file fails with STATUS_ACCESS_DENIED, and a request on a named stream
    /// fails with STATUS_INVALID_DEVICE_REQUEST; clients then read and write
    /// the data themselves. The requests to clone a range of a file that a
    /// backend with [`BackendCapabilities::block_cloning`] serves fail with
    /// STATUS_INVALID_DEVICE_REQUEST too, and the share does not report
    /// FILE_SUPPORTS_BLOCK_REFCOUNTING. On by default.
    ///
    /// [`BackendCapabilities::block_cloning`]: crate::BackendCapabilities::block_cloning
    pub fn server_side_copy(mut self, enabled: bool) -> Self {
        self.server_side_copy = enabled;
        self
    }

    /// Whether the share appears when clients list the server's shares.
    /// An unlisted share is still reachable by name, and a client that may
    /// connect to it can still look it up by name, so this is not access
    /// control. Clients hide shares whose name ends in `$` from ordinary
    /// lists; `net view /all` and `smbclient -L` show them. On by default.
    pub fn listed(mut self, listed: bool) -> Self {
        self.listed = listed;
        self
    }

    /// Text shown next to the share in share lists: the Comment column of
    /// Explorer and `smbclient -L`, the Remark column of `net view`. At most
    /// 1024 UTF-16 code units, without NUL. Empty by default.
    pub fn remark(mut self, remark: impl Into<String>) -> Self {
        self.remark = remark.into();
        self
    }
}

/// Longest share remark, in UTF-16 code units.
const MAX_REMARK_UNITS: usize = 1024;

/// Whether `remark` can be sent as a share's remark: no NUL, and at most
/// [`MAX_REMARK_UNITS`] UTF-16 code units.
pub(crate) fn valid_remark(remark: &str) -> bool {
    !remark.contains('\0') && remark.encode_utf16().count() <= MAX_REMARK_UNITS
}

// ---------------------------------------------------------------------------
// BuildError
// ---------------------------------------------------------------------------

/// Errors raised by `SmbServerBuilder::build`.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BuildError {
    #[error("listen address must be set")]
    MissingListenAddr,
    #[error("share `{0}` is declared more than once")]
    DuplicateShare(String),
    #[error("share `{0}` mixes .public()/.public_read_only() with explicit .user(...) entries")]
    PublicMixedWithUsers(String),
    #[error("share `{share}` references unknown user `{user}`")]
    UnknownUser { share: String, user: String },
    #[error("user name `{0}` is reserved (use .public()/.public_read_only() for anonymous)")]
    ReservedUserName(String),
    #[error("user name must be non-empty")]
    EmptyUserName,
    #[error("share name `{0}` is reserved")]
    ReservedShareName(String),
    #[error("share name `{0}` must be non-empty and contain no `\\`, `/` or NUL")]
    InvalidShareName(String),
    #[error("remark of share `{0}` must hold no NUL and at most 1024 UTF-16 code units")]
    InvalidShareRemark(String),
    #[error("`{setting}` must be {expected}")]
    OutOfRange {
        setting: &'static str,
        expected: &'static str,
    },
    #[error("discovery name `{0}` must be 1 to 63 bytes without control characters")]
    DiscoveryName(String),
    #[error("discovery model `{0}` must be 1 to 249 printable ASCII characters")]
    DiscoveryModel(String),
    #[error("discovery cannot announce the loopback listen address {0}")]
    DiscoveryOnLoopback(SocketAddr),
    #[error(
        "discovery workgroup `{0}` must be 1 to 15 characters without control characters or any of \"/\\[]:|<>+=;,?*"
    )]
    DiscoveryWorkgroup(String),
    #[error("discovery {setting} `{value}` must be 1 to 255 characters without control characters")]
    DiscoveryMetadata {
        setting: &'static str,
        value: String,
    },
    #[error("Apple model {0:?} must be 1 to 79 UTF-8 bytes without control characters")]
    AppleModel(String),
    #[error("WS-Discovery needs the server on port 445, not {0}")]
    WsDiscoveryPort(u16),
    #[error(
        "WS-Discovery needs a NetBIOS name of 1 to 15 characters without control characters or any of \"/\\[]:|<>+=;,?*, not `{0}`"
    )]
    WsDiscoveryNetbiosName(String),
}

/// Why a share name cannot be configured.
pub(crate) enum ShareNameError {
    /// IPC$, which the server provides itself.
    Reserved,
    /// Empty, or contains `\`, `/` or NUL, so no UNC path reaches it.
    Invalid,
}

/// Checks a share name for [`SmbServerBuilder::build`] and
/// `ConfigHandle`.
pub(crate) fn check_share_name(name: &str) -> Result<(), ShareNameError> {
    if name.eq_ignore_ascii_case("IPC$") {
        return Err(ShareNameError::Reserved);
    }
    if name.is_empty() || name.contains(['\\', '/', '\0']) {
        return Err(ShareNameError::Invalid);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// SmbServerBuilder
// ---------------------------------------------------------------------------

/// Builder for `SmbServer`. See `SmbServer::builder`.
pub struct SmbServerBuilder {
    listen_addr: Option<SocketAddr>,
    users: HashMap<String, String>, // name -> password
    user_order: Vec<String>,
    shares: Vec<Share>,
    netbios_name: Option<String>,
    max_read_size: u32,
    max_write_size: u32,
    server_guid: Option<Uuid>,
    limits: Limits,
    auth: crate::auth_policy::AuthSettings,
    max_opens_per_connection: usize,
    max_locks_per_open: usize,
    share_listing: bool,
    apple_extensions: bool,
    apple_model: String,
    apple_copyfile: bool,
    #[cfg(feature = "discovery")]
    discovery: Option<crate::discovery::Discovery>,
}

impl Default for SmbServerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl SmbServerBuilder {
    pub(crate) fn new() -> Self {
        Self {
            listen_addr: None,
            users: HashMap::new(),
            user_order: Vec::new(),
            shares: Vec::new(),
            netbios_name: None,
            max_read_size: 1024 * 1024,
            max_write_size: 1024 * 1024,
            server_guid: None,
            limits: Limits::default(),
            auth: crate::auth_policy::AuthSettings::default(),
            max_opens_per_connection: crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
            max_locks_per_open: crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
            share_listing: true,
            apple_extensions: true,
            apple_model: DEFAULT_APPLE_MODEL.to_string(),
            apple_copyfile: true,
            #[cfg(feature = "discovery")]
            discovery: None,
        }
    }

    pub fn listen(mut self, addr: SocketAddr) -> Self {
        self.listen_addr = Some(addr);
        self
    }

    pub fn user(mut self, name: impl Into<String>, password: impl Into<String>) -> Self {
        let n = name.into();
        if !self.users.contains_key(&n) {
            self.user_order.push(n.clone());
        }
        self.users.insert(n, password.into());
        self
    }

    pub fn share(mut self, share: Share) -> Self {
        self.shares.push(share);
        self
    }

    pub fn netbios_name(mut self, name: impl Into<String>) -> Self {
        self.netbios_name = Some(name.into());
        self
    }

    /// Require every authenticated session to sign its requests, and set
    /// SMB2_NEGOTIATE_SIGNING_REQUIRED in the NEGOTIATE response. It does
    /// not apply to anonymous and guest sessions, which have no key and stay
    /// unsigned. Off by default; a client can still require signing for its
    /// own sessions.
    pub fn require_signing(mut self, required: bool) -> Self {
        self.auth.require_signing = required;
        self
    }

    /// Encrypt every authenticated session on a connection that negotiated
    /// a cipher. While `reject_unencrypted_access` is on, clients that
    /// cannot encrypt get no session, and anonymous and guest sessions get
    /// no tree.
    /// Off by default; with it off, a client that sends encrypted requests
    /// gets encrypted replies, and `Share::encrypt_data` turns encryption
    /// on for one share.
    pub fn encrypt_data(mut self, encrypt: bool) -> Self {
        self.auth.encrypt_data = encrypt;
        self
    }

    /// Whether a session or share that must be encrypted refuses clients
    /// that cannot encrypt: SMB 2.x, SMB 3.0 and 3.0.2 without the
    /// encryption capability, SMB 3.1.1 without a common cipher, and
    /// anonymous and guest sessions. On SMB 3.0 and 3.0.2 it also refuses
    /// unencrypted requests from clients that can encrypt; SMB 3.1.1 always
    /// refuses them. On by default. Turned off, clients that cannot encrypt
    /// are served unencrypted.
    pub fn reject_unencrypted_access(mut self, reject: bool) -> Self {
        self.auth.reject_unencrypted_access = reject;
        self
    }

    /// Most sessions one connection may hold. SESSION_SETUP past the limit
    /// fails with STATUS_INSUFFICIENT_RESOURCES. Default 64.
    pub fn max_sessions_per_connection(mut self, sessions: usize) -> Self {
        self.auth.max_sessions_per_connection = sessions;
        self
    }

    /// Most tree connects one session may hold. TREE_CONNECT past the limit
    /// fails with STATUS_INSUFFICIENT_RESOURCES. Default 128.
    pub fn max_trees_per_session(mut self, trees: usize) -> Self {
        self.auth.max_trees_per_session = trees;
        self
    }

    /// Failed-logon throttle. After `max_failures` failed logons for one
    /// user name, each within `lockout` of the one before, logons with that
    /// name fail with STATUS_ACCOUNT_LOCKED_OUT until `lockout` has passed
    /// since the last failure. One client address is locked out the same
    /// way after ten times `max_failures` failed logons, whatever names they
    /// used. A connection is closed after `max_failures` failed logons.
    /// Unknown names are tracked the same way as configured ones.
    /// `max_failures` 0 turns the throttle off. Default 10 failures and 60
    /// seconds.
    pub fn logon_throttle(mut self, max_failures: u32, lockout: Duration) -> Self {
        self.auth.max_logon_failures = max_failures;
        self.auth.lockout = lockout;
        self
    }

    pub fn max_read_size(mut self, bytes: u32) -> Self {
        self.max_read_size = bytes;
        self
    }

    pub fn max_write_size(mut self, bytes: u32) -> Self {
        self.max_write_size = bytes;
        self
    }

    /// Override the random per-process server GUID. Mostly useful in tests.
    pub fn server_guid(mut self, guid: Uuid) -> Self {
        self.server_guid = Some(guid);
        self
    }

    /// Most connections served at once, counting every client together;
    /// per-host limits belong in the firewall. A connection accepted beyond
    /// the limit is closed straight away. Defaults to 1024.
    pub fn max_connections(mut self, connections: usize) -> Self {
        self.limits.max_connections = connections;
        self
    }

    /// Time a new connection has to establish a session, and each
    /// SESSION_SETUP exchange has to finish. A connection still without a
    /// session at the deadline is closed, and an unfinished exchange is
    /// dropped. Defaults to 30 seconds.
    pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
        self.limits.handshake_timeout = timeout;
        self
    }

    /// Closes a connection that has sent no request for this long and has no
    /// open files. Defaults to 15 minutes.
    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
        self.limits.idle_timeout = timeout;
        self
    }

    /// Time allowed to receive the rest of a request once its first bytes
    /// have arrived, and to send one response. The connection closes when
    /// either takes longer. Defaults to 60 seconds.
    pub fn io_timeout(mut self, timeout: Duration) -> Self {
        self.limits.io_timeout = timeout;
        self
    }

    /// Idle time before TCP keepalive probes start on accepted connections,
    /// or `None` to leave keepalive off. Defaults to 60 seconds.
    pub fn tcp_keepalive(mut self, idle: Option<Duration>) -> Self {
        self.limits.tcp_keepalive = idle;
        self
    }

    /// Most files and named pipes one connection may hold open at once. A
    /// CREATE past the limit fails with STATUS_INSUFFICIENT_RESOURCES.
    /// Named pipes are also limited to 16 per connection. Defaults to
    /// [`DEFAULT_MAX_OPENS_PER_CONNECTION`](crate::DEFAULT_MAX_OPENS_PER_CONNECTION).
    /// [`ConfigHandle::set_max_opens_per_connection`](crate::ConfigHandle::set_max_opens_per_connection)
    /// changes it at run time.
    pub fn max_opens_per_connection(mut self, opens: usize) -> Self {
        self.max_opens_per_connection = opens;
        self
    }

    /// Answer clients that list the server's shares: Explorer and `net
    /// view` on Windows, the Finder and `smbutil view` on macOS, `smbclient
    /// -L` and file managers on Linux. A client sees the shares its session
    /// may connect to, the public ones for an anonymous session, and IPC$,
    /// in the order the shares were added; a share whose traffic is
    /// encrypted is left out for a session that cannot encrypt. Shares left
    /// out with [`Share::listed`] are not in the list. Clients list shares through the
    /// `srvsvc` named pipe on IPC$; one connection may hold 16 named pipes
    /// at once. On by default; turned off, IPC$ opens no pipe and clients
    /// get no list.
    pub fn share_listing(mut self, enabled: bool) -> Self {
        self.share_listing = enabled;
        self
    }

    /// Most byte-range locks one open may hold at once. A LOCK past the
    /// limit fails with STATUS_INSUFFICIENT_RESOURCES. Defaults to
    /// [`DEFAULT_MAX_LOCKS_PER_OPEN`](crate::DEFAULT_MAX_LOCKS_PER_OPEN).
    pub fn max_locks_per_open(mut self, locks: usize) -> Self {
        self.max_locks_per_open = locks;
        self
    }

    /// How long the server keeps an open file for a client whose
    /// connection dropped or that logged off; see
    /// [`Share::durable_handles`]. A client that asks for a time in a
    /// version 2 durable handle request gets it, up to this timeout or 5
    /// minutes, whichever is longer. Must be between 1 millisecond and 49
    /// days. Defaults to
    /// [`DEFAULT_DURABLE_HANDLE_TIMEOUT`](crate::DEFAULT_DURABLE_HANDLE_TIMEOUT),
    /// 2 minutes.
    pub fn durable_handle_timeout(mut self, timeout: Duration) -> Self {
        self.limits.durable_handle_timeout = timeout;
        self
    }

    /// Most open files the server keeps for clients whose connection
    /// dropped or that logged off, counting every client together; one user
    /// gets at most a quarter of them, rounded up. Past the limit, such a
    /// client's files are closed. Defaults to
    /// [`DEFAULT_MAX_DISCONNECTED_OPENS`](crate::DEFAULT_MAX_DISCONNECTED_OPENS),
    /// 4096.
    pub fn max_disconnected_opens(mut self, opens: usize) -> Self {
        self.limits.max_disconnected_opens = opens;
        self
    }

    /// Announce the server on the local network while
    /// [`SmbServer::serve`] runs; see [`Discovery`](crate::Discovery). Off
    /// unless called. [`build`](Self::build) fails when the listen address
    /// is a loopback address, and when
    /// [`Discovery::ws_discovery`](crate::Discovery::ws_discovery) is `true`
    /// and the listen port is set to one other than 445 or the NetBIOS name
    /// is not one Windows accepts. Needs the `discovery` feature.
    #[cfg(feature = "discovery")]
    pub fn discovery(mut self, discovery: crate::discovery::Discovery) -> Self {
        self.discovery = Some(discovery);
        self
    }

    /// Answer the `AAPL` create context that macOS clients send when they
    /// mount a share. The reply carries the model string of
    /// [`apple_model`](Self::apple_model), whether the server runs on a
    /// Unix host and whether the share's names are case-sensitive, and the
    /// client then treats the server as one with Apple's SMB2 extensions.
    /// macOS keeps one case-sensitivity value per session: shares mounted
    /// over one session all take that of the last one mounted. On by
    /// default; turned off, the context is ignored.
    pub fn apple_extensions(mut self, enabled: bool) -> Self {
        self.apple_extensions = enabled;
        self
    }

    /// The model string sent to macOS clients in the `AAPL` reply. Default
    /// `smb-server`. While [`apple_extensions`](Self::apple_extensions) is
    /// on, [`build`](Self::build) fails unless it is 1 to 79 bytes of UTF-8
    /// without control characters.
    pub fn apple_model(mut self, model: impl Into<String>) -> Self {
        self.apple_model = model.into();
        self
    }

    /// Offers macOS clients the whole-file copy: a COPYCHUNK or
    /// COPYCHUNK_WRITE without chunks copies a file with its named streams
    /// and its creation and write times in one request. Offered on shares
    /// that serve named streams and allow server-side copies, while
    /// [`apple_extensions`](Self::apple_extensions) is on. A connection
    /// keeps the offer for every share, and a copy onto a share without
    /// named streams carries the data only. On by default.
    pub fn apple_copyfile(mut self, enabled: bool) -> Self {
        self.apple_copyfile = enabled;
        self
    }

    pub fn build(self) -> Result<SmbServer, BuildError> {
        let limits = &self.limits;
        if limits.max_connections == 0 {
            return Err(BuildError::OutOfRange {
                setting: "max_connections",
                expected: "at least 1",
            });
        }
        for (setting, size) in [
            ("max_read_size", self.max_read_size),
            ("max_write_size", self.max_write_size),
        ] {
            if !(MIN_IO_SIZE..=MAX_IO_SIZE).contains(&size) {
                return Err(BuildError::OutOfRange {
                    setting,
                    expected: "between 65536 and 8388608 bytes",
                });
            }
        }
        for (setting, timeout) in [
            ("handshake_timeout", Some(limits.handshake_timeout)),
            ("idle_timeout", Some(limits.idle_timeout)),
            ("io_timeout", Some(limits.io_timeout)),
            ("tcp_keepalive", limits.tcp_keepalive),
        ] {
            if timeout == Some(Duration::ZERO) {
                return Err(BuildError::OutOfRange {
                    setting,
                    expected: "greater than zero",
                });
            }
        }
        if !(MIN_DURABLE_HANDLE_TIMEOUT..=MAX_DURABLE_HANDLE_TIMEOUT)
            .contains(&limits.durable_handle_timeout)
        {
            return Err(BuildError::OutOfRange {
                setting: "durable_handle_timeout",
                expected: "between 1 millisecond and 49 days",
            });
        }

        for name in &self.user_order {
            if name.is_empty() {
                return Err(BuildError::EmptyUserName);
            }
            if name.eq_ignore_ascii_case("anonymous") {
                return Err(BuildError::ReservedUserName(name.clone()));
            }
        }

        let mut seen_names = std::collections::HashSet::new();
        for share in &self.shares {
            match check_share_name(&share.name) {
                Err(ShareNameError::Reserved) => {
                    return Err(BuildError::ReservedShareName(share.name.clone()));
                }
                Err(ShareNameError::Invalid) => {
                    return Err(BuildError::InvalidShareName(share.name.clone()));
                }
                Ok(()) => {}
            }
            if !valid_remark(&share.remark) {
                return Err(BuildError::InvalidShareRemark(share.name.clone()));
            }
            if !seen_names.insert(share.name.to_ascii_lowercase()) {
                return Err(BuildError::DuplicateShare(share.name.clone()));
            }
            let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
            if is_public && !share.users.is_empty() {
                return Err(BuildError::PublicMixedWithUsers(share.name.clone()));
            }
            // Each per-share user must exist in the global user table.
            for u in share.users.keys() {
                if !self.users.contains_key(u) {
                    return Err(BuildError::UnknownUser {
                        share: share.name.clone(),
                        user: u.clone(),
                    });
                }
            }
        }

        if self.apple_extensions
            && (!(1..=MAX_APPLE_MODEL).contains(&self.apple_model.len())
                || self.apple_model.chars().any(char::is_control))
        {
            return Err(BuildError::AppleModel(self.apple_model));
        }

        let listen = self.listen_addr.ok_or(BuildError::MissingListenAddr)?;

        let netbios = self.netbios_name.unwrap_or_else(default_netbios_name);
        #[cfg(feature = "discovery")]
        let discovery = self
            .discovery
            .map(|discovery| discovery.settings(listen, &netbios, self.server_guid))
            .transpose()?;

        let mut share_bindings: Vec<Arc<ShareBindings>> = Vec::with_capacity(self.shares.len());
        for s in self.shares {
            share_bindings.push(ShareBindings::from_share(s));
        }

        // Store NT hashes only; plaintext passwords are dropped.
        let mut user_table = HashMap::new();
        for name in &self.user_order {
            let pw = &self.users[name];
            let creds = crate::proto::auth::ntlm::UserCreds::from_password(pw);
            user_table.insert(name.clone(), creds);
        }

        let server_guid = self.server_guid.unwrap_or_else(Uuid::new_v4);

        let cfg = ServerConfig {
            listen_addr: listen,
            netbios_name: netbios,
            max_read_size: self.max_read_size,
            max_write_size: self.max_write_size,
            server_guid,
            limits: self.limits,
            share_listing: self.share_listing,
            apple_model: self.apple_extensions.then_some(self.apple_model),
            apple_copyfile: self.apple_copyfile,
            #[cfg(feature = "discovery")]
            discovery,
        };
        let users = ServerUsers {
            table: tokio::sync::RwLock::new(user_table),
        };

        let state = ServerState::new(cfg, users, share_bindings);
        let state = state.with_auth(self.auth);
        state
            .max_opens_per_connection
            .store(self.max_opens_per_connection, Ordering::Relaxed);
        state
            .max_locks_per_open
            .store(self.max_locks_per_open, Ordering::Relaxed);
        Ok(SmbServer::from_state(state))
    }
}

/// Shortest and longest accepted `durable_handle_timeout`. Version 2
/// responses carry the timeout in whole milliseconds, in 32 bits.
const MIN_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_millis(1);
const MAX_DURABLE_HANDLE_TIMEOUT: Duration = Duration::from_secs(49 * 24 * 60 * 60);

/// The model string of `AAPL` replies unless one is set.
const DEFAULT_APPLE_MODEL: &str = "smb-server";
/// Longest accepted model string, in UTF-8 bytes. macOS keeps the model
/// in an 80-byte buffer with its terminator.
const MAX_APPLE_MODEL: usize = 79;

/// Smallest and largest accepted `max_read_size` and `max_write_size`.
const MIN_IO_SIZE: u32 = 64 * 1024;
const MAX_IO_SIZE: u32 = 8 * 1024 * 1024;

/// The host name's first label, uppercased and cut to the 15 characters a
/// NetBIOS name holds, or `SMBSERVER` when the host name is unknown.
fn default_netbios_name() -> String {
    let host = host_name().unwrap_or_default();
    let label: String = host
        .split('.')
        .next()
        .unwrap_or("")
        .chars()
        .take(15)
        .collect();
    if label.is_empty() {
        "SMBSERVER".to_string()
    } else {
        label.to_uppercase()
    }
}

#[cfg(unix)]
pub(crate) fn host_name() -> Option<String> {
    let mut buf = [0u8; 256];
    // SAFETY: `buf` is valid for writes of `buf.len()` bytes.
    let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };
    if rc != 0 {
        return None;
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8(buf[..end].to_vec()).ok()
}

#[cfg(windows)]
pub(crate) fn host_name() -> Option<String> {
    std::env::var("COMPUTERNAME").ok()
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn host_name() -> Option<String> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::memfs::MemFsBackend;

    fn build_with_share(name: &str) -> Result<SmbServer, BuildError> {
        SmbServer::builder()
            .listen("127.0.0.1:0".parse().unwrap())
            .share(Share::new(name, MemFsBackend::new()).public())
            .build()
    }

    #[test]
    fn reserved_and_unreachable_share_names_are_rejected() {
        for name in ["IPC$", "ipc$"] {
            assert!(matches!(
                build_with_share(name),
                Err(BuildError::ReservedShareName(n)) if n == name
            ));
        }
        for name in ["", "a\\b", "a/b", "\\share", "a\0b"] {
            assert!(matches!(
                build_with_share(name),
                Err(BuildError::InvalidShareName(n)) if n == name
            ));
        }
        assert!(build_with_share("share$").is_ok());
    }

    #[test]
    fn remarks_hold_no_nul_and_at_most_1024_units() {
        let build = |remark: String| {
            SmbServer::builder()
                .listen("127.0.0.1:0".parse().unwrap())
                .share(Share::new("s", MemFsBackend::new()).remark(remark).public())
                .build()
        };
        // U+1F9A4 takes two UTF-16 code units.
        for remark in ["a".repeat(1024), "\u{1F9A4}".repeat(512)] {
            assert!(build(remark).is_ok());
        }
        for remark in [
            "a".repeat(1025),
            "\u{1F9A4}".repeat(513),
            "a\0b".to_string(),
        ] {
            assert!(matches!(
                build(remark),
                Err(BuildError::InvalidShareRemark(n)) if n == "s"
            ));
        }
    }

    #[test]
    fn io_sizes_must_fit_a_frame() {
        let build = |read: u32, write: u32| {
            SmbServer::builder()
                .listen("127.0.0.1:0".parse().unwrap())
                .max_read_size(read)
                .max_write_size(write)
                .build()
        };
        const MIB: u32 = 1024 * 1024;
        assert!(build(64 * 1024, 8 * MIB).is_ok());
        for (read, write, setting) in [
            (64 * 1024 - 1, MIB, "max_read_size"),
            (8 * MIB + 1, MIB, "max_read_size"),
            (MIB, 0, "max_write_size"),
            (MIB, 16 * MIB, "max_write_size"),
        ] {
            assert!(matches!(
                build(read, write),
                Err(BuildError::OutOfRange { setting: s, .. }) if s == setting
            ));
        }
    }

    #[test]
    fn the_apple_model_holds_1_to_79_bytes_without_control_characters() {
        let build = |builder: SmbServerBuilder, model: &str| {
            builder
                .listen("127.0.0.1:0".parse().unwrap())
                .apple_model(model)
                .build()
        };
        let longest = "\u{1F34E}".repeat(19) + "abc";
        assert_eq!(longest.len(), 79);
        for model in ["NAS 2", &"x".repeat(79), &longest] {
            assert!(build(SmbServer::builder(), model).is_ok(), "{model:?}");
        }
        for model in [
            "",
            &"x".repeat(80),
            &(longest.clone() + "a"),
            "a\nb",
            "a\u{85}",
        ] {
            assert!(
                matches!(build(SmbServer::builder(), model), Err(BuildError::AppleModel(m)) if m == model),
                "{model:?}"
            );
            let off = SmbServer::builder().apple_extensions(false);
            assert!(
                build(off, model).is_ok(),
                "{model:?} with the extensions off"
            );
        }
        let configured = |builder: SmbServerBuilder| {
            let server = builder
                .listen("127.0.0.1:0".parse().unwrap())
                .build()
                .expect("build");
            server.state().config.apple_model.clone()
        };
        assert_eq!(
            configured(SmbServer::builder()).as_deref(),
            Some("smb-server")
        );
        assert_eq!(
            configured(SmbServer::builder().apple_extensions(false)),
            None
        );
    }

    #[test]
    fn the_durable_handle_timeout_is_bounded() {
        let build = |timeout| {
            SmbServer::builder()
                .listen("127.0.0.1:0".parse().unwrap())
                .durable_handle_timeout(timeout)
                .build()
        };
        for timeout in [
            Duration::ZERO,
            Duration::from_micros(999),
            MAX_DURABLE_HANDLE_TIMEOUT + Duration::from_nanos(1),
            Duration::MAX,
        ] {
            assert!(
                matches!(
                    build(timeout),
                    Err(BuildError::OutOfRange {
                        setting: "durable_handle_timeout",
                        ..
                    })
                ),
                "{timeout:?}"
            );
        }
        for timeout in [MIN_DURABLE_HANDLE_TIMEOUT, MAX_DURABLE_HANDLE_TIMEOUT] {
            assert!(build(timeout).is_ok(), "{timeout:?}");
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn default_netbios_name_comes_from_the_host_name() {
        let host = std::fs::read_to_string("/proc/sys/kernel/hostname").expect("hostname");
        let label = host.trim().split('.').next().expect("label");
        let expected: String = label.chars().take(15).collect::<String>().to_uppercase();
        let server = SmbServer::builder()
            .listen("127.0.0.1:0".parse().unwrap())
            .build()
            .expect("build");
        assert_eq!(server.state().config.netbios_name, expected);
    }
}