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::error::{SmbError, SmbResult};
11use crate::path::SmbPath;
12
13// ---------------------------------------------------------------------------
14// OpenOptions
15// ---------------------------------------------------------------------------
16
17/// SMB CREATE disposition as seen by a backend.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum OpenIntent {
21 /// `FILE_OPEN`: open existing only; fail if missing.
22 Open,
23 /// `FILE_CREATE`: create new only; fail if exists.
24 Create,
25 /// `FILE_OPEN_IF`: open existing or create new.
26 OpenOrCreate,
27 /// `FILE_OVERWRITE_IF`: open existing (truncating) or create new.
28 OverwriteOrCreate,
29 /// `FILE_OVERWRITE`: open existing and truncate; fail if missing.
30 Truncate,
31}
32
33/// Options passed to `ShareBackend::open`.
34#[derive(Debug, Clone, Copy)]
35pub struct OpenOptions {
36 /// The open was granted `FILE_READ_DATA`, or has no data write access.
37 /// At least one of `read` and `write` is set.
38 pub read: bool,
39 /// The open was granted `FILE_WRITE_DATA` or `FILE_APPEND_DATA`.
40 pub write: bool,
41 /// The open was granted `FILE_WRITE_ATTRIBUTES`: the handle must be able
42 /// to change times and attributes, including on a read-only file.
43 pub write_attributes: bool,
44 /// CREATE disposition.
45 pub intent: OpenIntent,
46 /// `FILE_DIRECTORY_FILE` was set on CREATE: open or create a directory.
47 pub directory: bool,
48 /// `FILE_NON_DIRECTORY_FILE` was set on CREATE: fail if the target is a directory.
49 pub non_directory: bool,
50 /// `FILE_DELETE_ON_CLOSE` was set on CREATE.
51 pub delete_on_close: bool,
52}
53
54impl Default for OpenOptions {
55 fn default() -> Self {
56 Self {
57 read: true,
58 write: false,
59 write_attributes: false,
60 intent: OpenIntent::Open,
61 directory: false,
62 non_directory: false,
63 delete_on_close: false,
64 }
65 }
66}
67
68/// What `ShareBackend::open` did to the file (MS-SMB2 2.2.14 CreateAction).
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum OpenAction {
71 /// An existing file or directory was opened.
72 Opened,
73 /// A new file or directory was created.
74 Created,
75 /// An existing file was truncated to zero length, as
76 /// [`OpenIntent::Truncate`] and [`OpenIntent::OverwriteOrCreate`] do.
77 Overwritten,
78}
79
80// ---------------------------------------------------------------------------
81// FileInfo / DirEntry / FileTimes
82// ---------------------------------------------------------------------------
83
84/// Filesystem-style metadata for a single file or directory. Built with
85/// [`FileInfo::new`]; every field is public.
86#[derive(Debug, Clone)]
87#[non_exhaustive]
88pub struct FileInfo {
89 /// Display name (last component). For QUERY_INFO at the share root this
90 /// is the share name.
91 pub name: String,
92 /// File size in bytes.
93 pub end_of_file: u64,
94 /// Allocation size, usually `end_of_file` rounded up to a cluster.
95 /// Backends may return `end_of_file`.
96 pub allocation_size: u64,
97 /// FILETIME (100ns ticks since 1601).
98 pub creation_time: u64,
99 pub last_access_time: u64,
100 pub last_write_time: u64,
101 pub change_time: u64,
102 /// True if this is a directory.
103 pub is_directory: bool,
104 /// The file has `FILE_ATTRIBUTE_READONLY`.
105 pub read_only: bool,
106 /// Stable id of the file, unique within the share including any mounts
107 /// below the share root, reported as the file id by QUERY_INFO and
108 /// QUERY_DIRECTORY. Backends return the same value from `Handle::stat`
109 /// and `Handle::list_dir` for the same file, across opens and renames.
110 /// `0` if the backend has none; the server then tells files apart by
111 /// path, so a file reached through two hard links counts as two files:
112 /// share modes, byte-range locks and leases taken through one name do
113 /// not see opens through the other, and clients on the two names can
114 /// both cache writes to it.
115 pub file_index: u64,
116}
117
118// File attributes (MS-FSCC 2.6).
119pub(crate) const FILE_ATTRIBUTE_READONLY: u32 = 0x0000_0001;
120pub(crate) const FILE_ATTRIBUTE_HIDDEN: u32 = 0x0000_0002;
121pub(crate) const FILE_ATTRIBUTE_SYSTEM: u32 = 0x0000_0004;
122pub(crate) const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
123pub(crate) const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x0000_0020;
124pub(crate) const FILE_ATTRIBUTE_NORMAL: u32 = 0x0000_0080;
125pub(crate) const FILE_ATTRIBUTE_TEMPORARY: u32 = 0x0000_0100;
126pub(crate) const FILE_ATTRIBUTE_OFFLINE: u32 = 0x0000_1000;
127pub(crate) const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: u32 = 0x0000_2000;
128
129/// Attributes FileBasicInformation can set (MS-FSA 2.1.5.15.2).
130pub(crate) const VALID_SET_ATTRIBUTES: u32 = FILE_ATTRIBUTE_READONLY
131 | FILE_ATTRIBUTE_HIDDEN
132 | FILE_ATTRIBUTE_SYSTEM
133 | FILE_ATTRIBUTE_ARCHIVE
134 | FILE_ATTRIBUTE_TEMPORARY
135 | FILE_ATTRIBUTE_OFFLINE
136 | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
137
138impl FileInfo {
139 /// A zero-length, writable file named `name` with no times and no file
140 /// id. Set the fields the backend knows.
141 pub fn new(name: impl Into<String>) -> Self {
142 Self {
143 name: name.into(),
144 end_of_file: 0,
145 allocation_size: 0,
146 creation_time: 0,
147 last_access_time: 0,
148 last_write_time: 0,
149 change_time: 0,
150 is_directory: false,
151 read_only: false,
152 file_index: 0,
153 }
154 }
155
156 /// SMB2 file attributes (MS-FSCC 2.6) for this file:
157 /// `FILE_ATTRIBUTE_DIRECTORY` for directories and
158 /// `FILE_ATTRIBUTE_READONLY` for read-only files.
159 /// `FILE_ATTRIBUTE_NORMAL` stands alone when neither applies.
160 pub fn attributes(&self) -> u32 {
161 let mut attributes = 0;
162 if self.is_directory {
163 attributes |= FILE_ATTRIBUTE_DIRECTORY;
164 }
165 if self.read_only {
166 attributes |= FILE_ATTRIBUTE_READONLY;
167 }
168 if attributes == 0 {
169 FILE_ATTRIBUTE_NORMAL
170 } else {
171 attributes
172 }
173 }
174}
175
176/// One entry of a directory listing.
177#[derive(Debug, Clone)]
178pub struct DirEntry {
179 pub info: FileInfo,
180}
181
182/// Optional FILETIME values for `set_times`. `None` means "leave unchanged".
183#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
184pub struct FileTimes {
185 pub creation_time: Option<u64>,
186 pub last_access_time: Option<u64>,
187 pub last_write_time: Option<u64>,
188 pub change_time: Option<u64>,
189}
190
191impl FileTimes {
192 /// `FileTimes` with all four fields set to `t`.
193 pub fn all(t: SystemTime) -> Self {
194 let ft = crate::utils::system_time_to_filetime(t);
195 Self {
196 creation_time: Some(ft),
197 last_access_time: Some(ft),
198 last_write_time: Some(ft),
199 change_time: Some(ft),
200 }
201 }
202}
203
204// ---------------------------------------------------------------------------
205// BackendCapabilities
206// ---------------------------------------------------------------------------
207
208/// Static, advertised capabilities of a backend. Built from
209/// [`BackendCapabilities::default`]; every field is public.
210#[derive(Debug, Clone, Copy, Default)]
211#[non_exhaustive]
212pub struct BackendCapabilities {
213 /// If true, all write-class operations are denied at the protocol layer
214 /// before reaching the backend (matches `LocalFsBackend::read_only()`).
215 pub is_read_only: bool,
216 /// True iff the backend treats names case-sensitively.
217 pub case_sensitive: bool,
218}
219
220// ---------------------------------------------------------------------------
221// Traits
222// ---------------------------------------------------------------------------
223
224/// Pluggable storage backend mounted as a share.
225///
226/// Implementors must be `Send + Sync + 'static` so the server can spawn
227/// per-request handlers freely.
228#[async_trait]
229pub trait ShareBackend: Send + Sync + 'static {
230 /// Open or create a file or directory. Returns a fresh handle and what
231 /// the open did to the file.
232 ///
233 /// Fail with [`SmbError::PathNotFound`] when a directory on the way to
234 /// `path` is missing and [`SmbError::NotFound`] when only the last
235 /// component is.
236 async fn open(
237 &self,
238 path: &SmbPath,
239 opts: OpenOptions,
240 ) -> SmbResult<(Box<dyn Handle>, OpenAction)>;
241
242 /// Delete a file or an empty directory.
243 async fn unlink(&self, path: &SmbPath) -> SmbResult<()>;
244
245 /// Rename `from` to `to`.
246 ///
247 /// If `to` names an existing file other than `from`, including another
248 /// hard link to the same file, fail with [`SmbError::Exists`] unless
249 /// `replace_if_exists` is set, in which case the existing file is
250 /// replaced. An existing directory at `to` is never
251 /// replaced: fail with [`SmbError::AccessDenied`].
252 async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()>;
253
254 /// Static capabilities. TREE_CONNECT clamps access to read-only when
255 /// `is_read_only` is set.
256 fn capabilities(&self) -> BackendCapabilities;
257
258 /// Size, free space and identity of the volume behind the share, for the
259 /// filesystem QUERY_INFO classes. The default returns
260 /// [`VolumeInfo::default`].
261 async fn volume_info(&self) -> SmbResult<VolumeInfo> {
262 Ok(VolumeInfo::default())
263 }
264}
265
266/// A live open file or directory handle.
267///
268/// One handle per `CREATE`. `close` runs when CLOSE arrives, and when the
269/// tree, session or connection the open belongs to ends. A durable open's
270/// handle stays open past the end of its session or connection, until its
271/// client takes the open back, the open expires, or something else closes
272/// it; see the crate docs.
273#[async_trait]
274pub trait Handle: Send + Sync {
275 /// Read up to `len` bytes at `offset`. May return fewer.
276 async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes>;
277
278 /// Write `data` at `offset`. Returns bytes written.
279 async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32>;
280
281 /// Write owned `data` at `offset`. Backends that need ownership across a
282 /// blocking boundary can override this to avoid an extra copy.
283 async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
284 self.write(offset, &data).await
285 }
286
287 /// Flush buffered writes. May be a no-op on backends that always flush.
288 async fn flush(&self) -> SmbResult<()>;
289
290 /// Stat: current file info.
291 async fn stat(&self) -> SmbResult<FileInfo>;
292
293 /// Set timestamps on a file or directory. `None` fields leave the
294 /// corresponding time alone.
295 ///
296 /// Return [`SmbError::NotSupported`] for an access or write time the
297 /// backend cannot store. A backend that cannot store a creation time
298 /// ignores it and applies the other fields; a request with only a
299 /// creation time then succeeds and changes nothing.
300 /// `change_time` is the time of the last change: a backend whose
301 /// storage moves it to the current time on every change, as POSIX ctime
302 /// does, may keep doing so and not store the requested value.
303 ///
304 /// `LocalFsBackend` sets access and write times on every host and
305 /// creation time on Windows and macOS. Elsewhere it ignores the creation
306 /// time. The host keeps the change time.
307 async fn set_times(&self, times: FileTimes) -> SmbResult<()>;
308
309 /// Set the attributes (MS-FSCC 2.6) of a file or directory to
310 /// `attributes`, a combination of `FILE_ATTRIBUTE_READONLY` (0x1),
311 /// `HIDDEN` (0x2), `SYSTEM` (0x4), `ARCHIVE` (0x20), `TEMPORARY`
312 /// (0x100), `OFFLINE` (0x1000) and `NOT_CONTENT_INDEXED` (0x2000).
313 /// Flags left out are cleared. The protocol layer calls this only when
314 /// the request differs from the attributes [`Handle::stat`] reports.
315 ///
316 /// Return [`SmbError::NotSupported`] if a flag cannot be stored.
317 ///
318 /// `LocalFsBackend` stores `READONLY` on files: on Unix as the absence
319 /// of write permission bits, on Windows as the host attribute. It
320 /// accepts `ARCHIVE` without storing it and never reports it. Every
321 /// other flag, and `READONLY` on a directory, returns `NotSupported`.
322 async fn set_attributes(&self, attributes: u32) -> SmbResult<()>;
323
324 /// Truncate (or extend) to `len` bytes. For directories: the protocol
325 /// layer rejects this before reaching the backend.
326 async fn truncate(&self, len: u64) -> SmbResult<()>;
327
328 /// List directory entries matching the optional pattern. The pattern
329 /// uses the wildcards of MS-FSA 2.1.4.4: `*` and `?`, and the DOS forms
330 /// `<` (DOS_STAR), `>` (DOS_QM) and `"` (DOS_DOT).
331 /// QUERY_DIRECTORY returns the result as is, so the backend applies the
332 /// pattern. The `.` and `..` entries are left out; QUERY_DIRECTORY adds
333 /// them.
334 async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>>;
335
336 /// Close the handle. Boxed self lets implementors consume internal state.
337 async fn close(self: Box<Self>) -> SmbResult<()>;
338
339 /// Number of hard links to the file, reported as NumberOfLinks by
340 /// FileStandardInformation. `0` means the file has been deleted while
341 /// open. The default reports `1`.
342 async fn link_count(&self) -> SmbResult<u32> {
343 Ok(1)
344 }
345
346 /// True if this directory has no entries other than `.` and `..`,
347 /// including entries [`Handle::list_dir`] leaves out. The default checks
348 /// `list_dir(None)`, so a backend whose listing hides entries overrides
349 /// it.
350 async fn dir_is_empty(&self) -> SmbResult<bool> {
351 Ok(self.list_dir(None).await?.is_empty())
352 }
353
354 /// Watch this directory for changes to its entries made by anyone,
355 /// including outside the server. The server asks one open of a watched
356 /// directory and shares the watch among every watch of that directory;
357 /// it may outlive the handle, and is dropped with the directory's last
358 /// watch. The default returns `Ok(None)`: the server then reports only
359 /// the changes made through it.
360 async fn watch(&self) -> SmbResult<Option<Box<dyn DirWatch>>> {
361 Ok(None)
362 }
363}
364
365/// What a backend saw happen to an entry of a watched directory.
366#[derive(Debug, Clone, PartialEq, Eq)]
367#[non_exhaustive]
368pub enum DirChangeKind {
369 /// The entry appeared.
370 Added,
371 /// The entry went away.
372 Removed,
373 /// The entry was renamed within the directory from `from`.
374 Renamed { from: String },
375 /// The entry's contents were written.
376 Modified,
377 /// The entry's attributes or times changed.
378 AttributesChanged,
379 /// Changes were lost; the client has to list the directory again.
380 Lost,
381 /// The watched directory itself was renamed or moved. Changes to its
382 /// entries keep coming.
383 Moved,
384 /// The watched directory itself was deleted. No change follows.
385 Deleted,
386}
387
388/// A change to an entry of a watched directory, as the backend saw it.
389#[derive(Debug, Clone, PartialEq, Eq)]
390#[non_exhaustive]
391pub struct DirChange {
392 /// Name of the entry in the directory. Empty for
393 /// [`DirChangeKind::Lost`], [`DirChangeKind::Moved`] and
394 /// [`DirChangeKind::Deleted`].
395 pub name: String,
396 /// What happened to the entry.
397 pub kind: DirChangeKind,
398 /// The entry is a directory.
399 pub is_directory: bool,
400}
401
402impl DirChange {
403 /// A change of `kind` to the entry `name`, a directory when
404 /// `is_directory`.
405 pub fn new(name: impl Into<String>, kind: DirChangeKind, is_directory: bool) -> Self {
406 Self {
407 name: name.into(),
408 kind,
409 is_directory,
410 }
411 }
412}
413
414/// Changes to the entries of one directory, from [`Handle::watch`].
415#[async_trait]
416pub trait DirWatch: Send {
417 /// The next changes, in the order they happened; `None` once the watch
418 /// has stopped. A watch that stops without [`DirChangeKind::Deleted`]
419 /// may have lost changes, and the server asks for a new one. The server
420 /// leaves out names it cannot use, and takes a rename from or to one as
421 /// the addition or removal of the other name.
422 ///
423 /// Must be cancel-safe: the server may drop the future before it
424 /// completes, and changes it had not returned must come with the next
425 /// call.
426 async fn next(&mut self) -> Option<Vec<DirChange>>;
427}
428
429/// Backend for the synthetic IPC$ share. `open`, `unlink` and `rename`
430/// return [`SmbError::NotSupported`].
431pub(crate) struct NotSupportedBackend;
432
433#[async_trait]
434impl ShareBackend for NotSupportedBackend {
435 async fn open(
436 &self,
437 _path: &SmbPath,
438 _opts: OpenOptions,
439 ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
440 Err(SmbError::NotSupported)
441 }
442 async fn unlink(&self, _path: &SmbPath) -> SmbResult<()> {
443 Err(SmbError::NotSupported)
444 }
445 async fn rename(&self, _from: &SmbPath, _to: &SmbPath, _replace: bool) -> SmbResult<()> {
446 Err(SmbError::NotSupported)
447 }
448 fn capabilities(&self) -> BackendCapabilities {
449 BackendCapabilities {
450 is_read_only: true,
451 case_sensitive: false,
452 }
453 }
454}
455
456// ---------------------------------------------------------------------------
457// VolumeInfo
458// ---------------------------------------------------------------------------
459
460/// Volume behind a share, as reported by FileFsVolumeInformation,
461/// FileFsSizeInformation, FileFsFullSizeInformation,
462/// FileFsAttributeInformation and FileFsSectorSizeInformation (MS-FSCC 2.5).
463///
464/// Sizes count allocation units of `sectors_per_allocation_unit *
465/// bytes_per_sector` bytes. Built from [`VolumeInfo::default`]; every
466/// field is public.
467#[derive(Debug, Clone, PartialEq, Eq)]
468#[non_exhaustive]
469pub struct VolumeInfo {
470 /// Total allocation units on the volume.
471 pub total_allocation_units: u64,
472 /// Free allocation units available to the share's users, after quotas
473 /// and reserved space.
474 pub caller_available_allocation_units: u64,
475 /// Free allocation units on the volume.
476 pub actual_available_allocation_units: u64,
477 /// Sectors in one allocation unit.
478 pub sectors_per_allocation_unit: u32,
479 /// Bytes in one sector.
480 pub bytes_per_sector: u32,
481 /// Volume serial number.
482 pub serial_number: u32,
483 /// Volume label. `None` reports the share name.
484 pub label: Option<String>,
485 /// Longest file name the volume stores, in characters.
486 pub max_name_length: u32,
487}
488
489impl Default for VolumeInfo {
490 /// A 4 PiB volume with 2 PiB free, in 4 KiB allocation units.
491 fn default() -> Self {
492 Self {
493 total_allocation_units: 1 << 40,
494 caller_available_allocation_units: 1 << 39,
495 actual_available_allocation_units: 1 << 39,
496 sectors_per_allocation_unit: 1,
497 bytes_per_sector: 4096,
498 serial_number: crate::info_class::VOLUME_SERIAL_NUMBER,
499 label: None,
500 max_name_length: 255,
501 }
502 }
503}