smb-server 0.7.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
//! Top-level `SmbServer` lifecycle: builder integration, accept loop,
//! graceful shutdown.

use std::collections::HashMap;
use std::io;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Weak};

use crate::proto::auth::ntlm::{Identity, UserCreds};
use thiserror::Error;
use tokio::net::TcpListener;
use tokio::sync::{Notify, RwLock, Semaphore};
use tokio::task::JoinSet;
use tracing::{Instrument, debug, error, info, info_span, warn};
use uuid::Uuid;

use crate::backend::ShareBackend;
use crate::builder::{
    Access, Share, ShareNameError, SmbServerBuilder, check_share_name, valid_remark,
};
use crate::conn::connection_loop;
use crate::conn::limits::Limits;
use crate::conn::listener::{AcceptBackoff, configure_socket};
use crate::conn::state::Connection;
use crate::files::{DurableTable, close_opens};

// ---------------------------------------------------------------------------
// ShareMode / ShareBindings
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShareMode {
    Public,
    PublicReadOnly,
    /// Default: closed share. Only users in the explicit `users` map allowed.
    AuthenticatedOnly,
}

#[derive(Clone)]
pub struct ShareAcl {
    pub mode: ShareMode,
    pub users: HashMap<String, Access>,
}

impl ShareAcl {
    /// The access `identity` gets to the share, or `None` when it may not
    /// connect: public shares admit everyone, other shares their users.
    pub(crate) fn authorize(&self, identity: &Identity) -> Option<Access> {
        match self.mode {
            ShareMode::Public => Some(Access::ReadWrite),
            ShareMode::PublicReadOnly => Some(Access::Read),
            ShareMode::AuthenticatedOnly => match identity {
                Identity::Anonymous => None,
                Identity::User { user, .. } => self.users.get(user).copied(),
            },
        }
    }
}

/// A session as share admission sees it.
#[derive(Debug, Clone)]
pub(crate) struct Caller {
    pub identity: Identity,
    /// The session has encryption keys.
    pub can_encrypt: bool,
}

impl Caller {
    pub(crate) fn of(session: &crate::conn::state::Session) -> Self {
        Self {
            identity: session.identity.clone(),
            can_encrypt: session.cipher.is_some(),
        }
    }
}

/// Compiled binding for a single share: the per-server-state form of `Share`.
pub struct ShareBindings {
    pub name: String,
    pub backend: Arc<dyn ShareBackend>,
    pub acl: RwLock<ShareAcl>,
    /// `IPC$` synthetic share. Accepted at TREE_CONNECT; its opens are
    /// named pipes.
    pub is_ipc: bool,
    /// Share.EncryptData: traffic to the share is encrypted.
    pub encrypt_data: bool,
    /// Leases are granted on the share's files.
    pub(crate) leases: bool,
    /// Opens asking for a durable handle get one.
    pub(crate) durable_handles: bool,
    /// The share appears when clients list the server's shares.
    pub(crate) listed: bool,
    /// The comment shown next to the share in share lists.
    pub(crate) remark: String,
    /// Every file on the share that has an open, on any connection.
    pub(crate) files: crate::files::FileTable,
    /// CHANGE_NOTIFY is answered on the share.
    pub(crate) change_notify: bool,
    /// The directories clients watch for changes, on any connection.
    pub(crate) watches: crate::files::WatchTable,
}

impl ShareBindings {
    pub(crate) fn new(
        name: String,
        backend: Arc<dyn ShareBackend>,
        mode: ShareMode,
        users: HashMap<String, Access>,
        is_ipc: bool,
        leases: bool,
        durable_handles: bool,
    ) -> Arc<Self> {
        let watches = crate::files::WatchTable::new(backend.capabilities().case_sensitive);
        Arc::new(Self {
            name,
            backend,
            acl: RwLock::new(ShareAcl { mode, users }),
            is_ipc,
            encrypt_data: false,
            leases,
            durable_handles,
            listed: true,
            remark: String::new(),
            files: crate::files::FileTable::default(),
            change_notify: !is_ipc,
            watches,
        })
    }

    pub(crate) fn from_share(share: Share) -> Arc<Self> {
        let watches = crate::files::WatchTable::new(share.backend.capabilities().case_sensitive);
        Arc::new(Self {
            name: share.name,
            backend: share.backend,
            acl: RwLock::new(ShareAcl {
                mode: share.mode,
                users: share.users,
            }),
            is_ipc: false,
            encrypt_data: share.encrypt_data,
            leases: share.leases,
            durable_handles: share.durable_handles,
            listed: share.listed,
            remark: share.remark,
            files: crate::files::FileTable::default(),
            change_notify: share.change_notify,
            watches,
        })
    }

    /// Synthetic IPC$ share, whose opens are named pipes.
    pub fn ipc() -> Arc<Self> {
        Self::new(
            "IPC$".to_string(),
            Arc::new(crate::backend::NotSupportedBackend),
            ShareMode::PublicReadOnly,
            HashMap::new(),
            true,
            false,
            false,
        )
    }
}

// ---------------------------------------------------------------------------
// ServerConfig / ServerUsers / ServerState
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct ServerConfig {
    pub listen_addr: SocketAddr,
    pub netbios_name: String,
    pub max_read_size: u32,
    pub max_write_size: u32,
    pub server_guid: Uuid,
    pub limits: Limits,
    /// IPC$ serves the srvsvc pipe, so clients can list the shares.
    pub share_listing: bool,
}

pub struct ServerUsers {
    /// Username -> precomputed NT hash record.
    pub table: RwLock<HashMap<String, UserCreds>>,
}

pub struct ServerShares {
    /// Each share by its lowercased name, with its place in the order the
    /// shares were added.
    by_name: RwLock<HashMap<String, (u64, Arc<ShareBindings>)>>,
    next_seq: AtomicU64,
}

impl ServerShares {
    pub fn new(shares: Vec<Arc<ShareBindings>>) -> Self {
        let mut by_name = HashMap::with_capacity(shares.len());
        for (seq, share) in (0..).zip(shares) {
            by_name.insert(share.name.to_ascii_lowercase(), (seq, share));
        }
        Self {
            next_seq: AtomicU64::new(by_name.len() as u64),
            by_name: RwLock::new(by_name),
        }
    }

    pub async fn find(&self, name: &str) -> Option<Arc<ShareBindings>> {
        self.by_name
            .read()
            .await
            .get(&name.to_ascii_lowercase())
            .map(|(_, share)| Arc::clone(share))
    }

    /// Adds `share` after every share there is.
    pub async fn insert(&self, share: Arc<ShareBindings>) -> Result<(), ConfigError> {
        let key = share.name.to_ascii_lowercase();
        let mut by_name = self.by_name.write().await;
        if by_name.contains_key(&key) {
            return Err(ConfigError::DuplicateShare(share.name.clone()));
        }
        let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
        by_name.insert(key, (seq, share));
        Ok(())
    }

    pub async fn remove(&self, name: &str) -> Option<Arc<ShareBindings>> {
        self.by_name
            .write()
            .await
            .remove(&name.to_ascii_lowercase())
            .map(|(_, share)| share)
    }

    pub async fn all(&self) -> Vec<Arc<ShareBindings>> {
        self.by_name
            .read()
            .await
            .values()
            .map(|(_, share)| Arc::clone(share))
            .collect()
    }

    /// Holds the share table for writing, so lookups wait.
    #[cfg(test)]
    pub(crate) async fn hold(
        &self,
    ) -> tokio::sync::RwLockWriteGuard<'_, HashMap<String, (u64, Arc<ShareBindings>)>> {
        self.by_name.write().await
    }

    /// Every share, in the order the shares were added (MS-SRVS 3.1.4.8).
    pub(crate) async fn all_in_order(&self) -> Vec<Arc<ShareBindings>> {
        let mut shares: Vec<_> = self.by_name.read().await.values().cloned().collect();
        shares.sort_unstable_by_key(|(seq, _)| *seq);
        shares.into_iter().map(|(_, share)| share).collect()
    }
}

pub struct ActiveConnections {
    next_id: AtomicU64,
    conns: RwLock<HashMap<u64, Weak<Connection>>>,
}

impl ActiveConnections {
    pub fn new() -> Self {
        Self {
            next_id: AtomicU64::new(1),
            conns: RwLock::new(HashMap::new()),
        }
    }

    pub async fn register(&self, conn: &Arc<Connection>) -> u64 {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        self.conns.write().await.insert(id, Arc::downgrade(conn));
        id
    }

    pub async fn unregister(&self, id: u64) {
        self.conns.write().await.remove(&id);
    }

    pub async fn live(&self) -> Vec<Arc<Connection>> {
        let mut live = Vec::new();
        let mut conns = self.conns.write().await;
        conns.retain(|_, weak| {
            if let Some(conn) = weak.upgrade() {
                live.push(conn);
                true
            } else {
                false
            }
        });
        live
    }
}

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

/// Server state shared across connections.
pub struct ServerState {
    pub config: ServerConfig,
    pub users: ServerUsers,
    pub shares: ServerShares,
    pub active_connections: ActiveConnections,
    /// Notified by `shutdown()`. The accept loop stops; each connection
    /// closes once it has answered the frame it is receiving, if any.
    pub shutdown: Arc<Notify>,
    pub shutting_down: Arc<AtomicBool>,
    /// Signing policy, session and tree limits, and the logon throttle.
    pub auth: crate::auth_policy::AuthPolicy,

    /// Opens one connection may hold at once. CREATE past it fails with
    /// STATUS_INSUFFICIENT_RESOURCES.
    pub max_opens_per_connection: std::sync::atomic::AtomicUsize,
    /// Byte-range locks one open may hold at once. LOCK past it fails with
    /// STATUS_INSUFFICIENT_RESOURCES.
    pub max_locks_per_open: std::sync::atomic::AtomicUsize,
    /// Every lease held on a file of any share.
    pub(crate) leases: Arc<crate::files::LeaseTable>,
    /// Every durable open, and the ones kept after their session ended.
    pub(crate) durable: Arc<DurableTable>,
}

impl ServerState {
    pub fn new(config: ServerConfig, users: ServerUsers, shares: Vec<Arc<ShareBindings>>) -> Self {
        let durable = Arc::new(DurableTable::new(
            config.limits.durable_handle_timeout,
            config.limits.max_disconnected_opens,
        ));
        Self {
            config,
            users,
            shares: ServerShares::new(shares),
            active_connections: ActiveConnections::new(),
            shutdown: Arc::new(Notify::new()),
            shutting_down: Arc::new(AtomicBool::new(false)),
            auth: crate::auth_policy::AuthPolicy::default(),
            max_opens_per_connection: std::sync::atomic::AtomicUsize::new(
                crate::files::DEFAULT_MAX_OPENS_PER_CONNECTION,
            ),
            max_locks_per_open: std::sync::atomic::AtomicUsize::new(
                crate::files::DEFAULT_MAX_LOCKS_PER_OPEN,
            ),
            leases: Arc::default(),
            durable,
        }
    }

    /// The access `caller` gets at TREE_CONNECT to `share`, whose ACL is
    /// `acl`, or `None` when it is refused: the ACL must admit the caller,
    /// and while unencrypted access is refused, a share whose traffic is
    /// encrypted refuses a session that cannot encrypt (MS-SMB2 3.3.5.7).
    pub(crate) fn admits(
        &self,
        share: &ShareBindings,
        acl: &ShareAcl,
        caller: &Caller,
    ) -> Option<Access> {
        let settings = &self.auth.settings;
        if (settings.encrypt_data || share.encrypt_data)
            && settings.reject_unencrypted_access
            && !caller.can_encrypt
        {
            return None;
        }
        acl.authorize(&caller.identity)
    }

    /// Find a share by case-insensitive name.
    pub async fn find_share(&self, name: &str) -> Option<Arc<ShareBindings>> {
        self.shares.find(name).await
    }

    /// Look up a user's NT hash by name.
    pub async fn lookup_user(&self, name: &str) -> Option<UserCreds> {
        self.users.table.read().await.get(name).cloned()
    }

    /// Whether anonymous logon is permitted (i.e. at least one share is public).
    pub async fn anonymous_allowed(&self) -> bool {
        for share in self.shares.all().await {
            let acl = share.acl.read().await;
            if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
                return true;
            }
        }
        false
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum ConfigError {
    #[error("user `{0}` does not exist")]
    UnknownUser(String),
    #[error("share `{0}` does not exist")]
    UnknownShare(String),
    #[error("duplicate share `{0}`")]
    DuplicateShare(String),
    #[error("share `{0}` mixes public mode with explicit users")]
    PublicMixedWithUsers(String),
    #[error("user name `{0}` is reserved")]
    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),
}

#[derive(Clone)]
pub struct ConfigHandle {
    state: Arc<ServerState>,
}

impl ConfigHandle {
    /// Add a user, or replace the password of an existing one. Replacing a
    /// password ends the user's sessions and closes the user's durable
    /// opens kept after their session ended.
    pub async fn add_user(
        &self,
        name: impl Into<String>,
        password: impl AsRef<str>,
    ) -> Result<(), ConfigError> {
        let name = name.into();
        validate_user_name(&name)?;
        let creds = UserCreds::from_password(password.as_ref());
        let replaced = self
            .state
            .users
            .table
            .write()
            .await
            .insert(name.clone(), creds.clone());
        if replaced.is_some_and(|old| old.nt_hash != creds.nt_hash) {
            self.close_user_sessions(&name).await;
        }
        Ok(())
    }

    pub async fn remove_user(&self, name: &str) -> Result<(), ConfigError> {
        validate_user_name(name)?;
        let removed = self.state.users.table.write().await.remove(name);
        if removed.is_none() {
            return Err(ConfigError::UnknownUser(name.to_string()));
        }

        for share in self.state.shares.all().await {
            share.acl.write().await.users.remove(name);
        }

        self.close_user_sessions(name).await;
        Ok(())
    }

    pub async fn add_share(&self, share: Share) -> Result<(), ConfigError> {
        validate_share_name(&share.name)?;
        let is_public = matches!(share.mode, ShareMode::Public | ShareMode::PublicReadOnly);
        if is_public && !share.users.is_empty() {
            return Err(ConfigError::PublicMixedWithUsers(share.name));
        }
        if !valid_remark(&share.remark) {
            return Err(ConfigError::InvalidShareRemark(share.name));
        }
        let users = self.state.users.table.read().await;
        for user in share.users.keys() {
            if !users.contains_key(user) {
                return Err(ConfigError::UnknownUser(user.clone()));
            }
        }

        let binding = ShareBindings::from_share(share);
        self.state.shares.insert(binding).await
    }

    pub async fn remove_share(&self, name: &str) -> Result<(), ConfigError> {
        validate_share_name(name)?;
        let removed = self
            .state
            .shares
            .remove(name)
            .await
            .ok_or_else(|| ConfigError::UnknownShare(name.to_string()))?;

        self.close_share_trees(&removed, None).await;
        Ok(())
    }

    /// Grant `user` `access` to a share. Lowering a user's access ends the
    /// user's trees on the share, so it applies to open connections too, and
    /// closes the user's durable opens on the share kept after their session
    /// ended.
    pub async fn grant_share_user(
        &self,
        share_name: &str,
        user: &str,
        access: Access,
    ) -> Result<(), ConfigError> {
        validate_user_name(user)?;
        validate_share_name(share_name)?;
        let users = self.state.users.table.read().await;
        if !users.contains_key(user) {
            return Err(ConfigError::UnknownUser(user.to_string()));
        }
        drop(users);
        let share = self
            .state
            .find_share(share_name)
            .await
            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
        let mut acl = share.acl.write().await;
        if matches!(acl.mode, ShareMode::Public | ShareMode::PublicReadOnly) {
            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
        }
        let previous = acl.users.insert(user.to_string(), access);
        drop(acl);

        if previous.is_some_and(|old| old.allows_write() && !access.allows_write()) {
            self.close_share_trees(&share, Some(user)).await;
        }
        Ok(())
    }

    pub async fn revoke_share_user(&self, share_name: &str, user: &str) -> Result<(), ConfigError> {
        validate_user_name(user)?;
        validate_share_name(share_name)?;
        let share = self
            .state
            .find_share(share_name)
            .await
            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
        share.acl.write().await.users.remove(user);

        self.close_share_trees(&share, Some(user)).await;
        Ok(())
    }

    pub async fn set_share_mode(
        &self,
        share_name: &str,
        mode: ShareMode,
    ) -> Result<(), ConfigError> {
        validate_share_name(share_name)?;
        let share = self
            .state
            .find_share(share_name)
            .await
            .ok_or_else(|| ConfigError::UnknownShare(share_name.to_string()))?;
        let mut acl = share.acl.write().await;
        if matches!(mode, ShareMode::Public | ShareMode::PublicReadOnly) && !acl.users.is_empty() {
            return Err(ConfigError::PublicMixedWithUsers(share.name.clone()));
        }
        if acl.mode == mode {
            return Ok(());
        }
        acl.mode = mode;
        drop(acl);

        self.close_share_trees(&share, None).await;
        Ok(())
    }

    /// Set how many files and named pipes one connection may hold open at
    /// once. A CREATE past the limit fails with STATUS_INSUFFICIENT_RESOURCES;
    /// opens already held stay open. The default is
    /// [`DEFAULT_MAX_OPENS_PER_CONNECTION`](crate::DEFAULT_MAX_OPENS_PER_CONNECTION).
    pub fn set_max_opens_per_connection(&self, limit: usize) {
        self.state
            .max_opens_per_connection
            .store(limit, Ordering::Relaxed);
    }

    /// Ends every session of `user` on every connection, and closes the
    /// user's durable opens kept after their session ended. All of them are
    /// cut off before any open is closed, and closing waits for requests
    /// still using an open.
    async fn close_user_sessions(&self, user: &str) {
        let mut opens = Vec::new();
        for conn in self.state.active_connections.live().await {
            opens.extend(conn.detach_sessions_for_user(user).await);
        }
        opens.extend(self.state.durable.take_for(None, Some(user)));
        close_opens(opens).await;
    }

    /// Ends the trees on `share`, only those of `user` when given, on every
    /// connection, and closes the matching durable opens kept after their
    /// session ended, cutting all of them off before closing any open.
    async fn close_share_trees(&self, share: &Arc<ShareBindings>, user: Option<&str>) {
        let mut opens = Vec::new();
        for conn in self.state.active_connections.live().await {
            opens.extend(match user {
                Some(user) => conn.detach_trees_for_user_share(user, share).await,
                None => conn.detach_trees_for_share(share).await,
            });
        }
        opens.extend(self.state.durable.take_for(Some(share), user));
        close_opens(opens).await;
    }
}

fn validate_user_name(name: &str) -> Result<(), ConfigError> {
    if name.is_empty() {
        return Err(ConfigError::EmptyUserName);
    }
    if name.eq_ignore_ascii_case("anonymous") {
        return Err(ConfigError::ReservedUserName(name.to_string()));
    }
    Ok(())
}

fn validate_share_name(name: &str) -> Result<(), ConfigError> {
    match check_share_name(name) {
        Ok(()) => Ok(()),
        Err(ShareNameError::Reserved) => Err(ConfigError::ReservedShareName(name.to_string())),
        Err(ShareNameError::Invalid) => Err(ConfigError::InvalidShareName(name.to_string())),
    }
}

// ---------------------------------------------------------------------------
// SmbServer
// ---------------------------------------------------------------------------

/// A built but not-yet-running SMB server.
///
/// Use `serve()` to bind the configured listener and run until shutdown.
pub struct SmbServer {
    state: Arc<ServerState>,
    /// Listener opened by `bind()`, or by `serve()` if `bind()` was not
    /// called.
    bound: tokio::sync::Mutex<Option<TcpListener>>,
    /// Bound address, set by `bind()`.
    local_addr: tokio::sync::Mutex<Option<SocketAddr>>,
}

impl SmbServer {
    pub fn builder() -> SmbServerBuilder {
        SmbServerBuilder::default()
    }

    pub(crate) fn from_state(state: ServerState) -> Self {
        Self {
            state: Arc::new(state),
            bound: tokio::sync::Mutex::new(None),
            local_addr: tokio::sync::Mutex::new(None),
        }
    }

    pub fn config_handle(&self) -> ConfigHandle {
        ConfigHandle {
            state: self.state.clone(),
        }
    }

    /// Bind the listen address without starting the accept loop. Returns
    /// the bound address, which gives the real port when the configured port
    /// is 0.
    pub async fn bind(&self) -> io::Result<SocketAddr> {
        let mut bound = self.bound.lock().await;
        if let Some(l) = bound.as_ref() {
            return l.local_addr();
        }
        let listener = TcpListener::bind(self.state.config.listen_addr).await?;
        let addr = listener.local_addr()?;
        *bound = Some(listener);
        *self.local_addr.lock().await = Some(addr);
        Ok(addr)
    }

    /// Returns the actual bound address. `None` if `bind()`/`serve()` have
    /// not yet been called.
    pub async fn local_addr(&self) -> Option<SocketAddr> {
        *self.local_addr.lock().await
    }

    /// Listen address as configured. Use `local_addr()` for the bound
    /// address.
    pub fn configured_addr(&self) -> SocketAddr {
        self.state.config.listen_addr
    }

    /// Initiate a graceful shutdown. Stops the accept loop and closes each
    /// connection once its current request is answered. Takes effect even
    /// when called before `serve()`.
    pub fn shutdown(&self) {
        self.state.shutting_down.store(true, Ordering::Release);
        self.state.shutdown.notify_waiters();
    }

    /// Returns a clonable handle that can request shutdown after `serve()`
    /// has consumed the `SmbServer` value.
    pub fn shutdown_handle(&self) -> ShutdownHandle {
        ShutdownHandle {
            shutdown: self.state.shutdown.clone(),
            shutting_down: self.state.shutting_down.clone(),
        }
    }

    /// Run the accept loop until `shutdown()` is called. Returns once every
    /// connection has closed and every durable open kept after its session
    /// ended is closed, including closes that expiry or a lease break had
    /// already started.
    pub async fn serve(self) -> io::Result<()> {
        if self.bound.lock().await.is_none() {
            self.bind().await?;
        }
        let listener = self
            .bound
            .lock()
            .await
            .take()
            .expect("listener bound above");
        let local = listener.local_addr().ok();
        let span = info_span!("smb_server", listen = ?local);
        async move {
            info!("server starting");
            let state = self.state.clone();
            let shutdown = state.shutdown.clone();
            let shutting_down = state.shutting_down.clone();
            let mut backoff = AcceptBackoff::new();
            let mut connections = JoinSet::new();
            let limits = &state.config.limits;
            let slots = Arc::new(Semaphore::new(
                limits.max_connections.min(Semaphore::MAX_PERMITS),
            ));
            let mut at_capacity = false;

            loop {
                let stopped = shutdown.notified();
                tokio::pin!(stopped);
                stopped.as_mut().enable();
                if shutting_down.load(Ordering::Acquire) {
                    info!("shutdown requested; stopping accept loop");
                    break;
                }
                let retry_after = tokio::select! {
                    biased;
                    _ = &mut stopped => {
                        info!("shutdown requested; stopping accept loop");
                        break;
                    }
                    Some(_) = connections.join_next(), if !connections.is_empty() => None,
                    accept = listener.accept() => {
                        match accept {
                            Ok((stream, peer)) => {
                                backoff.succeeded();
                                if shutting_down.load(Ordering::Acquire) {
                                    drop(stream);
                                    break;
                                }
                                let Ok(slot) = slots.clone().try_acquire_owned() else {
                                    if !at_capacity {
                                        warn!(
                                            max = limits.max_connections,
                                            "connection limit reached; closing new connections"
                                        );
                                        at_capacity = true;
                                    }
                                    debug!(%peer, "connection refused: limit reached");
                                    drop(stream);
                                    continue;
                                };
                                if at_capacity {
                                    info!("below the connection limit again");
                                    at_capacity = false;
                                }
                                configure_socket(&stream, limits.tcp_keepalive);
                                let server_state = state.clone();
                                let span = info_span!("conn", peer = %peer);
                                connections.spawn(async move {
                                    let _slot = slot;
                                    if let Err(e) = connection_loop(stream, peer, server_state).await {
                                        error!(error = %e, "connection loop exited with error");
                                    }
                                }.instrument(span));
                                None
                            }
                            Err(e) => {
                                if shutting_down.load(Ordering::Acquire) {
                                    break;
                                }
                                Some(backoff.failed(&e))
                            }
                        }
                    }
                };
                if let Some(delay) = retry_after {
                    tokio::select! {
                        biased;
                        _ = &mut stopped => {
                            info!("shutdown requested; stopping accept loop");
                            break;
                        }
                        _ = tokio::time::sleep(delay) => {}
                    }
                }
            }
            drop(listener);
            if !connections.is_empty() {
                info!(open = connections.len(), "waiting for connections to close");
            }
            while connections.join_next().await.is_some() {}
            close_opens(state.durable.take_for(None, None)).await;
            state.durable.closed().await;
            info!("server stopped");
            Ok::<(), io::Error>(())
        }
        .instrument(span)
        .await
    }

    #[cfg(any(test, fuzzing))]
    pub(crate) fn state(&self) -> Arc<ServerState> {
        self.state.clone()
    }
}

/// Cheaply-clonable shutdown handle. Outlives `SmbServer::serve` consuming
/// the server.
#[derive(Clone)]
pub struct ShutdownHandle {
    shutdown: Arc<Notify>,
    shutting_down: Arc<AtomicBool>,
}

impl ShutdownHandle {
    /// Request a graceful shutdown.
    pub fn shutdown(&self) {
        self.shutting_down.store(true, Ordering::Release);
        self.shutdown.notify_waiters();
    }
}