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.
111 pub file_index: u64,
112}
113
114// File attributes (MS-FSCC 2.6).
115pub(crate) const FILE_ATTRIBUTE_READONLY: u32 = 0x0000_0001;
116pub(crate) const FILE_ATTRIBUTE_HIDDEN: u32 = 0x0000_0002;
117pub(crate) const FILE_ATTRIBUTE_SYSTEM: u32 = 0x0000_0004;
118pub(crate) const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
119pub(crate) const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x0000_0020;
120pub(crate) const FILE_ATTRIBUTE_NORMAL: u32 = 0x0000_0080;
121pub(crate) const FILE_ATTRIBUTE_TEMPORARY: u32 = 0x0000_0100;
122pub(crate) const FILE_ATTRIBUTE_OFFLINE: u32 = 0x0000_1000;
123pub(crate) const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: u32 = 0x0000_2000;
124
125/// Attributes FileBasicInformation can set (MS-FSA 2.1.5.15.2).
126pub(crate) const VALID_SET_ATTRIBUTES: u32 = FILE_ATTRIBUTE_READONLY
127 | FILE_ATTRIBUTE_HIDDEN
128 | FILE_ATTRIBUTE_SYSTEM
129 | FILE_ATTRIBUTE_ARCHIVE
130 | FILE_ATTRIBUTE_TEMPORARY
131 | FILE_ATTRIBUTE_OFFLINE
132 | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
133
134impl FileInfo {
135 /// A zero-length, writable file named `name` with no times and no file
136 /// id. Set the fields the backend knows.
137 pub fn new(name: impl Into<String>) -> Self {
138 Self {
139 name: name.into(),
140 end_of_file: 0,
141 allocation_size: 0,
142 creation_time: 0,
143 last_access_time: 0,
144 last_write_time: 0,
145 change_time: 0,
146 is_directory: false,
147 read_only: false,
148 file_index: 0,
149 }
150 }
151
152 /// SMB2 file attributes (MS-FSCC 2.6) for this file:
153 /// `FILE_ATTRIBUTE_DIRECTORY` for directories and
154 /// `FILE_ATTRIBUTE_READONLY` for read-only files.
155 /// `FILE_ATTRIBUTE_NORMAL` stands alone when neither applies.
156 pub fn attributes(&self) -> u32 {
157 let mut attributes = 0;
158 if self.is_directory {
159 attributes |= FILE_ATTRIBUTE_DIRECTORY;
160 }
161 if self.read_only {
162 attributes |= FILE_ATTRIBUTE_READONLY;
163 }
164 if attributes == 0 {
165 FILE_ATTRIBUTE_NORMAL
166 } else {
167 attributes
168 }
169 }
170}
171
172/// One entry of a directory listing.
173#[derive(Debug, Clone)]
174pub struct DirEntry {
175 pub info: FileInfo,
176}
177
178/// Optional FILETIME values for `set_times`. `None` means "leave unchanged".
179#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
180pub struct FileTimes {
181 pub creation_time: Option<u64>,
182 pub last_access_time: Option<u64>,
183 pub last_write_time: Option<u64>,
184 pub change_time: Option<u64>,
185}
186
187impl FileTimes {
188 /// `FileTimes` with all four fields set to `t`.
189 pub fn all(t: SystemTime) -> Self {
190 let ft = crate::utils::system_time_to_filetime(t);
191 Self {
192 creation_time: Some(ft),
193 last_access_time: Some(ft),
194 last_write_time: Some(ft),
195 change_time: Some(ft),
196 }
197 }
198}
199
200// ---------------------------------------------------------------------------
201// BackendCapabilities
202// ---------------------------------------------------------------------------
203
204/// Static, advertised capabilities of a backend. Built from
205/// [`BackendCapabilities::default`]; every field is public.
206#[derive(Debug, Clone, Copy, Default)]
207#[non_exhaustive]
208pub struct BackendCapabilities {
209 /// If true, all write-class operations are denied at the protocol layer
210 /// before reaching the backend (matches `LocalFsBackend::read_only()`).
211 pub is_read_only: bool,
212 /// True iff the backend treats names case-sensitively.
213 pub case_sensitive: bool,
214}
215
216// ---------------------------------------------------------------------------
217// Traits
218// ---------------------------------------------------------------------------
219
220/// Pluggable storage backend mounted as a share.
221///
222/// Implementors must be `Send + Sync + 'static` so the server can spawn
223/// per-request handlers freely.
224#[async_trait]
225pub trait ShareBackend: Send + Sync + 'static {
226 /// Open or create a file or directory. Returns a fresh handle and what
227 /// the open did to the file.
228 ///
229 /// Fail with [`SmbError::PathNotFound`] when a directory on the way to
230 /// `path` is missing and [`SmbError::NotFound`] when only the last
231 /// component is.
232 async fn open(
233 &self,
234 path: &SmbPath,
235 opts: OpenOptions,
236 ) -> SmbResult<(Box<dyn Handle>, OpenAction)>;
237
238 /// Delete a file or an empty directory.
239 async fn unlink(&self, path: &SmbPath) -> SmbResult<()>;
240
241 /// Rename `from` to `to`.
242 ///
243 /// If `to` names an existing file other than `from`, including another
244 /// hard link to the same file, fail with [`SmbError::Exists`] unless
245 /// `replace_if_exists` is set, in which case the existing file is
246 /// replaced. An existing directory at `to` is never
247 /// replaced: fail with [`SmbError::AccessDenied`].
248 async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()>;
249
250 /// Static capabilities. TREE_CONNECT clamps access to read-only when
251 /// `is_read_only` is set.
252 fn capabilities(&self) -> BackendCapabilities;
253
254 /// Size, free space and identity of the volume behind the share, for the
255 /// filesystem QUERY_INFO classes. The default returns
256 /// [`VolumeInfo::default`].
257 async fn volume_info(&self) -> SmbResult<VolumeInfo> {
258 Ok(VolumeInfo::default())
259 }
260}
261
262/// A live open file or directory handle.
263///
264/// One handle per `CREATE`. `close` runs when CLOSE arrives, and when the
265/// tree, session or connection the open belongs to ends.
266#[async_trait]
267pub trait Handle: Send + Sync {
268 /// Read up to `len` bytes at `offset`. May return fewer.
269 async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes>;
270
271 /// Write `data` at `offset`. Returns bytes written.
272 async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32>;
273
274 /// Write owned `data` at `offset`. Backends that need ownership across a
275 /// blocking boundary can override this to avoid an extra copy.
276 async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
277 self.write(offset, &data).await
278 }
279
280 /// Flush buffered writes. May be a no-op on backends that always flush.
281 async fn flush(&self) -> SmbResult<()>;
282
283 /// Stat: current file info.
284 async fn stat(&self) -> SmbResult<FileInfo>;
285
286 /// Set timestamps on a file or directory. `None` fields leave the
287 /// corresponding time alone.
288 ///
289 /// Return [`SmbError::NotSupported`] for an access or write time the
290 /// backend cannot store. A backend that cannot store a creation time
291 /// ignores it and applies the other fields; a request with only a
292 /// creation time then succeeds and changes nothing.
293 /// `change_time` is the time of the last change: a backend whose
294 /// storage moves it to the current time on every change, as POSIX ctime
295 /// does, may keep doing so and not store the requested value.
296 ///
297 /// `LocalFsBackend` sets access and write times on every host and
298 /// creation time on Windows and macOS. Elsewhere it ignores the creation
299 /// time. The host keeps the change time.
300 async fn set_times(&self, times: FileTimes) -> SmbResult<()>;
301
302 /// Set the attributes (MS-FSCC 2.6) of a file or directory to
303 /// `attributes`, a combination of `FILE_ATTRIBUTE_READONLY` (0x1),
304 /// `HIDDEN` (0x2), `SYSTEM` (0x4), `ARCHIVE` (0x20), `TEMPORARY`
305 /// (0x100), `OFFLINE` (0x1000) and `NOT_CONTENT_INDEXED` (0x2000).
306 /// Flags left out are cleared. The protocol layer calls this only when
307 /// the request differs from the attributes [`Handle::stat`] reports.
308 ///
309 /// Return [`SmbError::NotSupported`] if a flag cannot be stored.
310 ///
311 /// `LocalFsBackend` stores `READONLY` on files: on Unix as the absence
312 /// of write permission bits, on Windows as the host attribute. It
313 /// accepts `ARCHIVE` without storing it and never reports it. Every
314 /// other flag, and `READONLY` on a directory, returns `NotSupported`.
315 async fn set_attributes(&self, attributes: u32) -> SmbResult<()>;
316
317 /// Truncate (or extend) to `len` bytes. For directories: the protocol
318 /// layer rejects this before reaching the backend.
319 async fn truncate(&self, len: u64) -> SmbResult<()>;
320
321 /// List directory entries matching the optional pattern. The pattern
322 /// uses the wildcards of MS-FSA 2.1.4.4: `*` and `?`, and the DOS forms
323 /// `<` (DOS_STAR), `>` (DOS_QM) and `"` (DOS_DOT).
324 /// QUERY_DIRECTORY returns the result as is, so the backend applies the
325 /// pattern. The `.` and `..` entries are left out; QUERY_DIRECTORY adds
326 /// them.
327 async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>>;
328
329 /// Close the handle. Boxed self lets implementors consume internal state.
330 async fn close(self: Box<Self>) -> SmbResult<()>;
331
332 /// Number of hard links to the file, reported as NumberOfLinks by
333 /// FileStandardInformation. `0` means the file has been deleted while
334 /// open. The default reports `1`.
335 async fn link_count(&self) -> SmbResult<u32> {
336 Ok(1)
337 }
338
339 /// True if this directory has no entries other than `.` and `..`,
340 /// including entries [`Handle::list_dir`] leaves out. The default checks
341 /// `list_dir(None)`, so a backend whose listing hides entries overrides
342 /// it.
343 async fn dir_is_empty(&self) -> SmbResult<bool> {
344 Ok(self.list_dir(None).await?.is_empty())
345 }
346}
347
348/// Backend for the synthetic IPC$ share. `open`, `unlink` and `rename`
349/// return [`SmbError::NotSupported`].
350pub(crate) struct NotSupportedBackend;
351
352#[async_trait]
353impl ShareBackend for NotSupportedBackend {
354 async fn open(
355 &self,
356 _path: &SmbPath,
357 _opts: OpenOptions,
358 ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
359 Err(SmbError::NotSupported)
360 }
361 async fn unlink(&self, _path: &SmbPath) -> SmbResult<()> {
362 Err(SmbError::NotSupported)
363 }
364 async fn rename(&self, _from: &SmbPath, _to: &SmbPath, _replace: bool) -> SmbResult<()> {
365 Err(SmbError::NotSupported)
366 }
367 fn capabilities(&self) -> BackendCapabilities {
368 BackendCapabilities {
369 is_read_only: true,
370 case_sensitive: false,
371 }
372 }
373}
374
375// ---------------------------------------------------------------------------
376// VolumeInfo
377// ---------------------------------------------------------------------------
378
379/// Volume behind a share, as reported by FileFsVolumeInformation,
380/// FileFsSizeInformation, FileFsFullSizeInformation,
381/// FileFsAttributeInformation and FileFsSectorSizeInformation (MS-FSCC 2.5).
382///
383/// Sizes count allocation units of `sectors_per_allocation_unit *
384/// bytes_per_sector` bytes. Built from [`VolumeInfo::default`]; every
385/// field is public.
386#[derive(Debug, Clone, PartialEq, Eq)]
387#[non_exhaustive]
388pub struct VolumeInfo {
389 /// Total allocation units on the volume.
390 pub total_allocation_units: u64,
391 /// Free allocation units available to the share's users, after quotas
392 /// and reserved space.
393 pub caller_available_allocation_units: u64,
394 /// Free allocation units on the volume.
395 pub actual_available_allocation_units: u64,
396 /// Sectors in one allocation unit.
397 pub sectors_per_allocation_unit: u32,
398 /// Bytes in one sector.
399 pub bytes_per_sector: u32,
400 /// Volume serial number.
401 pub serial_number: u32,
402 /// Volume label. `None` reports the share name.
403 pub label: Option<String>,
404 /// Longest file name the volume stores, in characters.
405 pub max_name_length: u32,
406}
407
408impl Default for VolumeInfo {
409 /// A 4 PiB volume with 2 PiB free, in 4 KiB allocation units.
410 fn default() -> Self {
411 Self {
412 total_allocation_units: 1 << 40,
413 caller_available_allocation_units: 1 << 39,
414 actual_available_allocation_units: 1 << 39,
415 sectors_per_allocation_unit: 1,
416 bytes_per_sector: 4096,
417 serial_number: crate::info_class::VOLUME_SERIAL_NUMBER,
418 label: None,
419 max_name_length: 255,
420 }
421 }
422}