smb_server/lib.rs
1//! SMB2/3 file-sharing server with pluggable storage backends.
2//!
3//! Example:
4//!
5//! ```no_run
6//! use smb_server::{SmbServer, Share, Access, ShareBackend};
7//! # async fn run<B: ShareBackend>(backend: B) -> Result<(), Box<dyn std::error::Error>> {
8//! SmbServer::builder()
9//! .listen("0.0.0.0:4445".parse()?)
10//! .user("alice", "password")
11//! .share(Share::new("home", backend).user("alice", Access::ReadWrite))
12//! .build()?
13//! .serve()
14//! .await?;
15//! # Ok(()) }
16//! ```
17//!
18//! # Writing a backend
19//!
20//! A share serves any [`ShareBackend`]. Each CREATE calls
21//! [`ShareBackend::open`], which returns a [`Handle`] and the
22//! [`OpenAction`] it took; CREATE reports the action to the client. The
23//! handle serves READ, WRITE, FLUSH, QUERY_INFO, QUERY_DIRECTORY and
24//! SET_INFO on that open until the open is closed. `LocalFsBackend`
25//! (feature `localfs`) is the reference implementation.
26//!
27//! What the protocol layer does around the backend calls:
28//!
29//! - Paths arrive as [`SmbPath`], relative to the share root. `.` components
30//! are dropped; `..`, empty components, `<>:"|?*`, control characters and
31//! stream names are rejected before the backend sees them. The empty path
32//! is the share root.
33//! - `open` fails with [`SmbError::PathNotFound`] when a directory on the
34//! way to the path is missing, and with [`SmbError::NotFound`] when only
35//! the last component is. Clients see STATUS_OBJECT_PATH_NOT_FOUND and
36//! STATUS_OBJECT_NAME_NOT_FOUND.
37//! - Share permissions and the access the client asked for are checked
38//! before `open`. [`OpenOptions`] carries the result: `read`, `write` and
39//! `write_attributes` reflect the access granted to the open. READ and
40//! WRITE on a handle without the matching access fail before the handle
41//! is called. When [`BackendCapabilities::is_read_only`] is set, trees on
42//! the share get read access only, so opens that ask for write access,
43//! and dispositions that create or truncate, fail before `open`.
44//! - Share modes, byte-range locks and the delete-pending flag are kept by
45//! the protocol layer per share, across every connection, keyed by
46//! [`FileInfo::file_index`], or by path when it is 0. Two shares over
47//! the same directory do not see each other's opens. A CREATE that would
48//! truncate first opens the file without write access, runs the checks
49//! and enters the open in the table, so the sharing mode holds while
50//! `open` truncates. Any other CREATE refused by the share-mode check has
51//! already called `open` and closes the new handle again.
52//! - [`Handle::close`] runs on every path that ends an open: CLOSE,
53//! TREE_DISCONNECT, LOGOFF, the end of a session or connection, and
54//! [`ConfigHandle`] changes that end sessions or trees. Before it,
55//! [`Handle::set_times`] puts back access and write times that
56//! FileBasicInformation froze or set through that open.
57//! - Delete-on-close: [`OpenOptions::delete_on_close`] and
58//! FileDispositionInformation make the file delete-pending. When its last
59//! open ends, on any of the paths above, the protocol layer calls
60//! [`Handle::close`] and then [`ShareBackend::unlink`] on the file's
61//! current path. `open` doesn't delete anything itself. Read-only files
62//! are refused before that point, and so, for SET_INFO, are directories
63//! that [`Handle::dir_is_empty`] reports as not empty. `unlink` returns
64//! [`SmbError::NotEmpty`] for a directory that has entries; the directory
65//! then stays.
66//! - A rename through SET_INFO calls [`ShareBackend::rename`] and then moves
67//! the path of every open at or below the old name. Renames on one share
68//! run one at a time. The backend keeps those handles working on the
69//! renamed file.
70//! - A CREATE that makes or overwrites a file passes the attributes it asks
71//! for to [`Handle::set_attributes`] when they differ from what
72//! [`Handle::stat`] reports. If that returns [`SmbError::NotSupported`],
73//! it retries with READONLY alone when that was asked for; the CREATE
74//! succeeds either way.
75//! - FileBasicInformation passes [`Handle::set_attributes`] and
76//! [`Handle::set_times`] only the values that differ from what
77//! [`Handle::stat`] reports. After a write or truncate, `set_times` also
78//! puts back the times FileBasicInformation froze or set.
79//! [`Handle::truncate`] is never called on a directory.
80//! - QUERY_DIRECTORY calls [`Handle::list_dir`] with the search pattern on
81//! the first query and on a restart, then pages through the returned
82//! entries itself. Below the share root it adds `.` and `..`, and opens
83//! the parent directory to describe `..`.
84//! - FileStandardInformation and FileAllInformation report
85//! [`Handle::link_count`] as NumberOfLinks, and DeletePending when the
86//! file is delete-pending or has no links left. The filesystem
87//! QUERY_INFO classes, and the VolumeId of the on-disk id CREATE context,
88//! come from [`ShareBackend::volume_info`].
89//! - READ and WRITE lengths are bounded by the negotiated maximum sizes.
90//! - Each [`SmbError`] maps to one NTSTATUS for the client; see
91//! [`SmbError::to_nt_status`].
92//!
93//! A handle is dropped without [`Handle::close`] when the task serving its
94//! connection panics or is cancelled, and when a [`ConfigHandle`] call that
95//! ends its session or tree is cancelled, so release resources in `Drop` as
96//! well.
97//!
98//! Later releases may add methods with default bodies, fields to
99//! [`FileInfo`], [`BackendCapabilities`] and [`VolumeInfo`], and variants
100//! to [`OpenIntent`]. A backend that implements the required methods,
101//! builds those types through [`FileInfo::new`] and the `Default` impls, and
102//! matches `OpenIntent` with a wildcard arm keeps compiling.
103
104mod access_mask;
105mod auth_policy;
106mod backend;
107mod builder;
108pub(crate) mod conn;
109mod dispatch;
110mod error;
111mod files;
112#[cfg(feature = "localfs")]
113mod fs;
114mod handlers;
115pub(crate) mod info_class;
116pub mod ntstatus;
117mod path;
118mod proto;
119mod server;
120#[cfg(test)]
121mod tests {
122 mod dynamic_config;
123 pub(crate) mod memfs;
124}
125mod utils;
126mod wildcard;
127
128pub use backend::{
129 BackendCapabilities, DirEntry, FileInfo, FileTimes, Handle, OpenAction, OpenIntent,
130 OpenOptions, ShareBackend, VolumeInfo,
131};
132pub use builder::{Access, BuildError, Share, SmbServerBuilder};
133pub use bytes::Bytes;
134pub use error::{SmbError, SmbResult};
135pub use files::{DEFAULT_MAX_LOCKS_PER_OPEN, DEFAULT_MAX_OPENS_PER_CONNECTION};
136#[cfg(feature = "localfs")]
137pub use fs::LocalFsBackend;
138pub use path::SmbPath;
139pub use proto::auth::ntlm::Identity;
140pub use server::{ConfigError, ConfigHandle, ShareMode, ShutdownHandle, SmbServer};
141
142pub mod wire {
143 pub use crate::proto::header;
144 pub use crate::proto::messages;
145}
146
147/// Entry points for the cargo-fuzz targets in `fuzz/`. Built only with
148/// `--cfg fuzzing`, which `cargo fuzz` sets.
149#[cfg(fuzzing)]
150#[doc(hidden)]
151pub mod fuzzing {
152 use std::sync::Arc;
153
154 use crate::conn::state::Connection;
155 use crate::proto::auth::{ntlm, spnego};
156 use crate::proto::framing;
157 use crate::proto::header::Smb2Header;
158
159 /// Decodes the start of `data` as a transport frame header.
160 pub fn frame(data: &[u8]) {
161 if let Some(hdr) = data.first_chunk::<{ framing::FRAME_HEADER_LEN }>() {
162 let _ = framing::decode_frame_header(hdr);
163 }
164 }
165
166 /// Parses `data` as an SMB2 header.
167 pub fn header(data: &[u8]) {
168 let _ = Smb2Header::parse(data);
169 }
170
171 /// Decodes `data` as a SPNEGO NegTokenInit and as a NegTokenResp.
172 pub fn spnego(data: &[u8]) {
173 let _ = spnego::decode_init_token(data);
174 let _ = spnego::decode_resp_token(data);
175 }
176
177 /// Parses `data` as each NTLM message the server receives.
178 pub fn ntlm(data: &[u8]) {
179 let _ = ntlm::NtlmNegotiate::parse(data);
180 let _ = ntlm::NtlmAuthenticate::parse(data);
181 }
182
183 /// Dispatches one frame payload on a fresh connection to `server`.
184 pub async fn dispatch(server: &crate::SmbServer, frame: &[u8]) -> Option<Vec<u8>> {
185 let state = server.state();
186 let conn = Arc::new(Connection::new(
187 state.config.server_guid,
188 state.config.max_read_size,
189 state.config.max_write_size,
190 ));
191 crate::dispatch::dispatch_frame(&state, &conn, frame).await
192 }
193}