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#![cfg_attr(
19 feature = "discovery",
20 doc = r#"
21# Network discovery
22
23With the `discovery` feature, [`SmbServerBuilder::discovery`] announces
24the server on the local network while [`SmbServer::serve`] runs, and
25withdraws it before `serve` returns. Nothing is announced unless it is
26called, and the listen address must not be a loopback address.
27
28The Finder, GNOME Files and Dolphin find the server over mDNS and DNS-SD.
29Listen on `[::]:445`, as below: Windows may connect over IPv6 alone, so
30it cannot open a server that listens on IPv4 only. [`Discovery`] has the
31options and what each platform does.
32
33```no_run
34use smb_server::{Discovery, Share, ShareBackend, SmbServer};
35# async fn run<B: ShareBackend>(backend: B) -> Result<(), Box<dyn std::error::Error>> {
36SmbServer::builder()
37 .listen("[::]:445".parse()?)
38 .share(Share::new("public", backend).public_read_only())
39 .discovery(Discovery::new())
40 .build()?
41 .serve()
42 .await?;
43# Ok(()) }
44```
45"#
46)]
47//!
48//! # Writing a backend
49//!
50//! A share serves any [`ShareBackend`]. Each CREATE calls
51//! [`ShareBackend::open`], which returns a [`Handle`] and the
52//! [`OpenAction`] it took; CREATE reports the action to the client. The
53//! handle serves READ, WRITE, FLUSH, QUERY_INFO, QUERY_DIRECTORY and
54//! SET_INFO on that open until the open is closed. `LocalFsBackend`
55//! (feature `localfs`) is the reference implementation; its documentation
56//! says where it keeps named streams and extended attributes on each host.
57//! `S3Backend` (feature `s3`) serves a bucket of an S3-compatible store.
58//! `EncryptedBackend` (feature `encryption`) wraps another backend and stores
59//! file contents, and by default names, encrypted under a key.
60//!
61//! What the protocol layer does around the backend calls:
62//!
63//! - Paths arrive as [`SmbPath`], relative to the share root. `.` components
64//! are dropped; `..`, empty components, `<>:"|?*` and control characters
65//! are rejected before the backend sees them. A name ending in `::$DATA`
66//! opens the file with [`OpenOptions::non_directory`] set, and one ending
67//! in `::$INDEX_ALLOCATION` the directory with [`OpenOptions::directory`]
68//! set. The empty path is the share root.
69//! - A named stream (`file.txt:name`) arrives as a [`StreamName`] beside
70//! the file's path, on shares whose backend reports
71//! [`BackendCapabilities::named_streams`] unless [`Share::named_streams`]
72//! turns them off: CREATE opens the file with `open`, creating it when
73//! the disposition allows, then the stream with
74//! [`ShareBackend::open_stream`], which gets the file's handle. An
75//! overwrite of the file removes its named streams through
76//! [`ShareBackend::remove_stream`], each once no open is on it. A rename
77//! to `:name` or `::$DATA` goes to [`ShareBackend::rename_stream`]. An
78//! open of a named stream reports the file's times and attributes with
79//! the stream's sizes, without FILE_ATTRIBUTE_DIRECTORY on a directory's
80//! stream. Elsewhere named streams are rejected before the backend sees
81//! them.
82//! - Extended attributes, on shares whose backend reports
83//! [`BackendCapabilities::extended_attributes`] unless
84//! [`Share::extended_attributes`] turns them off: FileFullEaInformation
85//! queries call [`Handle::eas`], sets [`Handle::set_eas`], and an `ExtA`
86//! create context gives a new file its attributes. The protocol layer
87//! checks the names and the 65531-byte limit before the backend is
88//! called, matches names without regard to ASCII case, keeps each open's
89//! position in the attribute list across queries, replaces a file's
90//! attributes with those of a CREATE that overwrites or supersedes it,
91//! and refuses an open with FILE_NO_EA_KNOWLEDGE of a file that has one
92//! flagged FILE_NEED_EA. EaSize in FileEaInformation, FileAllInformation
93//! and directory listings is [`FileInfo::ea_size`]. A set breaks no
94//! lease and is reported, under EA and ATTRIBUTES, when the open that
95//! made it closes. A named stream has none of its own.
96//! - Apple's extensions: unless [`SmbServerBuilder::apple_extensions`]
97//! turns them off, a CREATE that carries the `AAPL` server query, as
98//! macOS clients send when they mount a share, gets a reply with the
99//! model string of [`SmbServerBuilder::apple_model`], UNIX_BASED on Unix
100//! hosts and the case sensitivity the backend reports. A client that
101//! asks for READ_DIR_ATTR on a share with named streams gets it for its
102//! connection. FileIdBothDirectoryInformation listings on that
103//! connection then carry Finder data in place of EaSize and the short
104//! name: the access the client may ask for, the low 16 bits of
105//! [`FileInfo::unix_mode`], and, on shares with named streams, the
106//! Finder info of each entry's `AFP_AfpInfo` stream and the size of its
107//! `AFP_Resource` stream, read through one [`Handle::peek_streams`] call
108//! per response. A client that asks for the server caps on a share that
109//! serves named streams and allows server-side copies is offered
110//! OSX_COPYFILE for its connection, unless
111//! [`SmbServerBuilder::apple_copyfile`] turns it off.
112//! - `open` fails with [`SmbError::PathNotFound`] when a directory on the
113//! way to the path is missing, and with [`SmbError::NotFound`] when only
114//! the last component is. Clients see STATUS_OBJECT_PATH_NOT_FOUND and
115//! STATUS_OBJECT_NAME_NOT_FOUND.
116//! - Share permissions and the access the client asked for are checked
117//! before `open`. [`OpenOptions`] carries the result: `read`, `write` and
118//! `write_attributes` reflect the access granted to the open. READ and
119//! WRITE on a handle without the matching access fail before the handle
120//! is called. When [`BackendCapabilities::is_read_only`] is set, trees on
121//! the share get read access only, so opens that ask for write access,
122//! and dispositions that create or truncate, fail before `open`.
123//! - Share modes, byte-range locks and the delete-pending flag are kept by
124//! the protocol layer per share, across every connection, keyed by
125//! [`FileInfo::file_index`], or by path when it is 0. Two shares over
126//! the same directory do not see each other's opens. Each named stream
127//! of a file has its own share modes, byte-range locks and
128//! delete-pending flag, and the last close of a stream marked for
129//! deletion calls [`ShareBackend::remove_stream`]. A CREATE that would
130//! truncate first opens the file without truncating it, for reading or,
131//! when reading is refused, with the access the CREATE was granted. It
132//! runs the checks, enters the open in the table and waits for lease
133//! breaks, so the sharing mode holds and clients caching writes have
134//! written back before `open` truncates. When that first open finds no
135//! file, the CREATE calls `open` with [`OpenIntent::Create`] instead and
136//! starts over if the file appeared meanwhile. Any other CREATE refused
137//! by the share-mode check has already called `open` and closes the new
138//! handle again.
139//! - [`Handle::close`] runs on every path that ends an open: CLOSE,
140//! TREE_DISCONNECT, LOGOFF, the end of a session or connection, and
141//! [`ConfigHandle`] changes that end sessions or trees. A durable open,
142//! described below, outlives LOGOFF and the end of its connection or
143//! session for a while. Before `close`, [`Handle::set_times`] puts back
144//! access and write times that FileBasicInformation froze or set through
145//! that open.
146//! - Delete-on-close: [`OpenOptions::delete_on_close`] and
147//! FileDispositionInformation make the file delete-pending. When its last
148//! open ends, on any of the paths above, the protocol layer calls
149//! [`Handle::close`] and then [`ShareBackend::unlink`] on the file's
150//! current path. `open` doesn't delete anything itself. Read-only files
151//! are refused before that point, and so, for SET_INFO, are directories
152//! that [`Handle::dir_is_empty`] reports as not empty. `unlink` returns
153//! [`SmbError::NotEmpty`] for a directory that has entries; the directory
154//! then stays.
155//! - A rename through SET_INFO of a directory with a file or directory open
156//! below it first asks the clients caching handles to those files to
157//! close them, and waits until they answer or the break times out; files
158//! kept open for a client to reconnect are closed. If an open below
159//! remains, the rename fails with STATUS_ACCESS_DENIED, and so does a
160//! rename of the share root. Otherwise the rename calls
161//! [`ShareBackend::rename`] and then moves the path of every open of the
162//! old name. Renames on one share run
163//! one at a time, and a CREATE or a delete waits for a rename in
164//! progress. The backend keeps those handles working on the renamed file.
165//! - A CREATE that makes or overwrites a file passes the attributes it asks
166//! for to [`Handle::set_attributes`] when they differ from what
167//! [`Handle::stat`] reports. If that returns [`SmbError::NotSupported`],
168//! it retries with READONLY alone when that was asked for; the CREATE
169//! succeeds either way.
170//! - FileBasicInformation passes [`Handle::set_attributes`] and
171//! [`Handle::set_times`] only the values that differ from what
172//! [`Handle::stat`] reports. After a write or truncate, `set_times` also
173//! puts back the times FileBasicInformation froze or set.
174//! [`Handle::truncate`] is never called on a directory.
175//! - QUERY_DIRECTORY calls [`Handle::list_dir`] with the search pattern on
176//! the first query and on a restart, then pages through the returned
177//! entries itself. It adds `.` and `..` when the pattern matches them,
178//! and opens the parent directory to describe `..`; at the share root,
179//! `..` describes the root itself, with file id 0.
180//! - FileStandardInformation and FileAllInformation report
181//! [`Handle::link_count`] as NumberOfLinks, and DeletePending when the
182//! file is delete-pending or has no links left. The filesystem
183//! QUERY_INFO classes, and the VolumeId of the on-disk id CREATE context,
184//! come from [`ShareBackend::volume_info`].
185//! - Leases: on every share unless [`Share::leases`] turns them off, files
186//! get read, handle and write caching leases. A client holding one
187//! caches what it reads, keeps files open after its applications close
188//! them, and caches writes while every other open of the file holds the
189//! same lease or is attribute-only. An open, write, size change,
190//! byte-range lock, rename or delete made through an open that does not
191//! hold the lease breaks it when it needs what the lease caches, whether
192//! that open belongs to another client or to the same client under
193//! another lease key or none; attribute-only opens and opens holding the
194//! same lease break nothing. Each named stream of a file or directory has
195//! leases of its own, which only opens of that stream grant and break,
196//! except that an overwrite of the file breaks their handle caching; a
197//! lease key held on one stream fails with STATUS_INVALID_PARAMETER on
198//! another stream or file. An open or rename that needs the client to
199//! write back or close first waits until the client acknowledges the
200//! break or closes, or until the break times out 35 seconds after the
201//! server sent it; meanwhile its backend handle stays open, except for
202//! one that truncates, which calls `open` after the wait. A byte-range
203//! lock asked for while another lease still caches writes is refused
204//! with STATUS_LOCK_NOT_GRANTED until that client has written back.
205//! Changes made outside the server, including through another share over
206//! the same directory, break nothing: clients keep serving stale cached
207//! data. Turn leases off on such shares.
208//! - Durable handles: on a share with leases, unless
209//! [`Share::durable_handles`] turns them off, a file opened with a
210//! durable handle request (DHnQ, or DH2Q on SMB 3.x) and a lease that
211//! caches handles stays open when the client's connection drops, when it
212//! logs off, when its session's reauthentication fails, or when a new
213//! session names its session as the previous one. A request without such
214//! a lease gets an open that is not durable and no durable context in the
215//! response. The backend handle stays open, and the file keeps its share
216//! mode, byte-range locks and lease, for
217//! [`SmbServerBuilder::durable_handle_timeout`], or for the time a DH2Q
218//! asked for, up to that timeout or 5 minutes, whichever is longer; the
219//! DH2Q response carries the time granted. The PERSISTENT flag is
220//! ignored. A file whose lease is being broken, or that holds byte-range
221//! locks under a lease that does not cache writes, closes with its
222//! session instead. Meanwhile the same user, from the same client, takes
223//! the file back with a durable handle reconnect (DHnC, or DH2C naming
224//! the CreateGuid of a DH2Q open) on a tree of the same share that names
225//! the file, or its named stream, and its lease; the backend handle,
226//! share mode, byte-range locks and lease carry on, and later lease
227//! breaks go to the new connection. A reconnect fails with
228//! STATUS_ACCESS_DENIED from another user, STATUS_INVALID_PARAMETER for a
229//! DHnC naming another file, and STATUS_INSUFFICIENT_RESOURCES past the
230//! connection's open limit; from another client, on another share, naming
231//! another lease, lease version or CreateGuid, a DH2C naming another
232//! file, or for a file that is not kept, with
233//! STATUS_OBJECT_NAME_NOT_FOUND. The file stays kept after a failed
234//! reconnect. One that comes while the connection holding the file is
235//! still closing waits up to 5 seconds for it. A file whose rights exceed
236//! what the user's tree on the share grants now is closed instead of
237//! reconnected. [`Handle::close`] runs when the time runs out; at once
238//! when an open, write, size change, byte-range lock, rename or delete
239//! through an open that does not hold the lease needs what the lease
240//! caches, or when the lease stops caching handles; for an open of a
241//! named stream, also when its file is renamed, or deleted while no
242//! connected open holds the same lease; on [`ConfigHandle`] changes that
243//! end the user's sessions or the share's trees; and at
244//! shutdown. At most [`SmbServerBuilder::max_disconnected_opens`] files
245//! are kept at once, and a quarter of that, rounded up, for one user;
246//! past that, files close with their session. Anonymous sessions and
247//! clients that send a nil ClientGuid get no durable handle. A DH2Q that
248//! repeats the CreateGuid of a live version 2 open of the same client,
249//! with access to its data or to delete it, fails with
250//! STATUS_DUPLICATE_OBJECTID unless it is marked as a replay; one marked
251//! as a replay opens the file anew rather than answering with that
252//! open.
253//! - Change notifications: on every share unless [`Share::change_notify`]
254//! turns them off, a CHANGE_NOTIFY on a directory waits until a file or
255//! directory in it, or below it when the client asks for the whole tree,
256//! changes through any connection to the share:
257//! - A create or delete is reported as an addition or a removal.
258//! - A rename within one directory is reported as its old and new name
259//! together, a move to another directory as a removal from one and an
260//! addition to the other. Either is followed by a modification, under
261//! LAST_WRITE, of the directory the entry is in afterwards, unless that
262//! is the share root. An entry the rename replaces,
263//! or the renamed entry itself when only the case of its name changes,
264//! is first reported removed under its name as stored. A watched
265//! directory can be renamed, and its watches follow it.
266//! - Attributes and times set through FileBasicInformation are reported
267//! at once as a modification, under ATTRIBUTES and the bit of each time
268//! changed but the change time. What changed is what [`Handle::stat`]
269//! shows differently afterwards, so a value the backend does not keep
270//! reports nothing.
271//! - New contents are reported as a modification under SIZE, LAST_WRITE
272//! and ATTRIBUTES: a write once, when the open that wrote closes, unless
273//! that close deletes the file; a change of size through
274//! FileEndOfFileInformation, a truncation through
275//! FileAllocationInformation, and an overwrite or supersede by CREATE,
276//! at once.
277//! - Changes of a named stream are named `file:stream`, under the
278//! STREAM_* bits: a new stream as an added stream; a write, a size
279//! change, an overwrite, a rename (under both names) and a deletion as
280//! a modified stream, after a modification of the file under
281//! LAST_WRITE and LAST_ACCESS for all but the deletion; and the named
282//! streams an overwrite of the file removes as removed streams. A write
283//! is reported when the open that wrote closes; an overwrite or a size
284//! change of a stream at once, and the stream again when that open
285//! closes. A deletion of the file reports the file alone. Changes of a
286//! stream whose name has a `"` are not reported: clients refuse a
287//! response that names one.
288//!
289//! A watched directory marked for deletion, through
290//! FileDispositionInformation or by the close of an open that asked for
291//! delete-on-close while other opens of it remain, ends every watch of
292//! it: the requests waiting on them, and any request on an open of the
293//! directory while it stays delete-pending, get STATUS_DELETE_PENDING. An
294//! open that marked the directory, and any open made with delete-on-close,
295//! always gets STATUS_DELETE_PENDING; once the mark is cleared, other
296//! opens watch again. Watches of the directories above it stay, and hear
297//! the removal once the directory is deleted.
298//!
299//! Changes are buffered on the directory handle between requests, up to
300//! the buffer size of its first request and at most 64 KiB; when more
301//! arrive, or they do not fit the request being answered, the answer is
302//! STATUS_NOTIFY_ENUM_DIR. Watches follow paths: a change made through a
303//! symlink inside the share reaches the watchers of the path it was made
304//! through, and on Linux, as a change on disk, those of the directory
305//! the symlink leads to. Names are spelled as the client that made the
306//! change spelled them, but for the stored names above.
307//!
308//! Changes made outside the server, or through another share over the
309//! same directory, are reported when the backend's [`Handle::watch`]
310//! reports them. `LocalFsBackend` does on Linux, through inotify, unless
311//! its `watch_host_changes` turns it off: additions, removals, renames
312//! within the directory, new contents when a writer closes the file
313//! (under SIZE, LAST_WRITE and ATTRIBUTES) and attribute or time changes
314//! (under ATTRIBUTES) of the entries directly in a watched directory,
315//! also for a client that asks for the whole tree. A move out of or into
316//! the directory is a removal or an addition, and so is a rename from or
317//! to a name the server cannot use. A lost kernel queue, and a watched
318//! directory renamed or moved outside the server, are answered
319//! STATUS_NOTIFY_ENUM_DIR; such a directory stays watched under its old
320//! name. A watched directory deleted outside the server, or replaced by a
321//! rename, ends its watches with STATUS_DELETE_PENDING, and every later
322//! CHANGE_NOTIFY on its handles gets the same. The parent of each watched
323//! directory is watched too, the share root's parent included, only to
324//! see the directory go. A change in a parent is reported only to the
325//! watchers of that parent, so a change in the share root's parent is
326//! reported to no one. One backend holds at most 4096 kernel watches,
327//! parents included. A directory past that, or one the kernel will not
328//! watch, past `fs.inotify.max_user_watches` or
329//! `fs.inotify.max_user_instances` or without `/proc`, gets only the
330//! changes made through the server, with a warning logged once. Other
331//! backends and platforms report only changes made through the server.
332//!
333//! The server leaves out the backend's reports of its own changes. Each
334//! addition, removal or rename it made in the last 5 seconds drops one
335//! matching backend report. A modification or attribute change is
336//! dropped while an open through the server that may write the entry's
337//! data or attributes has it open, for 5 seconds after the server
338//! reported a change to it or closed an open that wrote it or restored
339//! times fixed through it, and once after it closed an open that could
340//! write it, or created or overwrote it, and wrote nothing. A backend
341//! report waits up to 200 milliseconds for that comparison, and goes out
342//! before any change the server reports after it arrived in the same
343//! directory, or below it to a watch of the whole tree.
344//!
345//! The backend is called for these reports in four cases:
346//! [`Handle::watch`], through an open of a watched directory, on the
347//! first request on that directory and on the next request after the
348//! backend's reports stopped; a
349//! FileBasicInformation that passed something to the backend calls
350//! [`Handle::stat`] once more; a size change on a share with watches
351//! calls `stat` before and after; and a rename into a watched directory
352//! that may replace an entry or changes the case of a name calls, on a
353//! case-sensitive backend, [`ShareBackend::open`] of the target and
354//! `stat`, otherwise `open` of the target's directory and
355//! [`Handle::list_dir`] with the target's name.
356//! - Share listing: unless [`SmbServerBuilder::share_listing`] turns it
357//! off, IPC$ serves the `srvsvc` pipe, so clients can list the server's
358//! shares. A session sees the shares it may connect to, in the order
359//! they were added, and IPC$; for an anonymous session that is the
360//! public shares, and a session that cannot encrypt does not see shares
361//! whose traffic is encrypted. [`Share::listed`] leaves a share out of
362//! the list without hiding it from lookups by name, and
363//! [`Share::remark`] sets the comment shown next to it. Backends are not
364//! called. Other pipe names fail with STATUS_OBJECT_NAME_NOT_FOUND,
365//! DCE/RPC binds that carry authentication are refused, and one
366//! connection may hold 16 pipes at once.
367//! - READ and WRITE lengths are bounded by the negotiated maximum sizes.
368//! - Each [`SmbError`] maps to one NTSTATUS for the client; see
369//! [`SmbError::to_nt_status`].
370//!
371//! A handle is dropped without [`Handle::close`] when the task serving its
372//! connection panics or is cancelled, and when a [`ConfigHandle`] call that
373//! ends its session or tree is cancelled, so release resources in `Drop` as
374//! well.
375//!
376//! Later releases may add methods with default bodies, fields to
377//! [`FileInfo`], [`BackendCapabilities`], [`VolumeInfo`] and [`DirChange`],
378//! and variants to [`OpenIntent`] and [`DirChangeKind`]. A backend that
379//! implements the required methods, builds those types through
380//! [`FileInfo::new`], [`DirChange::new`] and the `Default` impls, and
381//! matches `OpenIntent` and `DirChangeKind` with a wildcard arm keeps
382//! compiling.
383//!
384//! # Server-side copy
385//!
386//! COPYCHUNK and COPYCHUNK_WRITE copy ranges between two open files, within
387//! a share or between two shares of one session, and either side may be a
388//! named stream. A request holds at most 256 chunks of up to 1 MiB, 16 MiB
389//! in all. On a connection that was offered OSX_COPYFILE through the `AAPL`
390//! context, a COPYCHUNK or COPYCHUNK_WRITE without chunks between the
391//! default streams of two files copies the whole source in one request: it
392//! truncates the target with [`Handle::truncate`], copies the data in pieces
393//! of 1 MiB the way it copies chunks, copies the named streams where both
394//! shares serve them, and passes the creation and last write times to
395//! [`Handle::set_times`]. FSCTL_DUPLICATE_EXTENTS_TO_FILE makes a range of
396//! one file share its storage with a range of another on shares whose
397//! backend reports [`BackendCapabilities::block_cloning`]; those shares
398//! report FILE_SUPPORTS_BLOCK_REFCOUNTING and accept FSCTL_SET_SPARSE.
399//!
400//! The server passes each chunk to [`ShareBackend::copy_range`], except a
401//! chunk whose source and target ranges overlap in one file, which it reads
402//! and writes itself. When the backend does not implement `copy_range`,
403//! returns [`SmbError::NotSupported`] or [`SmbError::NotSameDevice`], or
404//! copies fewer bytes than asked, the server reads the rest with
405//! [`Handle::read`] and writes it with [`Handle::write`]. [`Handle::as_any`]
406//! lets `copy_range` tell the handles of its backend from others.
407//! [`ShareBackend::clone_range`] serves duplicate extents on a backend that
408//! reports `block_cloning`. Byte-range locks, leases and change
409//! notifications stay with the server.
410//!
411//! [`Share::server_side_copy`] turns these requests off for a share, cloning
412//! included, and a copy between two shares needs both to serve them.
413
414mod access_mask;
415mod auth_policy;
416mod backend;
417mod builder;
418pub(crate) mod conn;
419#[cfg(feature = "discovery")]
420mod discovery;
421mod dispatch;
422mod ea;
423#[cfg(feature = "encryption")]
424mod encrypted;
425mod error;
426mod files;
427#[cfg(feature = "localfs")]
428mod fs;
429mod handlers;
430#[cfg(any(feature = "localfs", feature = "s3"))]
431mod host;
432pub(crate) mod info_class;
433pub mod ntstatus;
434mod path;
435mod proto;
436mod rpc;
437#[cfg(feature = "s3")]
438mod s3;
439mod server;
440mod stream;
441#[cfg(test)]
442mod tests {
443 mod aapl;
444 mod async_requests;
445 mod contract;
446 mod copy;
447 pub(crate) mod data;
448 #[cfg(feature = "discovery")]
449 mod discovery;
450 mod durable;
451 mod dynamic_config;
452 mod eas;
453 pub(crate) mod faulty;
454 pub(crate) mod file_ids;
455 #[cfg(all(target_os = "linux", feature = "localfs"))]
456 pub(crate) mod filesystems;
457 pub(crate) mod folding;
458 pub(crate) mod gated;
459 #[cfg(any(
460 feature = "s3",
461 feature = "encryption",
462 all(windows, feature = "localfs")
463 ))]
464 pub(crate) mod logs;
465 pub(crate) mod memfs;
466 mod notify;
467 pub(crate) mod peer;
468 mod pipes;
469 pub(crate) mod recorder;
470 #[cfg(feature = "s3")]
471 mod s3;
472 mod stream_leases;
473 mod streams;
474 pub(crate) mod util;
475}
476mod utils;
477mod wildcard;
478
479pub use backend::{
480 BackendCapabilities, DirChange, DirChangeKind, DirEntry, DirWatch, FileInfo, FileTimes, Handle,
481 OpenAction, OpenIntent, OpenOptions, ShareBackend, VolumeInfo,
482};
483pub use builder::{Access, BuildError, Share, SmbServerBuilder};
484pub use bytes::Bytes;
485#[cfg(feature = "discovery")]
486pub use discovery::Discovery;
487pub use ea::Ea;
488#[cfg(feature = "encryption")]
489pub use encrypted::{EncryptedBackend, EncryptedBackendBuilder, EncryptionError};
490pub use error::{SmbError, SmbResult};
491pub use files::{
492 DEFAULT_DURABLE_HANDLE_TIMEOUT, DEFAULT_MAX_DISCONNECTED_OPENS, DEFAULT_MAX_LOCKS_PER_OPEN,
493 DEFAULT_MAX_OPENS_PER_CONNECTION,
494};
495#[cfg(feature = "localfs")]
496pub use fs::LocalFsBackend;
497pub use path::SmbPath;
498pub use proto::auth::ntlm::Identity;
499#[cfg(feature = "s3")]
500pub use s3::{S3Backend, S3BackendBuilder, S3Error};
501pub use server::{ConfigError, ConfigHandle, ShareMode, ShutdownHandle, SmbServer};
502pub use stream::{StreamInfo, StreamName};
503
504pub mod wire {
505 pub use crate::proto::header;
506 pub use crate::proto::messages;
507}
508
509/// Entry points for the cargo-fuzz targets in `fuzz/`. Built only with
510/// `--cfg fuzzing`, which `cargo fuzz` sets.
511#[cfg(fuzzing)]
512#[doc(hidden)]
513pub mod fuzzing {
514 use std::sync::Arc;
515
516 use crate::conn::state::Connection;
517 use crate::proto::auth::{ntlm, spnego};
518 use crate::proto::framing;
519 use crate::proto::header::Smb2Header;
520
521 /// Decodes the start of `data` as a transport frame header.
522 pub fn frame(data: &[u8]) {
523 if let Some(hdr) = data.first_chunk::<{ framing::FRAME_HEADER_LEN }>() {
524 let _ = framing::decode_frame_header(hdr);
525 }
526 }
527
528 /// Parses `data` as an SMB2 header.
529 pub fn header(data: &[u8]) {
530 let _ = Smb2Header::parse(data);
531 }
532
533 /// Decodes `data` as a SPNEGO NegTokenInit and as a NegTokenResp.
534 pub fn spnego(data: &[u8]) {
535 let _ = spnego::decode_init_token(data);
536 let _ = spnego::decode_resp_token(data);
537 }
538
539 /// Parses `data` as each NTLM message the server receives.
540 pub fn ntlm(data: &[u8]) {
541 let _ = ntlm::NtlmNegotiate::parse(data);
542 let _ = ntlm::NtlmAuthenticate::parse(data);
543 }
544
545 /// Parses `data` as the data of a lease create context.
546 pub fn lease_context(data: &[u8]) {
547 let _ = crate::proto::messages::LeaseContext::parse(data);
548 }
549
550 /// Parses `data` as a UTF-16LE CREATE name and checks the result. A
551 /// name without `:` parses as `SmbPath::from_utf16` does. In a name
552 /// with one, the text before the first `:` parses as the path, a suffix
553 /// that selects no named stream is `::$DATA`, `::$INDEX_ALLOCATION` or
554 /// `:$I30:$INDEX_ALLOCATION`, and the path and stream put back together
555 /// parse to the same result. A data stream that a stream rename target
556 /// names is the one CREATE opens for `f` followed by the target.
557 pub fn create_name(data: &[u8]) {
558 use crate::stream::{StreamPart, StreamType, parse_create_name, parse_stream_target};
559 let units: Vec<u16> = data
560 .chunks_exact(2)
561 .map(|c| u16::from_le_bytes([c[0], c[1]]))
562 .collect();
563 if let Ok(target) = parse_stream_target(&units) {
564 let part = match (target.stream, target.kind) {
565 (Some(stream), None | Some(StreamType::Data)) => Some(StreamPart::Named(stream)),
566 (None, Some(StreamType::Data)) => Some(StreamPart::Data),
567 _ => None,
568 };
569 if let Some(part) = part {
570 let mut file: Vec<u16> = "f".encode_utf16().collect();
571 file.extend_from_slice(&units);
572 let expected = ("f".parse().expect("a valid path"), part);
573 assert_eq!(parse_create_name(&file).ok(), Some(expected));
574 }
575 }
576 let parsed = parse_create_name(&units);
577 let Ok(name) = String::from_utf16(&units) else {
578 assert!(parsed.is_err());
579 return;
580 };
581 let Some((file, suffix)) = name.split_once(':') else {
582 let path = parsed.ok().map(|(path, stream)| {
583 assert_eq!(stream, StreamPart::None);
584 path
585 });
586 assert_eq!(path, crate::SmbPath::from_utf16(&units).ok());
587 return;
588 };
589 let Ok((path, stream)) = parsed else {
590 return;
591 };
592 assert_eq!(file.parse::<crate::SmbPath>().ok(), Some(path.clone()));
593 let suffix = suffix.to_ascii_uppercase();
594 let rebuilt = match &stream {
595 StreamPart::None => panic!("a name with `:` parsed without a stream part"),
596 StreamPart::Data => {
597 assert_eq!(suffix, ":$DATA");
598 format!("{}::$DATA", path.display_backslash())
599 }
600 StreamPart::Directory => {
601 assert!(matches!(
602 suffix.as_str(),
603 ":$INDEX_ALLOCATION" | "$I30:$INDEX_ALLOCATION"
604 ));
605 format!("{}::$INDEX_ALLOCATION", path.display_backslash())
606 }
607 StreamPart::Named(stream) => {
608 format!("{}:{}", path.display_backslash(), stream.as_str())
609 }
610 StreamPart::NamedDirectory(stream) => format!(
611 "{}:{}:$INDEX_ALLOCATION",
612 path.display_backslash(),
613 stream.as_str()
614 ),
615 };
616 let units: Vec<u16> = rebuilt.encode_utf16().collect();
617 assert_eq!(parse_create_name(&units).ok(), Some((path, stream)));
618 }
619
620 /// Parses `data` as the data of an `AAPL` create context. It parses
621 /// exactly when it is 24 bytes with CommandCode 1, into the bitmap and
622 /// client caps at offsets 8 and 16. The reply to it holds the parts its
623 /// bitmap asks for, each at the offset the bits before it leave.
624 pub fn aapl_context(data: &[u8]) {
625 use crate::proto::messages::aapl::{AAPL_MODEL_INFO, AAPL_SERVER_CAPS, AAPL_VOLUME_CAPS};
626 use crate::proto::messages::{AaplQuery, AaplReply};
627 let parsed = AaplQuery::parse(data);
628 assert_eq!(
629 parsed.is_ok(),
630 data.len() == 24 && data[..4] == [1, 0, 0, 0]
631 );
632 let Ok(query) = parsed else {
633 return;
634 };
635 assert_eq!(query.bitmap.to_le_bytes(), data[8..16]);
636 assert_eq!(query.client_caps.to_le_bytes(), data[16..24]);
637 let (server_caps, volume_caps) = (query.client_caps, !query.client_caps);
638 let model = "smb-server";
639 let reply = AaplReply {
640 bitmap: query.bitmap,
641 server_caps,
642 volume_caps,
643 model,
644 }
645 .encode();
646 let bitmap = query.bitmap & (AAPL_SERVER_CAPS | AAPL_VOLUME_CAPS | AAPL_MODEL_INFO);
647 assert_eq!(reply[..8], [1, 0, 0, 0, 0, 0, 0, 0]);
648 assert_eq!(reply[8..16], bitmap.to_le_bytes());
649 let mut at = 16;
650 for (bit, caps) in [
651 (AAPL_SERVER_CAPS, server_caps),
652 (AAPL_VOLUME_CAPS, volume_caps),
653 ] {
654 if bitmap & bit != 0 {
655 assert_eq!(reply[at..at + 8], caps.to_le_bytes());
656 at += 8;
657 }
658 }
659 if bitmap & AAPL_MODEL_INFO != 0 {
660 let units = crate::utils::utf16le(model);
661 assert_eq!(reply[at..at + 4], [0, 0, 0, 0]);
662 assert_eq!(reply[at + 4..at + 8], (units.len() as u32).to_le_bytes());
663 assert_eq!(reply[at + 8..], units);
664 at += 8 + units.len();
665 }
666 assert_eq!(reply.len(), at);
667 }
668
669 /// Parses `data` as the input of a copy request and checks the limits and
670 /// the fields read. Reads the first 24 bytes as a resume key and checks
671 /// that it maps to the FileId it holds, and to nothing under another tag.
672 /// Parses `data` as the input of a duplicate extents request too, and
673 /// checks the fields read and the end of the source range.
674 pub fn copychunk(data: &[u8]) {
675 use crate::proto::messages::copychunk::{
676 CopychunkRequest, MAX_CHUNK_LEN, MAX_CHUNKS, MAX_COPY_LEN, resume_key,
677 resume_key_file_id,
678 };
679 use crate::proto::messages::duplicate_extents::DuplicateExtentsRequest;
680 match CopychunkRequest::parse(data) {
681 Ok(request) => {
682 assert_eq!(request.source_key, data[..24]);
683 assert_eq!(
684 request.chunks.len() as u32,
685 u32::from_le_bytes(data[24..28].try_into().expect("4 bytes"))
686 );
687 assert!(request.chunks.len() <= MAX_CHUNKS as usize);
688 let mut total = 0u64;
689 for (chunk, raw) in request.chunks.iter().zip(data[32..].chunks_exact(24)) {
690 assert_eq!(chunk.source_offset.to_le_bytes(), raw[..8]);
691 assert_eq!(chunk.target_offset.to_le_bytes(), raw[8..16]);
692 assert_eq!(chunk.length.to_le_bytes(), raw[16..20]);
693 assert!((1..=MAX_CHUNK_LEN).contains(&chunk.length));
694 assert!(
695 chunk.target_offset <= i64::MAX as u64 || chunk.target_offset == u64::MAX
696 );
697 total += u64::from(chunk.length);
698 }
699 assert!(total <= u64::from(MAX_COPY_LEN));
700 }
701 Err(over) => match over.source_key {
702 Some(key) => {
703 assert!(data.len() >= 32);
704 assert_eq!(key, data[..24]);
705 }
706 None => assert!(data.len() < 32),
707 },
708 }
709 if let Some(key) = data.first_chunk::<24>() {
710 let tag: [u8; 8] = key[16..].try_into().expect("8 bytes");
711 let id = resume_key_file_id(key, &tag).expect("a key ends in its tag");
712 assert_eq!(resume_key(id, &tag), *key);
713 assert_eq!(resume_key_file_id(key, &tag.map(|b| !b)), None);
714 }
715 match DuplicateExtentsRequest::parse(data) {
716 Some(request) => {
717 assert!(data.len() >= 40);
718 assert_eq!(request.source.persistent.to_le_bytes(), data[..8]);
719 assert_eq!(request.source.volatile.to_le_bytes(), data[8..16]);
720 assert_eq!(request.source_offset.to_le_bytes(), data[16..24]);
721 assert_eq!(request.target_offset.to_le_bytes(), data[24..32]);
722 assert_eq!(request.byte_count.to_le_bytes(), data[32..40]);
723 let end = u128::from(request.source_offset) + u128::from(request.byte_count);
724 assert_eq!(request.source_end(), u64::try_from(end).ok());
725 }
726 None => assert!(data.len() < 40),
727 }
728 }
729
730 /// Parses `data` as a FILE_FULL_EA_INFORMATION list and as a
731 /// FILE_GET_EA_INFORMATION list. Every attribute read has a valid name
732 /// and reads back the same from the list it encodes to; every name read
733 /// is valid and listed once.
734 pub fn ea_list(data: &[u8]) {
735 use crate::ea::{encode_full_list, parse_full_list, parse_get_list, valid_name};
736 if let Ok(eas) = parse_full_list(data) {
737 assert!(!eas.is_empty());
738 assert!(eas.iter().all(|ea| valid_name(ea.name.as_bytes())));
739 assert_eq!(parse_full_list(&encode_full_list(&eas)), Ok(eas));
740 }
741 if let Ok(names) = parse_get_list(data) {
742 for (at, name) in names.iter().enumerate() {
743 assert!(valid_name(name.as_bytes()));
744 assert!(
745 !names[..at]
746 .iter()
747 .any(|before| before.eq_ignore_ascii_case(name))
748 );
749 }
750 }
751 }
752
753 /// Parses `data` as a lease break acknowledgment.
754 pub fn lease_ack(data: &[u8]) {
755 let _ = crate::proto::messages::LeaseBreakAck::parse(data);
756 }
757
758 /// Parses `data` as the data of each durable handle create context.
759 pub fn durable_context(data: &[u8]) {
760 use crate::proto::messages::{
761 DurableReconnect, DurableReconnectV2, DurableRequest, DurableRequestV2,
762 };
763 let _ = DurableRequest::parse(data);
764 let _ = DurableReconnect::parse(data);
765 let _ = DurableRequestV2::parse(data);
766 let _ = DurableReconnectV2::parse(data);
767 }
768
769 /// Parses `data` as a create context chain and reads its durable handle
770 /// contexts on each dialect.
771 pub fn durable_ask(data: &[u8]) {
772 use crate::proto::messages::{CreateContext, Dialect};
773 let Ok(contexts) = CreateContext::parse_chain(data) else {
774 return;
775 };
776 for dialect in [
777 None,
778 Some(Dialect::Smb202),
779 Some(Dialect::Smb210),
780 Some(Dialect::Smb300),
781 Some(Dialect::Smb302),
782 Some(Dialect::Smb311),
783 Some(Dialect::Smb2Wildcard),
784 ] {
785 let _ = crate::handlers::create::durable_ask(&contexts, dialect);
786 }
787 }
788
789 /// Parses `data` as a DCE/RPC PDU a client sends.
790 pub fn rpc_pdu(data: &[u8]) {
791 let _ = crate::rpc::pdu::parse(data);
792 }
793
794 /// Writes `data` to an association in chunks whose size the first
795 /// byte picks, answering every call with a fault and with its stub as
796 /// a response. Every PDU sent back parses, a response fits in the size
797 /// the bind negotiated, and what the association holds stays bounded.
798 pub fn rpc_association(data: &[u8]) {
799 use crate::rpc::association::{Association, Fault, Step};
800 use crate::rpc::pdu::{
801 self, MAX_FRAG, NCA_OP_RNG_ERROR, PTYPE_ALTER_CONTEXT_RESP, PTYPE_BIND_ACK,
802 PTYPE_RESPONSE,
803 };
804
805 let Some((&chunk, data)) = data.split_first() else {
806 return;
807 };
808 let chunk = usize::from(chunk).max(1);
809 let mut assoc = Association::default();
810 let mut max_frag = MAX_FRAG;
811 for mut piece in data.chunks(chunk) {
812 while let Some(step) = assoc.next_step(&mut piece) {
813 let sent = match step {
814 Step::Send(pdu) => vec![pdu],
815 Step::Call(call) => {
816 let fault = Fault {
817 status: NCA_OP_RNG_ERROR,
818 did_not_execute: true,
819 };
820 let mut replies = assoc.reply(&call, Err(fault));
821 replies.extend(assoc.reply(&call, Ok(call.stub.clone())));
822 replies
823 }
824 };
825 for pdu in sent {
826 assert!(pdu::parse(&pdu).is_some());
827 match pdu[2] {
828 PTYPE_BIND_ACK => max_frag = u16::from_le_bytes([pdu[16], pdu[17]]),
829 PTYPE_RESPONSE => assert!(pdu.len() <= usize::from(max_frag)),
830 PTYPE_ALTER_CONTEXT_RESP => {}
831 _ => assert!(pdu.len() <= usize::from(MAX_FRAG)),
832 }
833 }
834 assert!(assoc.held() <= (64 << 10) + usize::from(u16::MAX));
835 }
836 }
837 }
838
839 /// Runs `data` as a srvsvc request stub. The first byte picks the
840 /// operation: NetrShareEnum, NetrShareGetInfo, NetrServerGetInfo or,
841 /// with the second byte, any opnum. The caller sees three shares.
842 pub fn srvsvc_request(data: &[u8]) {
843 use crate::rpc::srvsvc::{self, ListedShare, ShareView};
844
845 let Some((&pick, stub)) = data.split_first() else {
846 return;
847 };
848 let (opnum, stub) = match pick % 4 {
849 0 => (srvsvc::OPNUM_SHARE_ENUM, stub),
850 1 => (srvsvc::OPNUM_SHARE_GET_INFO, stub),
851 2 => (srvsvc::OPNUM_SERVER_GET_INFO, stub),
852 _ => match stub.split_first() {
853 Some((&opnum, stub)) => (u16::from(opnum), stub),
854 None => return,
855 },
856 };
857 let share = |name: &str, kind, remark: &str| ListedShare {
858 name: name.to_string(),
859 kind,
860 remark: remark.to_string(),
861 };
862 let view = ShareView {
863 server_name: "FUZZ".to_string(),
864 shares: vec![
865 share("public", 0, ""),
866 share("d\u{f6}cs$", 0, "\u{1F9A4} remark"),
867 share("IPC$", 0x8000_0003, "Remote IPC"),
868 ],
869 };
870 let _ = srvsvc::call(opnum, stub, &view);
871 }
872
873 /// Runs `data` through the WS-Discovery target service: the first byte
874 /// picks the family of the sender, the next 4 or 16 bytes its address
875 /// and 2 its port, and the rest is the datagram. A reply goes only to a
876 /// sender on the link, and is a well-formed envelope that fits a
877 /// datagram.
878 #[cfg(all(feature = "discovery", unix))]
879 pub fn wsd_datagram(data: &[u8]) {
880 crate::discovery::wsd::fuzz_datagram(data);
881 }
882
883 /// Answers `data` as a whole request to the WS-Discovery metadata
884 /// endpoint.
885 #[cfg(all(feature = "discovery", unix))]
886 pub fn wsd_http(data: &[u8]) {
887 crate::discovery::wsd::fuzz_http(data);
888 }
889
890 /// Parses `data` as stored data of an encrypted share under a fixed key.
891 /// The first byte picks the parser (marker, file header, short name, long
892 /// name, sizes or block) and the rest is its input.
893 #[cfg(feature = "encryption")]
894 pub fn encrypted_input(data: &[u8]) {
895 crate::encrypted::fuzz_input::run(data);
896 }
897
898 /// Dispatches one frame payload on a fresh connection to `server`.
899 pub async fn dispatch(server: &crate::SmbServer, frame: &[u8]) -> Option<Vec<u8>> {
900 let state = server.state();
901 let conn = Arc::new(Connection::new(
902 state.config.server_guid,
903 state.config.max_read_size,
904 state.config.max_write_size,
905 ));
906 crate::dispatch::dispatch_frame(&state, &conn, frame)
907 .await
908 .map(|out| out.bytes)
909 }
910}