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/// Translated SMB CREATE intent — the small set of cases v1 cares about.
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`. v1 keeps this tight on purpose;
33/// extra knobs become methods later if a backend genuinely needs them.
34#[derive(Debug, Clone, Copy)]
35pub struct OpenOptions {
36 /// Read access requested.
37 pub read: bool,
38 /// Write access requested.
39 pub write: bool,
40 /// CREATE disposition.
41 pub intent: OpenIntent,
42 /// `FILE_DIRECTORY_FILE` was set on CREATE — open or create a directory.
43 pub directory: bool,
44 /// `FILE_NON_DIRECTORY_FILE` was set on CREATE — fail if the target is a directory.
45 pub non_directory: bool,
46 /// `FILE_DELETE_ON_CLOSE` was set on CREATE.
47 pub delete_on_close: bool,
48}
49
50impl Default for OpenOptions {
51 fn default() -> Self {
52 Self {
53 read: true,
54 write: false,
55 intent: OpenIntent::Open,
56 directory: false,
57 non_directory: false,
58 delete_on_close: false,
59 }
60 }
61}
62
63// ---------------------------------------------------------------------------
64// FileInfo / DirEntry / FileTimes
65// ---------------------------------------------------------------------------
66
67/// Filesystem-style metadata for a single file or directory.
68#[derive(Debug, Clone)]
69pub struct FileInfo {
70 /// Display name (last component). For QUERY_INFO at the share root this
71 /// is the share name.
72 pub name: String,
73 /// File size in bytes.
74 pub end_of_file: u64,
75 /// Allocation size — typically `end_of_file` rounded up to a cluster size.
76 /// v1 backends may safely return the same value as `end_of_file`.
77 pub allocation_size: u64,
78 /// FILETIME (100ns ticks since 1601).
79 pub creation_time: u64,
80 pub last_access_time: u64,
81 pub last_write_time: u64,
82 pub change_time: u64,
83 /// True if this is a directory.
84 pub is_directory: bool,
85 /// Optional 64-bit unique file id (for `FileInternalInformation`). v1 may
86 /// return `0` if unavailable; the dispatcher will substitute the FileId.
87 pub file_index: u64,
88}
89
90impl FileInfo {
91 /// SMB2 file attributes (MS-FSCC §2.6) for this file. v1 returns
92 /// `FILE_ATTRIBUTE_DIRECTORY` for dirs, `FILE_ATTRIBUTE_NORMAL` (0x80) for
93 /// regular files. (`FILE_ATTRIBUTE_NORMAL` MUST be the only attribute set
94 /// when used.)
95 pub fn attributes(&self) -> u32 {
96 const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;
97 const FILE_ATTRIBUTE_NORMAL: u32 = 0x0000_0080;
98 if self.is_directory {
99 FILE_ATTRIBUTE_DIRECTORY
100 } else {
101 FILE_ATTRIBUTE_NORMAL
102 }
103 }
104}
105
106/// One entry of a directory listing.
107#[derive(Debug, Clone)]
108pub struct DirEntry {
109 pub info: FileInfo,
110}
111
112/// Optional FILETIME values for `set_times`. `None` means "leave unchanged".
113#[derive(Debug, Clone, Copy, Default)]
114pub struct FileTimes {
115 pub creation_time: Option<u64>,
116 pub last_access_time: Option<u64>,
117 pub last_write_time: Option<u64>,
118 pub change_time: Option<u64>,
119}
120
121impl FileTimes {
122 /// Convenience: convert `SystemTime` into a `FileTimes` setting all four
123 /// fields to the same instant.
124 pub fn all(t: SystemTime) -> Self {
125 let ft = crate::utils::system_time_to_filetime(t);
126 Self {
127 creation_time: Some(ft),
128 last_access_time: Some(ft),
129 last_write_time: Some(ft),
130 change_time: Some(ft),
131 }
132 }
133}
134
135// ---------------------------------------------------------------------------
136// BackendCapabilities
137// ---------------------------------------------------------------------------
138
139/// Static, advertised capabilities of a backend.
140///
141/// Kept small intentionally — extending requires discussing with the maintainer.
142#[derive(Debug, Clone, Copy, Default)]
143pub struct BackendCapabilities {
144 /// If true, all write-class operations are denied at the protocol layer
145 /// before reaching the backend (matches `LocalFsBackend::read_only()`).
146 pub is_read_only: bool,
147 /// True iff the backend treats names case-sensitively.
148 pub case_sensitive: bool,
149}
150
151// ---------------------------------------------------------------------------
152// Traits
153// ---------------------------------------------------------------------------
154
155/// Pluggable storage backend mounted as a share.
156///
157/// Implementors must be `Send + Sync + 'static` so the server can spawn
158/// per-request handlers freely.
159#[async_trait]
160pub trait ShareBackend: Send + Sync + 'static {
161 /// Open or create a file or directory. Returns a fresh handle.
162 async fn open(&self, path: &SmbPath, opts: OpenOptions) -> SmbResult<Box<dyn Handle>>;
163
164 /// Unlink (delete) a file. Directories: must be empty. v1 does not
165 /// recursively delete.
166 async fn unlink(&self, path: &SmbPath) -> SmbResult<()>;
167
168 /// Rename `from` to `to`. The backend must reject if `to` already exists.
169 async fn rename(&self, from: &SmbPath, to: &SmbPath) -> SmbResult<()>;
170
171 /// Static capabilities. The dispatcher consults these at TREE_CONNECT and
172 /// uses `is_read_only` to clamp authz.
173 fn capabilities(&self) -> BackendCapabilities;
174}
175
176/// A live open file or directory handle.
177///
178/// One handle per `CREATE`. The handle is dropped when CLOSE arrives or the
179/// session goes away.
180#[async_trait]
181pub trait Handle: Send + Sync {
182 /// Read up to `len` bytes at `offset`. May return fewer.
183 async fn read(&self, offset: u64, len: u32) -> SmbResult<bytes::Bytes>;
184
185 /// Write `data` at `offset`. Returns bytes written.
186 async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32>;
187
188 /// Write owned `data` at `offset`. Backends that need ownership across a
189 /// blocking boundary can override this to avoid an extra copy.
190 async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
191 self.write(offset, &data).await
192 }
193
194 /// Flush buffered writes. May be a no-op on backends that always flush.
195 async fn flush(&self) -> SmbResult<()>;
196
197 /// Stat: current file info.
198 async fn stat(&self) -> SmbResult<FileInfo>;
199
200 /// Set timestamps. `None` fields leave the corresponding field alone.
201 async fn set_times(&self, times: FileTimes) -> SmbResult<()>;
202
203 /// Truncate (or extend) to `len` bytes. For directories: the protocol
204 /// layer rejects this before reaching the backend.
205 async fn truncate(&self, len: u64) -> SmbResult<()>;
206
207 /// List directory entries matching the optional pattern. v1 ignores
208 /// `pattern` if the backend doesn't implement matching — the dispatcher
209 /// post-filters as needed for QUERY_DIRECTORY.
210 async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<DirEntry>>;
211
212 /// Close the handle. Boxed self lets implementors consume internal state.
213 async fn close(self: Box<Self>) -> SmbResult<()>;
214}
215
216/// No-op backend used for the synthetic IPC$ share. Every method returns
217/// [`SmbError::NotSupported`]. Exists so we can hand a `ShareBackend`
218/// implementor to the IPC$ tree without any real storage attached.
219pub(crate) struct NotSupportedBackend;
220
221#[async_trait]
222impl ShareBackend for NotSupportedBackend {
223 async fn open(&self, _path: &SmbPath, _opts: OpenOptions) -> SmbResult<Box<dyn Handle>> {
224 Err(SmbError::NotSupported)
225 }
226 async fn unlink(&self, _path: &SmbPath) -> SmbResult<()> {
227 Err(SmbError::NotSupported)
228 }
229 async fn rename(&self, _from: &SmbPath, _to: &SmbPath) -> SmbResult<()> {
230 Err(SmbError::NotSupported)
231 }
232 fn capabilities(&self) -> BackendCapabilities {
233 BackendCapabilities {
234 is_read_only: true,
235 case_sensitive: false,
236 }
237 }
238}