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