Skip to main content

smb_server/
backend.rs

1//! `ShareBackend` and `Handle` traits: the storage abstraction.
2//!
3//! Implementors of these traits plug into `Share::new(name, backend)`. The
4//! protocol layer never exposes raw FS types to backends; everything goes
5//! through validated `SmbPath`s and the small structs below.
6
7use async_trait::async_trait;
8use std::time::SystemTime;
9
10use crate::ea::Ea;
11use crate::error::{SmbError, SmbResult};
12use crate::path::SmbPath;
13use crate::stream::{StreamInfo, StreamName};
14
15// ---------------------------------------------------------------------------
16// OpenOptions
17// ---------------------------------------------------------------------------
18
19/// SMB CREATE disposition as seen by a backend.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum OpenIntent {
23    /// `FILE_OPEN`: open existing only; fail if missing.
24    Open,
25    /// `FILE_CREATE`: create new only; fail if exists.
26    Create,
27    /// `FILE_OPEN_IF`: open existing or create new.
28    OpenOrCreate,
29    /// `FILE_OVERWRITE_IF`: open existing (truncating) or create new.
30    OverwriteOrCreate,
31    /// `FILE_OVERWRITE`: open existing and truncate; fail if missing.
32    Truncate,
33}
34
35/// Options passed to `ShareBackend::open`.
36#[derive(Debug, Clone, Copy)]
37pub struct OpenOptions {
38    /// The open was granted `FILE_READ_DATA`, or has no data write access.
39    /// At least one of `read` and `write` is set.
40    pub read: bool,
41    /// The open was granted `FILE_WRITE_DATA` or `FILE_APPEND_DATA`.
42    pub write: bool,
43    /// The open was granted `FILE_WRITE_ATTRIBUTES`: the handle must be able
44    /// to change times and attributes, including on a read-only file.
45    pub write_attributes: bool,
46    /// CREATE disposition.
47    pub intent: OpenIntent,
48    /// `FILE_DIRECTORY_FILE` was set on CREATE, or the name ended in
49    /// `::$INDEX_ALLOCATION`: open or create a directory.
50    pub directory: bool,
51    /// `FILE_NON_DIRECTORY_FILE` was set on CREATE, or the name ended in
52    /// `::$DATA`: fail if the target is a directory.
53    pub non_directory: bool,
54    /// `FILE_DELETE_ON_CLOSE` was set on CREATE.
55    pub delete_on_close: bool,
56}
57
58impl Default for OpenOptions {
59    fn default() -> Self {
60        Self {
61            read: true,
62            write: false,
63            write_attributes: false,
64            intent: OpenIntent::Open,
65            directory: false,
66            non_directory: false,
67            delete_on_close: false,
68        }
69    }
70}
71
72/// What `ShareBackend::open` did to the file (MS-SMB2 2.2.14 CreateAction).
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum OpenAction {
75    /// An existing file or directory was opened.
76    Opened,
77    /// A new file or directory was created.
78    Created,
79    /// An existing file was truncated to zero length, as
80    /// [`OpenIntent::Truncate`] and [`OpenIntent::OverwriteOrCreate`] do.
81    Overwritten,
82}
83
84// ---------------------------------------------------------------------------
85// FileInfo / DirEntry / FileTimes
86// ---------------------------------------------------------------------------
87
88/// Filesystem-style metadata for a single file or directory. Built with
89/// [`FileInfo::new`]; every field is public.
90#[derive(Debug, Clone)]
91#[non_exhaustive]
92pub struct FileInfo {
93    /// Display name (last component). For QUERY_INFO at the share root this
94    /// is the share name.
95    pub name: String,
96    /// File size in bytes. The server reports a directory with a size of
97    /// 0 whatever this says.
98    pub end_of_file: u64,
99    /// Allocation size, usually `end_of_file` rounded up to a cluster.
100    /// Backends may return `end_of_file`. The server reports 0 for a
101    /// directory.
102    pub allocation_size: u64,
103    /// FILETIME (100ns ticks since 1601).
104    pub creation_time: u64,
105    pub last_access_time: u64,
106    pub last_write_time: u64,
107    pub change_time: u64,
108    /// True if this is a directory.
109    pub is_directory: bool,
110    /// The file has `FILE_ATTRIBUTE_READONLY`.
111    pub read_only: bool,
112    /// Stable id of the file, unique within the share including any mounts
113    /// below the share root, reported as the file id by QUERY_INFO and
114    /// QUERY_DIRECTORY. Backends return the same value from `Handle::stat`
115    /// and `Handle::list_dir` for the same file, across opens and renames.
116    /// `0` if the backend has none; the server then tells files apart by
117    /// path, so a file reached through two hard links counts as two files:
118    /// share modes, byte-range locks and leases taken through one name do
119    /// not see opens through the other, and clients on the two names can
120    /// both cache writes to it.
121    pub file_index: u64,
122    /// POSIX mode of the file, file type bits included, as `st_mode` has
123    /// it. Directory listings give macOS clients that negotiated Apple's
124    /// extensions its low 16 bits. `None` where the host has no modes.
125    pub unix_mode: Option<u32>,
126    /// Bytes the file's extended attributes take as FILE_FULL_EA_INFORMATION
127    /// entries of what [`Handle::eas`] returns, each 8 bytes, the name, a
128    /// NUL and the value, padded to 4 bytes. `0` when it has none or the
129    /// backend does not report [`BackendCapabilities::extended_attributes`].
130    /// FileEaInformation, FileAllInformation and directory listings report
131    /// it as EaSize; on an open of a named stream, the file's.
132    pub ea_size: u32,
133    /// The file's other attributes (MS-FSCC 2.6) as the backend stores
134    /// them: any of `FILE_ATTRIBUTE_HIDDEN`, `SYSTEM`, `ARCHIVE`,
135    /// `TEMPORARY`, `OFFLINE` and `NOT_CONTENT_INDEXED`. Other flags here
136    /// are ignored: `read_only` and `is_directory` give READONLY and
137    /// DIRECTORY. `0` for a backend that stores none of them.
138    pub file_attributes: u32,
139}
140
141// File attributes (MS-FSCC 2.6).
142pub(crate) const FILE_ATTRIBUTE_READONLY: u32 = 0x0000_0001;
143pub(crate) const FILE_ATTRIBUTE_HIDDEN: u32 = 0x0000_0002;
144pub(crate) const FILE_ATTRIBUTE_SYSTEM: u32 = 0x0000_0004;
145pub(crate) const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
146pub(crate) const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x0000_0020;
147pub(crate) const FILE_ATTRIBUTE_NORMAL: u32 = 0x0000_0080;
148pub(crate) const FILE_ATTRIBUTE_TEMPORARY: u32 = 0x0000_0100;
149pub(crate) const FILE_ATTRIBUTE_OFFLINE: u32 = 0x0000_1000;
150pub(crate) const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: u32 = 0x0000_2000;
151
152/// Attributes [`FileInfo::file_attributes`] carries.
153const OTHER_ATTRIBUTES: u32 = FILE_ATTRIBUTE_HIDDEN
154    | FILE_ATTRIBUTE_SYSTEM
155    | FILE_ATTRIBUTE_ARCHIVE
156    | FILE_ATTRIBUTE_TEMPORARY
157    | FILE_ATTRIBUTE_OFFLINE
158    | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
159
160/// Attributes FileBasicInformation can set (MS-FSA 2.1.5.15.2).
161pub(crate) const VALID_SET_ATTRIBUTES: u32 = FILE_ATTRIBUTE_READONLY | OTHER_ATTRIBUTES;
162
163impl FileInfo {
164    /// A zero-length, writable file named `name` with no times and no file
165    /// id. Set the fields the backend knows.
166    pub fn new(name: impl Into<String>) -> Self {
167        Self {
168            name: name.into(),
169            end_of_file: 0,
170            allocation_size: 0,
171            creation_time: 0,
172            last_access_time: 0,
173            last_write_time: 0,
174            change_time: 0,
175            is_directory: false,
176            read_only: false,
177            file_index: 0,
178            unix_mode: None,
179            ea_size: 0,
180            file_attributes: 0,
181        }
182    }
183
184    /// SMB2 file attributes (MS-FSCC 2.6) for this file:
185    /// `FILE_ATTRIBUTE_DIRECTORY` for directories,
186    /// `FILE_ATTRIBUTE_READONLY` for read-only files, and the flags of
187    /// [`FileInfo::file_attributes`]. `FILE_ATTRIBUTE_NORMAL` stands alone
188    /// when none applies.
189    pub fn attributes(&self) -> u32 {
190        let mut attributes = self.file_attributes & OTHER_ATTRIBUTES;
191        if self.is_directory {
192            attributes |= FILE_ATTRIBUTE_DIRECTORY;
193        }
194        if self.read_only {
195            attributes |= FILE_ATTRIBUTE_READONLY;
196        }
197        if attributes == 0 {
198            FILE_ATTRIBUTE_NORMAL
199        } else {
200            attributes
201        }
202    }
203
204    /// EndOfFile and AllocationSize as the server reports them: 0 for a
205    /// directory, which has no data of its own.
206    pub(crate) fn sizes(&self) -> (u64, u64) {
207        if self.is_directory {
208            (0, 0)
209        } else {
210            (self.end_of_file, self.allocation_size)
211        }
212    }
213}
214
215/// One entry of a directory listing.
216#[derive(Debug, Clone)]
217pub struct DirEntry {
218    pub info: FileInfo,
219}
220
221/// Optional FILETIME values for `set_times`. `None` means "leave unchanged".
222#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
223pub struct FileTimes {
224    pub creation_time: Option<u64>,
225    pub last_access_time: Option<u64>,
226    pub last_write_time: Option<u64>,
227    pub change_time: Option<u64>,
228}
229
230impl FileTimes {
231    /// `FileTimes` with all four fields set to `t`.
232    pub fn all(t: SystemTime) -> Self {
233        let ft = crate::utils::system_time_to_filetime(t);
234        Self {
235            creation_time: Some(ft),
236            last_access_time: Some(ft),
237            last_write_time: Some(ft),
238            change_time: Some(ft),
239        }
240    }
241}
242
243// ---------------------------------------------------------------------------
244// BackendCapabilities
245// ---------------------------------------------------------------------------
246
247/// Static, advertised capabilities of a backend. Built from
248/// [`BackendCapabilities::default`]; every field is public.
249#[derive(Debug, Clone, Copy, Default)]
250#[non_exhaustive]
251pub struct BackendCapabilities {
252    /// If true, all write-class operations are denied at the protocol layer
253    /// before reaching the backend (matches `LocalFsBackend::read_only()`).
254    pub is_read_only: bool,
255    /// True iff the backend treats names case-sensitively.
256    pub case_sensitive: bool,
257    /// The backend stores named streams (`file.txt:name`), served by
258    /// [`ShareBackend::open_stream`], [`ShareBackend::remove_stream`],
259    /// [`ShareBackend::rename_stream`] and [`Handle::streams`]. On a share
260    /// that leaves [`Share::named_streams`](crate::Share::named_streams) on,
261    /// FileFsAttributeInformation then reports FILE_NAMED_STREAMS. Without
262    /// it, a CREATE that names a stream fails with
263    /// STATUS_OBJECT_NAME_INVALID before the backend is called.
264    pub named_streams: bool,
265    /// The backend stores extended attributes of files and directories,
266    /// served by [`Handle::eas`] and [`Handle::set_eas`]. On a share that
267    /// leaves
268    /// [`Share::extended_attributes`](crate::Share::extended_attributes)
269    /// on, FileFsAttributeInformation then reports
270    /// FILE_SUPPORTS_EXTENDED_ATTRIBUTES. Without it, the share answers as
271    /// [`Share::extended_attributes`](crate::Share::extended_attributes)
272    /// describes for a share that turns them off.
273    pub extended_attributes: bool,
274    /// The backend can make a range of one file share its storage with a
275    /// range of another file on the same volume, served by
276    /// [`ShareBackend::clone_range`]. On a share that leaves
277    /// [`Share::server_side_copy`](crate::Share::server_side_copy) on,
278    /// FileFsAttributeInformation then reports
279    /// FILE_SUPPORTS_BLOCK_REFCOUNTING and FSCTL_DUPLICATE_EXTENTS_TO_FILE
280    /// reaches the backend. Without it, that FSCTL fails with
281    /// STATUS_INVALID_DEVICE_REQUEST.
282    pub block_cloning: bool,
283}
284
285// ---------------------------------------------------------------------------
286// Traits
287// ---------------------------------------------------------------------------
288
289/// Pluggable storage backend mounted as a share.
290///
291/// Implementors must be `Send + Sync + 'static` so the server can spawn
292/// per-request handlers freely.
293#[async_trait]
294pub trait ShareBackend: Send + Sync + 'static {
295    /// Open or create a file or directory. Returns a fresh handle and what
296    /// the open did to the file.
297    ///
298    /// Fail with [`SmbError::PathNotFound`] when a directory on the way to
299    /// `path` is missing and [`SmbError::NotFound`] when only the last
300    /// component is.
301    ///
302    /// A new entry is stored under the spelling of the last name of `path`.
303    ///
304    /// A backend that reports [`BackendCapabilities::named_streams`] keeps
305    /// the named streams of a file that [`OpenIntent::Truncate`] or
306    /// [`OpenIntent::OverwriteOrCreate`] overwrites: the protocol layer
307    /// removes them with [`ShareBackend::remove_stream`], each once no open
308    /// is on it. `unlink` removes them with the file, and `rename` keeps
309    /// them with it.
310    async fn open(
311        &self,
312        path: &SmbPath,
313        opts: OpenOptions,
314    ) -> SmbResult<(Box<dyn Handle>, OpenAction)>;
315
316    /// Delete a file or an empty directory.
317    async fn unlink(&self, path: &SmbPath) -> SmbResult<()>;
318
319    /// Rename `from` to `to`.
320    ///
321    /// If `to` names an existing file or directory other than `from`,
322    /// including another hard link to the same file, fail with
323    /// [`SmbError::Exists`] unless `replace_if_exists` is set. With it set,
324    /// an existing file is replaced; an existing directory is never
325    /// replaced: fail with [`SmbError::AccessDenied`] (MS-FSA 2.1.5.15.12).
326    ///
327    /// A rename gives the entry the spelling of `to`, also when only the
328    /// case changes. A rename that replaces an entry spelled differently,
329    /// or that names its own path, may keep the stored spelling.
330    async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()>;
331
332    /// Static capabilities. TREE_CONNECT clamps access to read-only when
333    /// `is_read_only` is set.
334    fn capabilities(&self) -> BackendCapabilities;
335
336    /// Size, free space and identity of the volume behind the share, for the
337    /// filesystem QUERY_INFO classes. The default returns
338    /// [`VolumeInfo::default`].
339    async fn volume_info(&self) -> SmbResult<VolumeInfo> {
340        Ok(VolumeInfo::default())
341    }
342
343    /// Open or create the named stream `stream` of the file or directory at
344    /// `path`. `file` is the handle `open` just gave for `path`, opened for
345    /// reading. The backend owns it and closes it, also when this fails; it
346    /// may keep it for as long as the stream's handle lasts, so the stream
347    /// follows the file through renames. `opts.intent` applies to the
348    /// stream; `opts.directory` and `opts.non_directory` are false. The
349    /// handle reads and writes the stream: its `stat` reports the file's
350    /// times, attributes and id with the stream's sizes, `set_times` and
351    /// `set_attributes` change the file, and `truncate` the stream. A
352    /// write or size change of the stream updates the file's last write
353    /// time, which the protocol layer reports as a change of the file.
354    ///
355    /// Stream names compare without regard to case: an existing stream
356    /// opens under any spelling of its name, and a new one keeps the
357    /// spelling of `stream`. An open that would write or create a stream of
358    /// a read-only file fails with STATUS_ACCESS_DENIED before this is
359    /// called.
360    ///
361    /// Called only when [`BackendCapabilities::named_streams`] is set. The
362    /// protocol layer answers [`SmbError::NotSupported`] from this, from
363    /// [`ShareBackend::remove_stream`], from [`ShareBackend::rename_stream`]
364    /// and from a stream's handle with STATUS_ACCESS_DENIED: macOS stores
365    /// an extended attribute in a `._` file when a stream request fails
366    /// with STATUS_NOT_SUPPORTED. The default closes `file` and returns
367    /// [`SmbError::NotSupported`].
368    async fn open_stream(
369        &self,
370        file: Box<dyn Handle>,
371        _path: &SmbPath,
372        _stream: &StreamName,
373        _opts: OpenOptions,
374    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
375        let _ = file.close().await;
376        Err(SmbError::NotSupported)
377    }
378
379    /// Remove the named stream of the file or directory at `path` that
380    /// `stream` names, whatever the case of its spelling. Fail with
381    /// [`SmbError::NotFound`] when the file has no such stream.
382    ///
383    /// `file_index` is the [`FileInfo::file_index`] the backend reported
384    /// for the file the protocol layer means, `0` if it reported none. A
385    /// backend with file ids fails with [`SmbError::NotFound`] when the
386    /// file at `path` has another id, as when another file took its place
387    /// outside the server, and leaves that file alone. The default returns
388    /// [`SmbError::NotSupported`].
389    async fn remove_stream(
390        &self,
391        _path: &SmbPath,
392        _file_index: u64,
393        _stream: &StreamName,
394    ) -> SmbResult<()> {
395        Err(SmbError::NotSupported)
396    }
397
398    /// Rename a stream of the file or directory at `path`, which has the id
399    /// `file_index` as [`ShareBackend::remove_stream`] says: the named
400    /// stream `from` names, or the default stream when `from` is `None`,
401    /// to the named stream `to`, or to the default stream when `to` is
402    /// `None`. Names compare without regard to case, and a renamed stream
403    /// takes the spelling of `to`. `from` and `to` never name the same
404    /// stream, and a directory, which has no default stream, only renames
405    /// a named stream to another.
406    ///
407    /// When `to` names an existing stream, fail with [`SmbError::Exists`]
408    /// unless `replace_if_exists` is set; then that stream is replaced,
409    /// and the protocol layer has checked that it is empty and that no
410    /// open is on it. That holds for the default stream too, which a
411    /// rename to it always replaces.
412    ///
413    /// A rename from the default stream moves the file's data into the
414    /// named stream and leaves the default stream empty; a rename to it
415    /// moves the stream's data into the file and removes the stream. A
416    /// rename that fails leaves both streams as they were, a replaced one
417    /// included.
418    ///
419    /// Stream handles track their stream itself, not its name: every
420    /// handle open on a named stream renamed to another name keeps reading
421    /// and writing it under its new name. A rename to or from the default
422    /// stream comes from the only open on the stream it renames, whose
423    /// handle the protocol layer replaces with a new one; the old handle
424    /// still has to close cleanly. The rename updates the file's last
425    /// write time, which the protocol layer reports as a change of the
426    /// file.
427    ///
428    /// The default returns [`SmbError::NotSupported`].
429    async fn rename_stream(
430        &self,
431        _path: &SmbPath,
432        _file_index: u64,
433        _from: Option<&StreamName>,
434        _to: Option<&StreamName>,
435        _replace_if_exists: bool,
436    ) -> SmbResult<()> {
437        Err(SmbError::NotSupported)
438    }
439
440    /// Copies `len` bytes from `src_offset` of `src` to `dst_offset` of
441    /// `dst` inside the storage, for a client's server-side copy, and
442    /// returns the number copied. `dst` is a handle this backend gave. `src`
443    /// may be a handle of another backend or share, or of the same file as
444    /// `dst`. A copy past the end of `dst` leaves a gap that reads as
445    /// zeros, as [`Handle::write`] does.
446    ///
447    /// The ranges can overlap when `src` and `dst` are one file; the server
448    /// cannot tell for two shares over one directory, or for hard links on a
449    /// backend without file ids. Copy such a range in full as a buffered
450    /// copy would, fail with an error, or return [`SmbError::NotSupported`]
451    /// to have the server copy it; never return a short count for it.
452    ///
453    /// Return [`SmbError::NotSupported`] or [`SmbError::NotSameDevice`] when
454    /// the backend has no faster way to copy between these two handles than
455    /// reading one and writing the other, such as when [`Handle::as_any`] of
456    /// either is `None`, as this crate's named-stream handles do. The
457    /// server then reads `src` and writes `dst` with [`Handle::read`] and
458    /// [`Handle::write`], and does the same for what is left when this
459    /// returns fewer than `len` bytes. Outside an overlapping copy, a
460    /// backend that copied some bytes and then fails returns the number
461    /// copied, and an error only when it copied nothing. Byte-range locks,
462    /// leases and change reports are the server's. The default returns
463    /// [`SmbError::NotSupported`].
464    async fn copy_range(
465        &self,
466        _src: &dyn Handle,
467        _src_offset: u64,
468        _dst: &dyn Handle,
469        _dst_offset: u64,
470        _len: u64,
471    ) -> SmbResult<u64> {
472        Err(SmbError::NotSupported)
473    }
474
475    /// Makes the `len` bytes at `dst_offset` of `dst` share their storage
476    /// with the `len` bytes at `src_offset` of `src`, for a client's
477    /// duplicate extents request: the bytes read the same, and a later write
478    /// to either file leaves the other as it is. `dst` is a handle this
479    /// backend gave. `src` may be a handle of another backend or share.
480    ///
481    /// Called only when [`BackendCapabilities::block_cloning`] is set, with a
482    /// `len` other than 0. The server has checked that `src` and `dst` are
483    /// files open with the access a clone needs, that both offsets are
484    /// multiples of the allocation unit [`ShareBackend::volume_info`]
485    /// reports, that `len` is a multiple of it too or the range of `src`
486    /// ends at the end of `src` and the range of `dst` at the end of `dst`,
487    /// that each range lies inside its file, and that no byte-range lock of
488    /// another open covers either range. Byte-range locks, leases and change
489    /// reports are the server's.
490    ///
491    /// Return [`SmbError::NotSameDevice`] when `src` is on another volume
492    /// than `dst`, which includes a handle of another backend,
493    /// [`SmbError::NotSupported`] when the storage cannot share blocks
494    /// between these two files, and [`SmbError::InvalidParameter`] for ranges
495    /// it refuses, such as overlapping ranges of one file. Clients see
496    /// STATUS_INVALID_PARAMETER for the first and the last, and
497    /// STATUS_INVALID_DEVICE_REQUEST for `NotSupported`. These three leave
498    /// `dst` as it was. A clone that fails with another error may have
499    /// changed part of the range. The default returns
500    /// [`SmbError::NotSupported`].
501    async fn clone_range(
502        &self,
503        _src: &dyn Handle,
504        _src_offset: u64,
505        _dst: &dyn Handle,
506        _dst_offset: u64,
507        _len: u64,
508    ) -> SmbResult<()> {
509        Err(SmbError::NotSupported)
510    }
511}
512
513/// A live open file or directory handle.
514///
515/// One handle per `CREATE`. `close` runs when CLOSE arrives, and when the
516/// tree, session or connection the open belongs to ends. A durable open's
517/// handle stays open past the end of its session or connection, until its
518/// client takes the open back, the open expires, or something else closes
519/// it; see the crate docs.
520#[async_trait]
521pub trait Handle: Send + Sync {
522    /// Read up to `len` bytes at `offset`. May return fewer.
523    async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes>;
524
525    /// Write `data` at `offset`. Returns bytes written. A write that starts
526    /// past the end of the file leaves a gap that reads as zeros.
527    async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32>;
528
529    /// Write owned `data` at `offset`. Backends that need ownership across a
530    /// blocking boundary can override this to avoid an extra copy.
531    async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
532        self.write(offset, &data).await
533    }
534
535    /// Flush buffered writes. May be a no-op on backends that always flush.
536    async fn flush(&self) -> SmbResult<()>;
537
538    /// Stat: current file info.
539    async fn stat(&self) -> SmbResult<FileInfo>;
540
541    /// Set timestamps on a file or directory. `None` fields leave the
542    /// corresponding time alone.
543    ///
544    /// Return [`SmbError::NotSupported`] for an access or write time the
545    /// backend cannot store. A backend that cannot store a creation time
546    /// ignores it and applies the other fields; a request with only a
547    /// creation time then succeeds and changes nothing.
548    /// `change_time` is the time of the last change: a backend whose
549    /// storage moves it to the current time on every change, as POSIX ctime
550    /// does, may keep doing so and not store the requested value.
551    ///
552    /// `LocalFsBackend` sets access and write times on every host and
553    /// creation time on Windows and macOS. Elsewhere it ignores the creation
554    /// time. The host keeps the change time.
555    async fn set_times(&self, times: FileTimes) -> SmbResult<()>;
556
557    /// Set the attributes (MS-FSCC 2.6) of a file or directory to
558    /// `attributes`, a combination of `FILE_ATTRIBUTE_READONLY` (0x1),
559    /// `HIDDEN` (0x2), `SYSTEM` (0x4), `ARCHIVE` (0x20), `TEMPORARY`
560    /// (0x100), `OFFLINE` (0x1000) and `NOT_CONTENT_INDEXED` (0x2000).
561    /// Flags left out are cleared. The protocol layer calls this only when
562    /// the request differs from the attributes [`Handle::stat`] reports.
563    ///
564    /// Return [`SmbError::NotSupported`] if a flag cannot be stored, or
565    /// store what the backend can and ignore the rest, as long as
566    /// [`Handle::stat`] then reports what is stored.
567    ///
568    /// `LocalFsBackend` on Windows stores every flag as the host's
569    /// attributes. On Unix hosts it stores `READONLY` on files as the
570    /// absence of write permission bits and ignores the other flags, and
571    /// `READONLY` on a directory: [`FileInfo::file_attributes`] stays 0
572    /// there.
573    async fn set_attributes(&self, attributes: u32) -> SmbResult<()>;
574
575    /// Truncate (or extend) to `len` bytes; bytes added by extending read as
576    /// zeros. For directories: the protocol layer rejects this before
577    /// reaching the backend.
578    async fn truncate(&self, len: u64) -> SmbResult<()>;
579
580    /// List directory entries matching the optional pattern. The pattern
581    /// uses the wildcards of MS-FSA 2.1.4.4: `*` and `?`, and the DOS forms
582    /// `<` (DOS_STAR), `>` (DOS_QM) and `"` (DOS_DOT).
583    /// QUERY_DIRECTORY returns the result as is, so the backend applies the
584    /// pattern. The `.` and `..` entries are left out; QUERY_DIRECTORY adds
585    /// them.
586    async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>>;
587
588    /// [`Handle::list_dir`] for a caller that reads the
589    /// [`FileInfo::ea_size`] of the entries only when `ea_size` is set;
590    /// without it a backend may leave that 0 and skip reading it.
591    /// QUERY_DIRECTORY calls this when a listing starts or restarts, with
592    /// `ea_size` set when the share serves extended attributes and the
593    /// information class carries EaSize; the layout with Finder data for
594    /// macOS clients carries none. Queries that carry on a listing reuse
595    /// its entries, so one carried on under a class with EaSize after it
596    /// started under one without reports 0 until it restarts. The default
597    /// calls `list_dir`.
598    async fn list_dir_sized(
599        &self,
600        pattern: Option<&str>,
601        ea_size: bool,
602    ) -> SmbResult<Vec<DirEntry>> {
603        let _ = ea_size;
604        self.list_dir(pattern).await
605    }
606
607    /// Close the handle. Boxed self lets implementors consume internal state.
608    async fn close(self: Box<Self>) -> SmbResult<()>;
609
610    /// Number of hard links to the file, reported as NumberOfLinks by
611    /// FileStandardInformation. `0` means the file has been deleted while
612    /// open. The default reports `1`.
613    async fn link_count(&self) -> SmbResult<u32> {
614        Ok(1)
615    }
616
617    /// True if this directory has no entries other than `.` and `..`,
618    /// including entries [`Handle::list_dir`] leaves out. The default checks
619    /// `list_dir(None)`, so a backend whose listing hides entries overrides
620    /// it.
621    async fn dir_is_empty(&self) -> SmbResult<bool> {
622        Ok(self.list_dir(None).await?.is_empty())
623    }
624
625    /// Watch this directory for changes to its entries made by anyone,
626    /// including outside the server. The server asks one open of a watched
627    /// directory and shares the watch among every watch of that directory;
628    /// it may outlive the handle, and is dropped with the directory's last
629    /// watch. The default returns `Ok(None)`: the server then reports only
630    /// the changes made through it.
631    async fn watch(&self) -> SmbResult<Option<Box<dyn DirWatch>>> {
632        Ok(None)
633    }
634
635    /// The named streams of the file or directory this handle is on,
636    /// whichever of its streams the handle is open on, in the order
637    /// FileStreamInformation lists them. The default stream is not listed.
638    /// Called only when [`BackendCapabilities::named_streams`] is set. The
639    /// default returns none.
640    async fn streams(&self) -> SmbResult<Vec<StreamInfo>> {
641        Ok(Vec::new())
642    }
643
644    /// The named streams of entries of this directory: for each entry of
645    /// `entries`, a name and the streams to read with the most bytes to
646    /// read of each, one result per stream, in order, with the stream's
647    /// size and up to that many bytes from its start. A result is `None`
648    /// when the entry has no such stream, or when it or the entry cannot
649    /// be read; stream names compare without regard to case. An entry
650    /// that is not a regular file or a directory has none: no FIFO,
651    /// socket or device is opened in a way that blocks, and no link is
652    /// followed out of the share.
653    ///
654    /// QUERY_DIRECTORY for a macOS client that negotiated Apple's
655    /// extensions calls it once per response, for `AFP_AfpInfo` of the
656    /// entries the response carries, other than "." and "..", and
657    /// `AFP_Resource` of the files among them. Called only on a directory
658    /// and only when [`BackendCapabilities::named_streams`] is set. A
659    /// handle that wraps another has to forward it, or listings carry no
660    /// Finder data. The default returns [`SmbError::NotSupported`];
661    /// listings then carry no Finder info or resource fork sizes.
662    async fn peek_streams(
663        &self,
664        _entries: &[(&str, &[(StreamName, u32)])],
665    ) -> SmbResult<Vec<Vec<Option<(u64, bytes::Bytes)>>>> {
666        Err(SmbError::NotSupported)
667    }
668
669    /// The extended attributes of the file or directory this handle is
670    /// on, in the order FileFullEaInformation lists them. The protocol
671    /// layer leaves out those with names a client cannot send, empty
672    /// values or values over 65535 bytes. Called only when
673    /// [`BackendCapabilities::extended_attributes`] is set, and never on a
674    /// handle of a named stream. The default returns none.
675    async fn eas(&self) -> SmbResult<Vec<Ea>> {
676        Ok(Vec::new())
677    }
678
679    /// Changes the extended attributes of the file or directory this
680    /// handle is on: each of `eas` replaces the attribute of its name, or
681    /// adds it, and one with an empty value removes it, if there is one.
682    /// Names compare without regard to ASCII case; a replaced attribute
683    /// may keep the spelling it had. A name appears once in `eas`. All
684    /// of them apply or none does.
685    ///
686    /// The protocol layer has checked the names, and that the attributes
687    /// the file ends up with take at most 65531 bytes, counting 5 bytes,
688    /// the name and the value of each. Fail with
689    /// [`SmbError::EaTooLarge`] when they need more room than the backend
690    /// has, and with [`SmbError::EaNameInvalid`] for a name it cannot
691    /// store. Called only when
692    /// [`BackendCapabilities::extended_attributes`] is set, and never on a
693    /// handle of a named stream. The default returns
694    /// [`SmbError::NotSupported`].
695    async fn set_eas(&self, _eas: &[Ea]) -> SmbResult<()> {
696        Err(SmbError::NotSupported)
697    }
698
699    /// This handle as [`Any`](std::any::Any), for [`ShareBackend::copy_range`]
700    /// to tell the handles its backend gave from others. A handle that wraps
701    /// another and changes what it does must not forward it. The default
702    /// returns `None`.
703    fn as_any(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
704        None
705    }
706}
707
708/// What a backend saw happen to an entry of a watched directory.
709#[derive(Debug, Clone, PartialEq, Eq)]
710#[non_exhaustive]
711pub enum DirChangeKind {
712    /// The entry appeared.
713    Added,
714    /// The entry went away.
715    Removed,
716    /// The entry was renamed within the directory from `from`.
717    Renamed { from: String },
718    /// The entry's contents were written.
719    Modified,
720    /// The entry's attributes or times changed.
721    AttributesChanged,
722    /// Changes were lost; the client has to list the directory again.
723    Lost,
724    /// The watched directory itself was renamed or moved. Changes to its
725    /// entries keep coming.
726    Moved,
727    /// The watched directory itself was deleted. No change follows.
728    Deleted,
729}
730
731/// A change to an entry of a watched directory, as the backend saw it.
732#[derive(Debug, Clone, PartialEq, Eq)]
733#[non_exhaustive]
734pub struct DirChange {
735    /// Name of the entry in the directory. Empty for
736    /// [`DirChangeKind::Lost`], [`DirChangeKind::Moved`] and
737    /// [`DirChangeKind::Deleted`].
738    pub name: String,
739    /// What happened to the entry.
740    pub kind: DirChangeKind,
741    /// The entry is a directory.
742    pub is_directory: bool,
743}
744
745impl DirChange {
746    /// A change of `kind` to the entry `name`, a directory when
747    /// `is_directory`.
748    pub fn new(name: impl Into<String>, kind: DirChangeKind, is_directory: bool) -> Self {
749        Self {
750            name: name.into(),
751            kind,
752            is_directory,
753        }
754    }
755}
756
757/// Changes to the entries of one directory, from [`Handle::watch`].
758#[async_trait]
759pub trait DirWatch: Send {
760    /// The next changes, in the order they happened; `None` once the watch
761    /// has stopped. A watch that stops without [`DirChangeKind::Deleted`]
762    /// may have lost changes, and the server asks for a new one. The server
763    /// leaves out names it cannot use, and takes a rename from or to one as
764    /// the addition or removal of the other name.
765    ///
766    /// Must be cancel-safe: the server may drop the future before it
767    /// completes, and changes it had not returned must come with the next
768    /// call.
769    async fn next(&mut self) -> Option<Vec<DirChange>>;
770}
771
772/// Backend for the synthetic IPC$ share. `open`, `unlink` and `rename`
773/// return [`SmbError::NotSupported`].
774pub(crate) struct NotSupportedBackend;
775
776#[async_trait]
777impl ShareBackend for NotSupportedBackend {
778    async fn open(
779        &self,
780        _path: &SmbPath,
781        _opts: OpenOptions,
782    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
783        Err(SmbError::NotSupported)
784    }
785    async fn unlink(&self, _path: &SmbPath) -> SmbResult<()> {
786        Err(SmbError::NotSupported)
787    }
788    async fn rename(&self, _from: &SmbPath, _to: &SmbPath, _replace: bool) -> SmbResult<()> {
789        Err(SmbError::NotSupported)
790    }
791    fn capabilities(&self) -> BackendCapabilities {
792        BackendCapabilities {
793            is_read_only: true,
794            case_sensitive: false,
795            named_streams: false,
796            extended_attributes: false,
797            block_cloning: false,
798        }
799    }
800}
801
802// ---------------------------------------------------------------------------
803// VolumeInfo
804// ---------------------------------------------------------------------------
805
806/// Volume behind a share, as reported by FileFsVolumeInformation,
807/// FileFsSizeInformation, FileFsFullSizeInformation,
808/// FileFsAttributeInformation and FileFsSectorSizeInformation (MS-FSCC 2.5).
809///
810/// Sizes count allocation units of `sectors_per_allocation_unit *
811/// bytes_per_sector` bytes. Built from [`VolumeInfo::default`]; every
812/// field is public.
813#[derive(Debug, Clone, PartialEq, Eq)]
814#[non_exhaustive]
815pub struct VolumeInfo {
816    /// Total allocation units on the volume.
817    pub total_allocation_units: u64,
818    /// Free allocation units available to the share's users, after quotas
819    /// and reserved space.
820    pub caller_available_allocation_units: u64,
821    /// Free allocation units on the volume.
822    pub actual_available_allocation_units: u64,
823    /// Sectors in one allocation unit.
824    pub sectors_per_allocation_unit: u32,
825    /// Bytes in one sector.
826    pub bytes_per_sector: u32,
827    /// Volume serial number.
828    pub serial_number: u32,
829    /// Volume label. `None` reports the share name.
830    pub label: Option<String>,
831    /// Longest file name the volume stores, in characters.
832    pub max_name_length: u32,
833}
834
835impl VolumeInfo {
836    /// Bytes in one allocation unit, at least 1.
837    pub(crate) fn allocation_unit(&self) -> u64 {
838        (u64::from(self.sectors_per_allocation_unit) * u64::from(self.bytes_per_sector)).max(1)
839    }
840}
841
842impl Default for VolumeInfo {
843    /// A 4 PiB volume with 2 PiB free, in 4 KiB allocation units.
844    fn default() -> Self {
845        Self {
846            total_allocation_units: 1 << 40,
847            caller_available_allocation_units: 1 << 39,
848            actual_available_allocation_units: 1 << 39,
849            sectors_per_allocation_unit: 1,
850            bytes_per_sector: 4096,
851            serial_number: crate::info_class::VOLUME_SERIAL_NUMBER,
852            label: None,
853            max_name_length: 255,
854        }
855    }
856}