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}
275
276// ---------------------------------------------------------------------------
277// Traits
278// ---------------------------------------------------------------------------
279
280/// Pluggable storage backend mounted as a share.
281///
282/// Implementors must be `Send + Sync + 'static` so the server can spawn
283/// per-request handlers freely.
284#[async_trait]
285pub trait ShareBackend: Send + Sync + 'static {
286    /// Open or create a file or directory. Returns a fresh handle and what
287    /// the open did to the file.
288    ///
289    /// Fail with [`SmbError::PathNotFound`] when a directory on the way to
290    /// `path` is missing and [`SmbError::NotFound`] when only the last
291    /// component is.
292    ///
293    /// A backend that reports [`BackendCapabilities::named_streams`] keeps
294    /// the named streams of a file that [`OpenIntent::Truncate`] or
295    /// [`OpenIntent::OverwriteOrCreate`] overwrites: the protocol layer
296    /// removes them with [`ShareBackend::remove_stream`], each once no open
297    /// is on it. `unlink` removes them with the file, and `rename` keeps
298    /// them with it.
299    async fn open(
300        &self,
301        path: &SmbPath,
302        opts: OpenOptions,
303    ) -> SmbResult<(Box<dyn Handle>, OpenAction)>;
304
305    /// Delete a file or an empty directory.
306    async fn unlink(&self, path: &SmbPath) -> SmbResult<()>;
307
308    /// Rename `from` to `to`.
309    ///
310    /// If `to` names an existing file other than `from`, including another
311    /// hard link to the same file, fail with [`SmbError::Exists`] unless
312    /// `replace_if_exists` is set, in which case the existing file is
313    /// replaced. An existing directory at `to` is never
314    /// replaced: fail with [`SmbError::AccessDenied`].
315    async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()>;
316
317    /// Static capabilities. TREE_CONNECT clamps access to read-only when
318    /// `is_read_only` is set.
319    fn capabilities(&self) -> BackendCapabilities;
320
321    /// Size, free space and identity of the volume behind the share, for the
322    /// filesystem QUERY_INFO classes. The default returns
323    /// [`VolumeInfo::default`].
324    async fn volume_info(&self) -> SmbResult<VolumeInfo> {
325        Ok(VolumeInfo::default())
326    }
327
328    /// Open or create the named stream `stream` of the file or directory at
329    /// `path`. `file` is the handle `open` just gave for `path`, opened for
330    /// reading. The backend owns it and closes it, also when this fails; it
331    /// may keep it for as long as the stream's handle lasts, so the stream
332    /// follows the file through renames. `opts.intent` applies to the
333    /// stream; `opts.directory` and `opts.non_directory` are false. The
334    /// handle reads and writes the stream: its `stat` reports the file's
335    /// times, attributes and id with the stream's sizes, `set_times` and
336    /// `set_attributes` change the file, and `truncate` the stream. A
337    /// write or size change of the stream updates the file's last write
338    /// time, which the protocol layer reports as a change of the file.
339    ///
340    /// Stream names compare without regard to case: an existing stream
341    /// opens under any spelling of its name, and a new one keeps the
342    /// spelling of `stream`. An open that would write or create a stream of
343    /// a read-only file fails with STATUS_ACCESS_DENIED before this is
344    /// called.
345    ///
346    /// Called only when [`BackendCapabilities::named_streams`] is set. The
347    /// protocol layer answers [`SmbError::NotSupported`] from this, from
348    /// [`ShareBackend::remove_stream`], from [`ShareBackend::rename_stream`]
349    /// and from a stream's handle with STATUS_ACCESS_DENIED: macOS stores
350    /// an extended attribute in a `._` file when a stream request fails
351    /// with STATUS_NOT_SUPPORTED. The default closes `file` and returns
352    /// [`SmbError::NotSupported`].
353    async fn open_stream(
354        &self,
355        file: Box<dyn Handle>,
356        _path: &SmbPath,
357        _stream: &StreamName,
358        _opts: OpenOptions,
359    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
360        let _ = file.close().await;
361        Err(SmbError::NotSupported)
362    }
363
364    /// Remove the named stream of the file or directory at `path` that
365    /// `stream` names, whatever the case of its spelling. Fail with
366    /// [`SmbError::NotFound`] when the file has no such stream.
367    ///
368    /// `file_index` is the [`FileInfo::file_index`] the backend reported
369    /// for the file the protocol layer means, `0` if it reported none. A
370    /// backend with file ids fails with [`SmbError::NotFound`] when the
371    /// file at `path` has another id, as when another file took its place
372    /// outside the server, and leaves that file alone. The default returns
373    /// [`SmbError::NotSupported`].
374    async fn remove_stream(
375        &self,
376        _path: &SmbPath,
377        _file_index: u64,
378        _stream: &StreamName,
379    ) -> SmbResult<()> {
380        Err(SmbError::NotSupported)
381    }
382
383    /// Rename a stream of the file or directory at `path`, which has the id
384    /// `file_index` as [`ShareBackend::remove_stream`] says: the named
385    /// stream `from` names, or the default stream when `from` is `None`,
386    /// to the named stream `to`, or to the default stream when `to` is
387    /// `None`. Names compare without regard to case, and a renamed stream
388    /// takes the spelling of `to`. `from` and `to` never name the same
389    /// stream, and a directory, which has no default stream, only renames
390    /// a named stream to another.
391    ///
392    /// When `to` names an existing stream, fail with [`SmbError::Exists`]
393    /// unless `replace_if_exists` is set; then that stream is replaced,
394    /// and the protocol layer has checked that it is empty and that no
395    /// open is on it. That holds for the default stream too, which a
396    /// rename to it always replaces.
397    ///
398    /// A rename from the default stream moves the file's data into the
399    /// named stream and leaves the default stream empty; a rename to it
400    /// moves the stream's data into the file and removes the stream. A
401    /// rename that fails leaves both streams as they were, a replaced one
402    /// included.
403    ///
404    /// Stream handles track their stream itself, not its name: every
405    /// handle open on a named stream renamed to another name keeps reading
406    /// and writing it under its new name. A rename to or from the default
407    /// stream comes from the only open on the stream it renames, whose
408    /// handle the protocol layer replaces with a new one; the old handle
409    /// still has to close cleanly. The rename updates the file's last
410    /// write time, which the protocol layer reports as a change of the
411    /// file.
412    ///
413    /// The default returns [`SmbError::NotSupported`].
414    async fn rename_stream(
415        &self,
416        _path: &SmbPath,
417        _file_index: u64,
418        _from: Option<&StreamName>,
419        _to: Option<&StreamName>,
420        _replace_if_exists: bool,
421    ) -> SmbResult<()> {
422        Err(SmbError::NotSupported)
423    }
424}
425
426/// A live open file or directory handle.
427///
428/// One handle per `CREATE`. `close` runs when CLOSE arrives, and when the
429/// tree, session or connection the open belongs to ends. A durable open's
430/// handle stays open past the end of its session or connection, until its
431/// client takes the open back, the open expires, or something else closes
432/// it; see the crate docs.
433#[async_trait]
434pub trait Handle: Send + Sync {
435    /// Read up to `len` bytes at `offset`. May return fewer.
436    async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes>;
437
438    /// Write `data` at `offset`. Returns bytes written. A write that starts
439    /// past the end of the file leaves a gap that reads as zeros.
440    async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32>;
441
442    /// Write owned `data` at `offset`. Backends that need ownership across a
443    /// blocking boundary can override this to avoid an extra copy.
444    async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
445        self.write(offset, &data).await
446    }
447
448    /// Flush buffered writes. May be a no-op on backends that always flush.
449    async fn flush(&self) -> SmbResult<()>;
450
451    /// Stat: current file info.
452    async fn stat(&self) -> SmbResult<FileInfo>;
453
454    /// Set timestamps on a file or directory. `None` fields leave the
455    /// corresponding time alone.
456    ///
457    /// Return [`SmbError::NotSupported`] for an access or write time the
458    /// backend cannot store. A backend that cannot store a creation time
459    /// ignores it and applies the other fields; a request with only a
460    /// creation time then succeeds and changes nothing.
461    /// `change_time` is the time of the last change: a backend whose
462    /// storage moves it to the current time on every change, as POSIX ctime
463    /// does, may keep doing so and not store the requested value.
464    ///
465    /// `LocalFsBackend` sets access and write times on every host and
466    /// creation time on Windows and macOS. Elsewhere it ignores the creation
467    /// time. The host keeps the change time.
468    async fn set_times(&self, times: FileTimes) -> SmbResult<()>;
469
470    /// Set the attributes (MS-FSCC 2.6) of a file or directory to
471    /// `attributes`, a combination of `FILE_ATTRIBUTE_READONLY` (0x1),
472    /// `HIDDEN` (0x2), `SYSTEM` (0x4), `ARCHIVE` (0x20), `TEMPORARY`
473    /// (0x100), `OFFLINE` (0x1000) and `NOT_CONTENT_INDEXED` (0x2000).
474    /// Flags left out are cleared. The protocol layer calls this only when
475    /// the request differs from the attributes [`Handle::stat`] reports.
476    ///
477    /// Return [`SmbError::NotSupported`] if a flag cannot be stored, or
478    /// store what the backend can and ignore the rest, as long as
479    /// [`Handle::stat`] then reports what is stored.
480    ///
481    /// `LocalFsBackend` on Windows stores every flag as the host's
482    /// attributes. On Unix hosts it stores `READONLY` on files as the
483    /// absence of write permission bits and ignores the other flags, and
484    /// `READONLY` on a directory: [`FileInfo::file_attributes`] stays 0
485    /// there.
486    async fn set_attributes(&self, attributes: u32) -> SmbResult<()>;
487
488    /// Truncate (or extend) to `len` bytes; bytes added by extending read as
489    /// zeros. For directories: the protocol layer rejects this before
490    /// reaching the backend.
491    async fn truncate(&self, len: u64) -> SmbResult<()>;
492
493    /// List directory entries matching the optional pattern. The pattern
494    /// uses the wildcards of MS-FSA 2.1.4.4: `*` and `?`, and the DOS forms
495    /// `<` (DOS_STAR), `>` (DOS_QM) and `"` (DOS_DOT).
496    /// QUERY_DIRECTORY returns the result as is, so the backend applies the
497    /// pattern. The `.` and `..` entries are left out; QUERY_DIRECTORY adds
498    /// them.
499    async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>>;
500
501    /// [`Handle::list_dir`] for a caller that reads the
502    /// [`FileInfo::ea_size`] of the entries only when `ea_size` is set;
503    /// without it a backend may leave that 0 and skip reading it.
504    /// QUERY_DIRECTORY calls this when a listing starts or restarts, with
505    /// `ea_size` set when the share serves extended attributes and the
506    /// information class carries EaSize; the layout with Finder data for
507    /// macOS clients carries none. Queries that carry on a listing reuse
508    /// its entries, so one carried on under a class with EaSize after it
509    /// started under one without reports 0 until it restarts. The default
510    /// calls `list_dir`.
511    async fn list_dir_sized(
512        &self,
513        pattern: Option<&str>,
514        ea_size: bool,
515    ) -> SmbResult<Vec<DirEntry>> {
516        let _ = ea_size;
517        self.list_dir(pattern).await
518    }
519
520    /// Close the handle. Boxed self lets implementors consume internal state.
521    async fn close(self: Box<Self>) -> SmbResult<()>;
522
523    /// Number of hard links to the file, reported as NumberOfLinks by
524    /// FileStandardInformation. `0` means the file has been deleted while
525    /// open. The default reports `1`.
526    async fn link_count(&self) -> SmbResult<u32> {
527        Ok(1)
528    }
529
530    /// True if this directory has no entries other than `.` and `..`,
531    /// including entries [`Handle::list_dir`] leaves out. The default checks
532    /// `list_dir(None)`, so a backend whose listing hides entries overrides
533    /// it.
534    async fn dir_is_empty(&self) -> SmbResult<bool> {
535        Ok(self.list_dir(None).await?.is_empty())
536    }
537
538    /// Watch this directory for changes to its entries made by anyone,
539    /// including outside the server. The server asks one open of a watched
540    /// directory and shares the watch among every watch of that directory;
541    /// it may outlive the handle, and is dropped with the directory's last
542    /// watch. The default returns `Ok(None)`: the server then reports only
543    /// the changes made through it.
544    async fn watch(&self) -> SmbResult<Option<Box<dyn DirWatch>>> {
545        Ok(None)
546    }
547
548    /// The named streams of the file or directory this handle is on,
549    /// whichever of its streams the handle is open on, in the order
550    /// FileStreamInformation lists them. The default stream is not listed.
551    /// Called only when [`BackendCapabilities::named_streams`] is set. The
552    /// default returns none.
553    async fn streams(&self) -> SmbResult<Vec<StreamInfo>> {
554        Ok(Vec::new())
555    }
556
557    /// The named streams of entries of this directory: for each entry of
558    /// `entries`, a name and the streams to read with the most bytes to
559    /// read of each, one result per stream, in order, with the stream's
560    /// size and up to that many bytes from its start. A result is `None`
561    /// when the entry has no such stream, or when it or the entry cannot
562    /// be read; stream names compare without regard to case. An entry
563    /// that is not a regular file or a directory has none: no FIFO,
564    /// socket or device is opened in a way that blocks, and no link is
565    /// followed out of the share.
566    ///
567    /// QUERY_DIRECTORY for a macOS client that negotiated Apple's
568    /// extensions calls it once per response, for `AFP_AfpInfo` of the
569    /// entries the response carries, other than "." and "..", and
570    /// `AFP_Resource` of the files among them. Called only on a directory
571    /// and only when [`BackendCapabilities::named_streams`] is set. A
572    /// handle that wraps another has to forward it, or listings carry no
573    /// Finder data. The default returns [`SmbError::NotSupported`];
574    /// listings then carry no Finder info or resource fork sizes.
575    async fn peek_streams(
576        &self,
577        _entries: &[(&str, &[(StreamName, u32)])],
578    ) -> SmbResult<Vec<Vec<Option<(u64, bytes::Bytes)>>>> {
579        Err(SmbError::NotSupported)
580    }
581
582    /// The extended attributes of the file or directory this handle is
583    /// on, in the order FileFullEaInformation lists them. The protocol
584    /// layer leaves out those with names a client cannot send, empty
585    /// values or values over 65535 bytes. Called only when
586    /// [`BackendCapabilities::extended_attributes`] is set, and never on a
587    /// handle of a named stream. The default returns none.
588    async fn eas(&self) -> SmbResult<Vec<Ea>> {
589        Ok(Vec::new())
590    }
591
592    /// Changes the extended attributes of the file or directory this
593    /// handle is on: each of `eas` replaces the attribute of its name, or
594    /// adds it, and one with an empty value removes it, if there is one.
595    /// Names compare without regard to ASCII case; a replaced attribute
596    /// may keep the spelling it had. A name appears once in `eas`. All
597    /// of them apply or none does.
598    ///
599    /// The protocol layer has checked the names, and that the attributes
600    /// the file ends up with take at most 65531 bytes, counting 5 bytes,
601    /// the name and the value of each. Fail with
602    /// [`SmbError::EaTooLarge`] when they need more room than the backend
603    /// has, and with [`SmbError::EaNameInvalid`] for a name it cannot
604    /// store. Called only when
605    /// [`BackendCapabilities::extended_attributes`] is set, and never on a
606    /// handle of a named stream. The default returns
607    /// [`SmbError::NotSupported`].
608    async fn set_eas(&self, _eas: &[Ea]) -> SmbResult<()> {
609        Err(SmbError::NotSupported)
610    }
611}
612
613/// What a backend saw happen to an entry of a watched directory.
614#[derive(Debug, Clone, PartialEq, Eq)]
615#[non_exhaustive]
616pub enum DirChangeKind {
617    /// The entry appeared.
618    Added,
619    /// The entry went away.
620    Removed,
621    /// The entry was renamed within the directory from `from`.
622    Renamed { from: String },
623    /// The entry's contents were written.
624    Modified,
625    /// The entry's attributes or times changed.
626    AttributesChanged,
627    /// Changes were lost; the client has to list the directory again.
628    Lost,
629    /// The watched directory itself was renamed or moved. Changes to its
630    /// entries keep coming.
631    Moved,
632    /// The watched directory itself was deleted. No change follows.
633    Deleted,
634}
635
636/// A change to an entry of a watched directory, as the backend saw it.
637#[derive(Debug, Clone, PartialEq, Eq)]
638#[non_exhaustive]
639pub struct DirChange {
640    /// Name of the entry in the directory. Empty for
641    /// [`DirChangeKind::Lost`], [`DirChangeKind::Moved`] and
642    /// [`DirChangeKind::Deleted`].
643    pub name: String,
644    /// What happened to the entry.
645    pub kind: DirChangeKind,
646    /// The entry is a directory.
647    pub is_directory: bool,
648}
649
650impl DirChange {
651    /// A change of `kind` to the entry `name`, a directory when
652    /// `is_directory`.
653    pub fn new(name: impl Into<String>, kind: DirChangeKind, is_directory: bool) -> Self {
654        Self {
655            name: name.into(),
656            kind,
657            is_directory,
658        }
659    }
660}
661
662/// Changes to the entries of one directory, from [`Handle::watch`].
663#[async_trait]
664pub trait DirWatch: Send {
665    /// The next changes, in the order they happened; `None` once the watch
666    /// has stopped. A watch that stops without [`DirChangeKind::Deleted`]
667    /// may have lost changes, and the server asks for a new one. The server
668    /// leaves out names it cannot use, and takes a rename from or to one as
669    /// the addition or removal of the other name.
670    ///
671    /// Must be cancel-safe: the server may drop the future before it
672    /// completes, and changes it had not returned must come with the next
673    /// call.
674    async fn next(&mut self) -> Option<Vec<DirChange>>;
675}
676
677/// Backend for the synthetic IPC$ share. `open`, `unlink` and `rename`
678/// return [`SmbError::NotSupported`].
679pub(crate) struct NotSupportedBackend;
680
681#[async_trait]
682impl ShareBackend for NotSupportedBackend {
683    async fn open(
684        &self,
685        _path: &SmbPath,
686        _opts: OpenOptions,
687    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
688        Err(SmbError::NotSupported)
689    }
690    async fn unlink(&self, _path: &SmbPath) -> SmbResult<()> {
691        Err(SmbError::NotSupported)
692    }
693    async fn rename(&self, _from: &SmbPath, _to: &SmbPath, _replace: bool) -> SmbResult<()> {
694        Err(SmbError::NotSupported)
695    }
696    fn capabilities(&self) -> BackendCapabilities {
697        BackendCapabilities {
698            is_read_only: true,
699            case_sensitive: false,
700            named_streams: false,
701            extended_attributes: false,
702        }
703    }
704}
705
706// ---------------------------------------------------------------------------
707// VolumeInfo
708// ---------------------------------------------------------------------------
709
710/// Volume behind a share, as reported by FileFsVolumeInformation,
711/// FileFsSizeInformation, FileFsFullSizeInformation,
712/// FileFsAttributeInformation and FileFsSectorSizeInformation (MS-FSCC 2.5).
713///
714/// Sizes count allocation units of `sectors_per_allocation_unit *
715/// bytes_per_sector` bytes. Built from [`VolumeInfo::default`]; every
716/// field is public.
717#[derive(Debug, Clone, PartialEq, Eq)]
718#[non_exhaustive]
719pub struct VolumeInfo {
720    /// Total allocation units on the volume.
721    pub total_allocation_units: u64,
722    /// Free allocation units available to the share's users, after quotas
723    /// and reserved space.
724    pub caller_available_allocation_units: u64,
725    /// Free allocation units on the volume.
726    pub actual_available_allocation_units: u64,
727    /// Sectors in one allocation unit.
728    pub sectors_per_allocation_unit: u32,
729    /// Bytes in one sector.
730    pub bytes_per_sector: u32,
731    /// Volume serial number.
732    pub serial_number: u32,
733    /// Volume label. `None` reports the share name.
734    pub label: Option<String>,
735    /// Longest file name the volume stores, in characters.
736    pub max_name_length: u32,
737}
738
739impl Default for VolumeInfo {
740    /// A 4 PiB volume with 2 PiB free, in 4 KiB allocation units.
741    fn default() -> Self {
742        Self {
743            total_allocation_units: 1 << 40,
744            caller_available_allocation_units: 1 << 39,
745            actual_available_allocation_units: 1 << 39,
746            sectors_per_allocation_unit: 1,
747            bytes_per_sector: 4096,
748            serial_number: crate::info_class::VOLUME_SERIAL_NUMBER,
749            label: None,
750            max_name_length: 255,
751        }
752    }
753}