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)]
19pub enum OpenIntent {
20 /// `FILE_OPEN`: open existing only; fail if missing.
21 Open,
22 /// `FILE_CREATE`: create new only; fail if exists.
23 Create,
24 /// `FILE_OPEN_IF`: open existing or create new.
25 OpenOrCreate,
26 /// `FILE_OVERWRITE_IF`: open existing (truncating) or create new.
27 OverwriteOrCreate,
28 /// `FILE_OVERWRITE`: open existing and truncate; fail if missing.
29 Truncate,
30}
31
32/// Options passed to `ShareBackend::open`.
33#[derive(Debug, Clone, Copy)]
34pub struct OpenOptions {
35 /// The open was granted `FILE_READ_DATA`, or has no data write access.
36 /// At least one of `read` and `write` is set.
37 pub read: bool,
38 /// The open was granted `FILE_WRITE_DATA` or `FILE_APPEND_DATA`.
39 pub write: bool,
40 /// The open was granted `FILE_WRITE_ATTRIBUTES`: the handle must be able
41 /// to change times and attributes, including on a read-only file.
42 pub write_attributes: bool,
43 /// CREATE disposition.
44 pub intent: OpenIntent,
45 /// `FILE_DIRECTORY_FILE` was set on CREATE: open or create a directory.
46 pub directory: bool,
47 /// `FILE_NON_DIRECTORY_FILE` was set on CREATE: fail if the target is a directory.
48 pub non_directory: bool,
49 /// `FILE_DELETE_ON_CLOSE` was set on CREATE.
50 pub delete_on_close: bool,
51}
52
53impl Default for OpenOptions {
54 fn default() -> Self {
55 Self {
56 read: true,
57 write: false,
58 write_attributes: false,
59 intent: OpenIntent::Open,
60 directory: false,
61 non_directory: false,
62 delete_on_close: false,
63 }
64 }
65}
66
67// ---------------------------------------------------------------------------
68// FileInfo / DirEntry / FileTimes
69// ---------------------------------------------------------------------------
70
71/// Filesystem-style metadata for a single file or directory.
72#[derive(Debug, Clone)]
73pub struct FileInfo {
74 /// Display name (last component). For QUERY_INFO at the share root this
75 /// is the share name.
76 pub name: String,
77 /// File size in bytes.
78 pub end_of_file: u64,
79 /// Allocation size, usually `end_of_file` rounded up to a cluster.
80 /// Backends may return `end_of_file`.
81 pub allocation_size: u64,
82 /// FILETIME (100ns ticks since 1601).
83 pub creation_time: u64,
84 pub last_access_time: u64,
85 pub last_write_time: u64,
86 pub change_time: u64,
87 /// True if this is a directory.
88 pub is_directory: bool,
89 /// The file has `FILE_ATTRIBUTE_READONLY`.
90 pub read_only: bool,
91 /// Stable id of the file, unique within the share including any mounts
92 /// below the share root, reported as the file id by QUERY_INFO and
93 /// QUERY_DIRECTORY. Backends return the same value from `Handle::stat`
94 /// and `Handle::list_dir` for the same file, across opens and renames.
95 /// `0` if the backend has none.
96 pub file_index: u64,
97}
98
99// File attributes (MS-FSCC 2.6).
100pub(crate) const FILE_ATTRIBUTE_READONLY: u32 = 0x0000_0001;
101pub(crate) const FILE_ATTRIBUTE_HIDDEN: u32 = 0x0000_0002;
102pub(crate) const FILE_ATTRIBUTE_SYSTEM: u32 = 0x0000_0004;
103pub(crate) const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
104pub(crate) const FILE_ATTRIBUTE_ARCHIVE: u32 = 0x0000_0020;
105pub(crate) const FILE_ATTRIBUTE_NORMAL: u32 = 0x0000_0080;
106pub(crate) const FILE_ATTRIBUTE_TEMPORARY: u32 = 0x0000_0100;
107pub(crate) const FILE_ATTRIBUTE_OFFLINE: u32 = 0x0000_1000;
108pub(crate) const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: u32 = 0x0000_2000;
109
110/// Attributes FileBasicInformation can set (MS-FSA 2.1.5.15.2).
111pub(crate) const VALID_SET_ATTRIBUTES: u32 = FILE_ATTRIBUTE_READONLY
112 | FILE_ATTRIBUTE_HIDDEN
113 | FILE_ATTRIBUTE_SYSTEM
114 | FILE_ATTRIBUTE_ARCHIVE
115 | FILE_ATTRIBUTE_TEMPORARY
116 | FILE_ATTRIBUTE_OFFLINE
117 | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
118
119impl FileInfo {
120 /// SMB2 file attributes (MS-FSCC 2.6) for this file:
121 /// `FILE_ATTRIBUTE_DIRECTORY` for directories and
122 /// `FILE_ATTRIBUTE_READONLY` for read-only files.
123 /// `FILE_ATTRIBUTE_NORMAL` stands alone when neither applies.
124 pub fn attributes(&self) -> u32 {
125 let mut attributes = 0;
126 if self.is_directory {
127 attributes |= FILE_ATTRIBUTE_DIRECTORY;
128 }
129 if self.read_only {
130 attributes |= FILE_ATTRIBUTE_READONLY;
131 }
132 if attributes == 0 {
133 FILE_ATTRIBUTE_NORMAL
134 } else {
135 attributes
136 }
137 }
138}
139
140/// One entry of a directory listing.
141#[derive(Debug, Clone)]
142pub struct DirEntry {
143 pub info: FileInfo,
144}
145
146/// Optional FILETIME values for `set_times`. `None` means "leave unchanged".
147#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
148pub struct FileTimes {
149 pub creation_time: Option<u64>,
150 pub last_access_time: Option<u64>,
151 pub last_write_time: Option<u64>,
152 pub change_time: Option<u64>,
153}
154
155impl FileTimes {
156 /// `FileTimes` with all four fields set to `t`.
157 pub fn all(t: SystemTime) -> Self {
158 let ft = crate::utils::system_time_to_filetime(t);
159 Self {
160 creation_time: Some(ft),
161 last_access_time: Some(ft),
162 last_write_time: Some(ft),
163 change_time: Some(ft),
164 }
165 }
166}
167
168// ---------------------------------------------------------------------------
169// BackendCapabilities
170// ---------------------------------------------------------------------------
171
172/// Static, advertised capabilities of a backend.
173#[derive(Debug, Clone, Copy, Default)]
174pub struct BackendCapabilities {
175 /// If true, all write-class operations are denied at the protocol layer
176 /// before reaching the backend (matches `LocalFsBackend::read_only()`).
177 pub is_read_only: bool,
178 /// True iff the backend treats names case-sensitively.
179 pub case_sensitive: bool,
180}
181
182// ---------------------------------------------------------------------------
183// Traits
184// ---------------------------------------------------------------------------
185
186/// Pluggable storage backend mounted as a share.
187///
188/// Implementors must be `Send + Sync + 'static` so the server can spawn
189/// per-request handlers freely.
190#[async_trait]
191pub trait ShareBackend: Send + Sync + 'static {
192 /// Open or create a file or directory. Returns a fresh handle.
193 async fn open(&self, path: &SmbPath, opts: OpenOptions) -> SmbResult<Box<dyn Handle>>;
194
195 /// Delete a file or an empty directory.
196 async fn unlink(&self, path: &SmbPath) -> SmbResult<()>;
197
198 /// Rename `from` to `to`.
199 ///
200 /// If `to` names an existing file other than `from`, including another
201 /// hard link to the same file, fail with [`SmbError::Exists`] unless
202 /// `replace_if_exists` is set, in which case the existing file is
203 /// replaced. An existing directory at `to` is never
204 /// replaced: fail with [`SmbError::AccessDenied`].
205 async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()>;
206
207 /// Static capabilities. TREE_CONNECT clamps access to read-only when
208 /// `is_read_only` is set.
209 fn capabilities(&self) -> BackendCapabilities;
210}
211
212/// A live open file or directory handle.
213///
214/// One handle per `CREATE`. The handle is dropped when CLOSE arrives or the
215/// session goes away.
216#[async_trait]
217pub trait Handle: Send + Sync {
218 /// Read up to `len` bytes at `offset`. May return fewer.
219 async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes>;
220
221 /// Write `data` at `offset`. Returns bytes written.
222 async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32>;
223
224 /// Write owned `data` at `offset`. Backends that need ownership across a
225 /// blocking boundary can override this to avoid an extra copy.
226 async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
227 self.write(offset, &data).await
228 }
229
230 /// Flush buffered writes. May be a no-op on backends that always flush.
231 async fn flush(&self) -> SmbResult<()>;
232
233 /// Stat: current file info.
234 async fn stat(&self) -> SmbResult<FileInfo>;
235
236 /// Set timestamps on a file or directory. `None` fields leave the
237 /// corresponding time alone.
238 ///
239 /// Return [`SmbError::NotSupported`] for an access or write time the
240 /// backend cannot store. A backend that cannot store a creation time
241 /// ignores it and applies the other fields; a request with only a
242 /// creation time then succeeds and changes nothing.
243 /// `change_time` is the time of the last change: a backend whose
244 /// storage moves it to the current time on every change, as POSIX ctime
245 /// does, may keep doing so and not store the requested value.
246 ///
247 /// `LocalFsBackend` sets access and write times on every host and
248 /// creation time on Windows and macOS. Elsewhere it ignores the creation
249 /// time. The host keeps the change time.
250 async fn set_times(&self, times: FileTimes) -> SmbResult<()>;
251
252 /// Set the attributes (MS-FSCC 2.6) of a file or directory to
253 /// `attributes`, a combination of `FILE_ATTRIBUTE_READONLY` (0x1),
254 /// `HIDDEN` (0x2), `SYSTEM` (0x4), `ARCHIVE` (0x20), `TEMPORARY`
255 /// (0x100), `OFFLINE` (0x1000) and `NOT_CONTENT_INDEXED` (0x2000).
256 /// Flags left out are cleared. The protocol layer calls this only when
257 /// the request differs from the attributes [`Handle::stat`] reports.
258 ///
259 /// Return [`SmbError::NotSupported`] if a flag cannot be stored.
260 ///
261 /// `LocalFsBackend` stores `READONLY` on files: on Unix as the absence
262 /// of write permission bits, on Windows as the host attribute. It
263 /// accepts `ARCHIVE` without storing it and never reports it. Every
264 /// other flag, and `READONLY` on a directory, returns `NotSupported`.
265 async fn set_attributes(&self, attributes: u32) -> SmbResult<()>;
266
267 /// Truncate (or extend) to `len` bytes. For directories: the protocol
268 /// layer rejects this before reaching the backend.
269 async fn truncate(&self, len: u64) -> SmbResult<()>;
270
271 /// List directory entries matching the optional pattern. The pattern
272 /// uses the wildcards of MS-FSA 2.1.4.4: `*` and `?`, and the DOS forms
273 /// `<` (DOS_STAR), `>` (DOS_QM) and `"` (DOS_DOT).
274 /// QUERY_DIRECTORY returns the result as is, so the backend applies the
275 /// pattern.
276 async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>>;
277
278 /// Close the handle. Boxed self lets implementors consume internal state.
279 async fn close(self: Box<Self>) -> SmbResult<()>;
280}
281
282/// Backend for the synthetic IPC$ share. `open`, `unlink` and `rename`
283/// return [`SmbError::NotSupported`].
284pub(crate) struct NotSupportedBackend;
285
286#[async_trait]
287impl ShareBackend for NotSupportedBackend {
288 async fn open(&self, _path: &SmbPath, _opts: OpenOptions) -> SmbResult<Box<dyn Handle>> {
289 Err(SmbError::NotSupported)
290 }
291 async fn unlink(&self, _path: &SmbPath) -> SmbResult<()> {
292 Err(SmbError::NotSupported)
293 }
294 async fn rename(&self, _from: &SmbPath, _to: &SmbPath, _replace: bool) -> SmbResult<()> {
295 Err(SmbError::NotSupported)
296 }
297 fn capabilities(&self) -> BackendCapabilities {
298 BackendCapabilities {
299 is_read_only: true,
300 case_sensitive: false,
301 }
302 }
303}