Skip to main content

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