smb-server 0.9.1

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
//! State of open files shared by every connection, and closing an open.

mod durable;
mod lease;
mod leases;
mod table;
mod watch;

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use tokio::sync::RwLock;
use tracing::debug;

use crate::access_mask::{FILE_APPEND_DATA, FILE_WRITE_DATA};
use crate::backend::{FileInfo, Handle};
use crate::conn::state::Open;
use crate::handlers::shared::restore_fixed_times;
use crate::ntstatus;
use crate::proto::messages::change_notify::{FILE_ACTION_MODIFIED, FILE_ACTION_MODIFIED_STREAM};
use crate::stream::data_stream_info;

pub(crate) use durable::{Claim, Durability, DurableReg, DurableTable, Unclaimed, v2_timeout};
pub use durable::{DEFAULT_DURABLE_HANDLE_TIMEOUT, DEFAULT_MAX_DISCONNECTED_OPENS};
pub(crate) use lease::{Granted, LeaseId, LeaseRequest, LeaseState, LeaseVersion, Trigger};
#[cfg(test)]
pub(crate) use leases::LEASE_BREAK_TIMEOUT;
pub(crate) use leases::{AfterSend, BreakWait, LeaseRef, LeaseTable, MAX_BREAK_WAIT};
pub(crate) use table::{FileRef, FileTable, OpenRequest, Refused, Sharing};
#[cfg(test)]
pub(crate) use watch::MAX_WATCHES_PER_CONNECTION;
pub(crate) use watch::{
    Answer, CONTENT_CHANGED, Change, EA_CHANGED, NotifyBudget, STREAM_BASE_CHANGED, STREAM_CHANGED,
    WatchReg, WatchTable,
};

/// Default for
/// [`SmbServerBuilder::max_opens_per_connection`](crate::SmbServerBuilder::max_opens_per_connection)
/// and
/// [`ConfigHandle::set_max_opens_per_connection`](crate::ConfigHandle::set_max_opens_per_connection).
pub const DEFAULT_MAX_OPENS_PER_CONNECTION: usize = 16384;

/// Default for
/// [`SmbServerBuilder::max_locks_per_open`](crate::SmbServerBuilder::max_locks_per_open).
pub const DEFAULT_MAX_LOCKS_PER_OPEN: usize = 1024;

/// What a closing open did to its file: whether its close reports new
/// contents, and which of the backend's reports of the close it hides.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Closing {
    /// The open could not write the file's data.
    ReadOnly,
    /// The open could write the file's data, or created or overwrote it,
    /// and wrote nothing.
    Unwritten,
    /// The open sets times it fixed again as it closes.
    RestoresTimes,
    /// A WRITE through the open changed the file.
    Wrote,
    /// A WRITE through the open changed the named stream it is on, or the
    /// open moved the file's data into it (`moved`).
    StreamWrote { moved: bool },
    /// The named stream the open is on was overwritten or resized through
    /// it, and not written.
    StreamResized,
}

impl Closing {
    /// How `open` closes; `restores_times` when the close sets the times
    /// the open fixed again. The share's watches are told before the close
    /// touches the file, so the backend's reports of it are left out
    /// whenever they arrive.
    pub(crate) fn announce(open: &Open, restores_times: bool) -> Self {
        let fixed = open.fixed_times;
        let wrote = open.wrote.load(Ordering::Acquire);
        let closing = if open.on_stream {
            if wrote || open.moved_data {
                Self::StreamWrote {
                    moved: open.moved_data,
                }
            } else if open.resized.load(Ordering::Acquire) {
                Self::StreamResized
            } else {
                Self::ReadOnly
            }
        } else if wrote {
            Self::Wrote
        } else if restores_times
            && (fixed.last_access_time.is_some() || fixed.last_write_time.is_some())
        {
            Self::RestoresTimes
        } else if !open.is_directory
            && (open.created || open.granted_access & (FILE_WRITE_DATA | FILE_APPEND_DATA) != 0)
        {
            Self::Unwritten
        } else {
            Self::ReadOnly
        };
        if let Some(file) = &open.file {
            let watches = &file.share().watches;
            match closing {
                _ if open.eas_changed.load(Ordering::Acquire) => watches.touch(&file.path()),
                Self::ReadOnly => {}
                Self::Unwritten => watches.closed(&file.path()),
                Self::RestoresTimes
                | Self::Wrote
                | Self::StreamWrote { .. }
                | Self::StreamResized => watches.touch(&file.path()),
            }
        }
        closing
    }
}

/// Counts one open against its connection's limit until dropped.
pub(crate) struct OpenSlot(Arc<AtomicUsize>);

impl OpenSlot {
    /// Takes a slot from `count`, or `None` when `limit` slots are taken.
    pub(crate) fn acquire(count: &Arc<AtomicUsize>, limit: usize) -> Option<Self> {
        count
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| {
                (n < limit).then_some(n + 1)
            })
            .ok()
            .map(|_| Self(Arc::clone(count)))
    }
}

impl Drop for OpenSlot {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::AcqRel);
    }
}

/// Closes an open that is no longer reachable by FileId (MS-SMB2 3.3.4.17,
/// MS-FSA 2.1.5.5): ends the change notification watch still on it,
/// restores the times it fixed, closes the backend handle, drops its
/// byte-range locks and removes the file when this was the last open of a
/// delete-pending file.
/// With `want_attrs`, returns the file's attributes as they were before the
/// handle closed. Waits for requests still using the open.
pub(crate) async fn close_open(open_arc: &Arc<RwLock<Open>>, want_attrs: bool) -> Option<FileInfo> {
    let mut open = open_arc.write().await;
    // Requests waiting on the watch end with STATUS_NOTIFY_CLEANUP before
    // the close reports anything (MS-SMB2 3.3.5.10). CLOSE takes the watch
    // out first and ends it once its response is queued.
    drop(open.watch.take());
    let closing = Closing::announce(&open, true);
    let eas_changed = open.eas_changed.load(Ordering::Acquire);
    restore_fixed_times(&open).await;
    let handle = open.handle.take();
    let file = open.file.take();
    if handle.is_none() && file.is_none() {
        return None;
    }
    let info = match &handle {
        Some(handle) if want_attrs => handle.stat().await.ok(),
        _ => None,
    };
    let info = match info {
        Some(info) if open.on_stream => Some(data_stream_info(info)),
        info => info,
    };
    open.slot.take();
    let delete_on_close = open.delete_on_close;
    let is_directory = open.is_directory;
    drop(open);
    finish_close(
        handle,
        file,
        delete_on_close,
        is_directory,
        closing,
        eas_changed,
    )
    .await;
    info
}

/// Closes the backend handle of an open and takes the open out of its
/// share's file table. With `delete_on_close` the file becomes
/// delete-pending, unless it is a directory with entries (MS-FSA 2.1.5.5
/// phase 1), and is removed when this was its last open. An open that
/// wrote and leaves the file in place reports the new contents to the
/// share's watchers, once, one that set extended attributes
/// (`eas_changed`) reports that, and one that changed or deleted the named
/// stream it is on reports that. A directory this leaves delete-pending, open
/// elsewhere, ends its watches with STATUS_DELETE_PENDING. Every path that
/// ends an open goes through here.
pub(crate) async fn finish_close(
    handle: Option<Box<dyn Handle>>,
    file: Option<FileRef>,
    delete_on_close: bool,
    is_directory: bool,
    closing: Closing,
    eas_changed: bool,
) {
    // A close reports new contents of the file, new extended attributes
    // and a change of the named stream the open is on. Deleting on close a
    // stream not yet marked for deletion counts as a change of the stream.
    let contents = match closing {
        Closing::Wrote | Closing::StreamWrote { moved: true } => CONTENT_CHANGED,
        Closing::StreamWrote { moved: false } => STREAM_BASE_CHANGED,
        _ => 0,
    };
    let filter = contents | if eas_changed { EA_CHANGED } else { 0 };
    let file_filter = (filter != 0).then_some(filter);
    let on_stream = file.as_ref().is_some_and(|f| f.stream().is_some());
    let deletes = delete_on_close && !file.as_ref().is_some_and(FileRef::stream_delete_pending);
    let stream_changed = on_stream
        && (deletes
            || matches!(
                closing,
                Closing::StreamWrote { .. } | Closing::StreamResized
            ));
    let share = file.as_ref().map(|f| Arc::clone(f.share()));
    // A directory is checked for entries and marked with no CREATE or
    // rename running, so it is still empty when it becomes delete-pending.
    let exclusive = match &share {
        Some(share) if delete_on_close && is_directory => Some(share.files.rename_lock().await),
        _ => None,
    };
    let delete_on_close = delete_on_close
        && (!is_directory
            || match &handle {
                Some(handle) => handle.dir_is_empty().await.unwrap_or(false),
                None => false,
            });
    if let Some(handle) = handle
        && let Err(e) = handle.close().await
    {
        let path = file.as_ref().map(FileRef::path).unwrap_or_default();
        debug!(error = %e, path = %path, "backend close failed");
    }
    let (Some(file), Some(share)) = (file, &share) else {
        return;
    };
    // A directory that stays delete-pending, open elsewhere, ends its
    // watches under each of its names, as FileDispositionInformation would.
    let marks_deleted = delete_on_close && is_directory;
    let marked = if marks_deleted {
        file.open_paths()
    } else {
        Vec::new()
    };
    // The name is read and reported with no rename in between, when anyone
    // on the share may hear it.
    let reports = file_filter.is_some() || stream_changed;
    let names = if exclusive.is_none() && reports && !share.watches.is_empty() {
        Some(share.files.names_lock().await)
    } else {
        None
    };
    let heard = names.is_some() || exclusive.is_some();
    let path = file.path();
    let stream = file.stream();
    let mut changes = Vec::new();
    if let Some(filter) = file_filter {
        changes.push(Change {
            path: &path,
            stream: None,
            action: FILE_ACTION_MODIFIED,
            filter,
            seen: true,
        });
    }
    if stream_changed {
        changes.push(Change {
            path: &path,
            stream: stream.as_ref(),
            action: FILE_ACTION_MODIFIED_STREAM,
            filter: STREAM_CHANGED,
            seen: false,
        });
    }
    match file.release(delete_on_close) {
        Some(pending) => {
            // The removal of a file reports itself; that of a stream does
            // not.
            if heard && pending.is_stream() && !changes.is_empty() {
                share.watches.report(&changes);
            }
            drop(names);
            drop(exclusive);
            pending.run().await;
        }
        None => {
            if heard && !changes.is_empty() {
                share.watches.report(&changes);
            }
            for path in &marked {
                share.watches.end_at(path, ntstatus::STATUS_DELETE_PENDING);
            }
        }
    }
}

/// Closes every open in `opens`, each on its own task, so one that waits
/// for a slow request does not hold up the others. Returns once all are
/// closed; the tasks finish even if the caller stops waiting.
pub(crate) async fn close_opens(opens: Vec<Arc<RwLock<Open>>>) {
    end_opens(opens, None).await;
}

/// Ends the opens of a session that is going away, each on its own task as
/// [`close_opens`] does. With `keep`, a durable open that qualifies stays
/// in that table for its client (MS-SMB2 3.3.7.1, 3.3.5.6); every other
/// open is closed. `keep` carries the table's [`DurableTable::sweeps`]
/// from before the session left its connection.
pub(crate) async fn end_opens(
    opens: Vec<Arc<RwLock<Open>>>,
    keep: Option<(&Arc<DurableTable>, u64)>,
) {
    let tasks: Vec<_> = opens
        .into_iter()
        .map(|open| {
            let keep = keep.map(|(table, since)| (Arc::clone(table), since));
            tokio::spawn(async move {
                let open = match keep {
                    Some((table, since)) => table.preserve(open, since).await,
                    None => Some(open),
                };
                if let Some(open) = open {
                    close_open(&open, false).await;
                }
            })
        })
        .collect();
    for task in tasks {
        let _ = task.await;
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;
    use crate::access_mask::DELETE;
    use crate::backend::{FileTimes, OpenIntent, OpenOptions};
    use crate::builder::Access;
    use crate::conn::state::{Connection, Session, TreeConnect};
    use crate::error::SmbError;
    use crate::path::SmbPath;
    use crate::proto::auth::ntlm::Identity;
    use crate::proto::messages::FileId;
    use crate::server::{ShareBindings, ShareMode};
    use crate::tests::memfs::MemFsBackend;

    fn share() -> Arc<ShareBindings> {
        share_on(MemFsBackend::new())
    }

    fn share_on(backend: MemFsBackend) -> Arc<ShareBindings> {
        ShareBindings::new(
            "s".to_string(),
            Arc::new(backend),
            ShareMode::Public,
            HashMap::new(),
            false,
            true,
            true,
        )
    }

    /// Opens `path` with FILE_DELETE_ON_CLOSE, creating it if needed, and
    /// drops the open without a CLOSE.
    async fn drop_without_close(
        share: &Arc<ShareBindings>,
        path: &str,
        directory: bool,
    ) -> SmbPath {
        let path: SmbPath = path.parse().unwrap();
        let opts = OpenOptions {
            directory,
            intent: OpenIntent::OpenOrCreate,
            ..OpenOptions::default()
        };
        let (handle, _) = share.backend.open(&path, opts).await.unwrap();
        let info = handle.stat().await.unwrap();
        let sharing = Sharing {
            access: DELETE,
            share: 0,
        };
        let file = FileRef::register(share, &info, &path, sharing.into())
            .unwrap()
            .0;
        drop(Open {
            file_id: FileId::default(),
            handle: Some(handle),
            granted_access: DELETE,
            is_directory: directory,
            on_stream: false,
            delete_on_close: true,
            search_state: None,
            fixed_times: FileTimes::default(),
            create_options: 0,
            file: Some(file),
            slot: None,
            durable: None,
            watch: None,
            wrote: Default::default(),
            created: false,
            marked_deleted: Default::default(),
            ea_cursor: Default::default(),
            eas_changed: Default::default(),
            resized: Default::default(),
            moved_data: false,
        });
        let in_table = || {
            share.files.path_is_open(&path, false) || share.files.delete_pending_at(&path, false)
        };
        for _ in 0..100 {
            if !in_table() {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert!(!in_table());
        path
    }

    #[tokio::test]
    async fn a_dropped_delete_on_close_open_removes_the_file() {
        let s = share();
        let path = drop_without_close(&s, "f", false).await;
        let missing = s.backend.open(&path, OpenOptions::default()).await;
        assert!(matches!(missing, Err(SmbError::NotFound)));
    }

    #[tokio::test]
    async fn a_dropped_delete_on_close_open_keeps_a_directory_with_entries() {
        let s = share_on(MemFsBackend::new().with_file("d\\f", b"x"));
        let path = drop_without_close(&s, "d", true).await;
        let opts = OpenOptions {
            directory: true,
            ..OpenOptions::default()
        };
        assert!(s.backend.open(&path, opts).await.is_ok());
    }

    #[tokio::test]
    async fn sweeps_match_the_share_not_its_name() {
        let removed = share();
        let added = share();
        let conn = Connection::new(uuid::Uuid::nil(), 1 << 16, 1 << 16);
        let session = Session::new(Identity::Anonymous, [0; 16], [0; 16], false, None);
        let tree = TreeConnect::new(1, Arc::clone(&added), Access::ReadWrite);
        session
            .trees
            .write()
            .await
            .insert(1, Arc::new(RwLock::new(tree)));
        let session = Arc::new(RwLock::new(session));
        conn.sessions.write().await.insert(1, Arc::clone(&session));

        assert!(conn.detach_trees_for_share(&removed).await.is_empty());
        assert_eq!(session.read().await.trees.read().await.len(), 1);
        conn.detach_trees_for_share(&added).await;
        assert!(session.read().await.trees.read().await.is_empty());
    }
}