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.
56//!
57//! What the protocol layer does around the backend calls:
58//!
59//! - Paths arrive as [`SmbPath`], relative to the share root. `.` components
60//!   are dropped; `..`, empty components, `<>:"|?*`, control characters and
61//!   stream names are rejected before the backend sees them. The empty path
62//!   is the share root.
63//! - `open` fails with [`SmbError::PathNotFound`] when a directory on the
64//!   way to the path is missing, and with [`SmbError::NotFound`] when only
65//!   the last component is. Clients see STATUS_OBJECT_PATH_NOT_FOUND and
66//!   STATUS_OBJECT_NAME_NOT_FOUND.
67//! - Share permissions and the access the client asked for are checked
68//!   before `open`. [`OpenOptions`] carries the result: `read`, `write` and
69//!   `write_attributes` reflect the access granted to the open. READ and
70//!   WRITE on a handle without the matching access fail before the handle
71//!   is called. When [`BackendCapabilities::is_read_only`] is set, trees on
72//!   the share get read access only, so opens that ask for write access,
73//!   and dispositions that create or truncate, fail before `open`.
74//! - Share modes, byte-range locks and the delete-pending flag are kept by
75//!   the protocol layer per share, across every connection, keyed by
76//!   [`FileInfo::file_index`], or by path when it is 0. Two shares over
77//!   the same directory do not see each other's opens. A CREATE that would
78//!   truncate first opens the file without truncating it, for reading or,
79//!   when reading is refused, with the access the CREATE was granted. It
80//!   runs the checks, enters the open in the table and waits for lease
81//!   breaks, so the sharing mode holds and clients caching writes have
82//!   written back before `open` truncates. When that first open finds no
83//!   file, the CREATE calls `open` with [`OpenIntent::Create`] instead and
84//!   starts over if the file appeared meanwhile. Any other CREATE refused
85//!   by the share-mode check has already called `open` and closes the new
86//!   handle again.
87//! - [`Handle::close`] runs on every path that ends an open: CLOSE,
88//!   TREE_DISCONNECT, LOGOFF, the end of a session or connection, and
89//!   [`ConfigHandle`] changes that end sessions or trees. A durable open,
90//!   described below, outlives LOGOFF and the end of its connection or
91//!   session for a while. Before `close`, [`Handle::set_times`] puts back
92//!   access and write times that FileBasicInformation froze or set through
93//!   that open.
94//! - Delete-on-close: [`OpenOptions::delete_on_close`] and
95//!   FileDispositionInformation make the file delete-pending. When its last
96//!   open ends, on any of the paths above, the protocol layer calls
97//!   [`Handle::close`] and then [`ShareBackend::unlink`] on the file's
98//!   current path. `open` doesn't delete anything itself. Read-only files
99//!   are refused before that point, and so, for SET_INFO, are directories
100//!   that [`Handle::dir_is_empty`] reports as not empty. `unlink` returns
101//!   [`SmbError::NotEmpty`] for a directory that has entries; the directory
102//!   then stays.
103//! - A rename through SET_INFO of a directory with a file or directory open
104//!   below it first asks the clients caching handles to those files to
105//!   close them, and waits until they answer or the break times out; files
106//!   kept open for a client to reconnect are closed. If an open below
107//!   remains, the rename fails with STATUS_ACCESS_DENIED, and so does a
108//!   rename of the share root. Otherwise the rename calls
109//!   [`ShareBackend::rename`] and then moves the path of every open of the
110//!   old name. Renames on one share run
111//!   one at a time, and a CREATE or a delete waits for a rename in
112//!   progress. The backend keeps those handles working on the renamed file.
113//! - A CREATE that makes or overwrites a file passes the attributes it asks
114//!   for to [`Handle::set_attributes`] when they differ from what
115//!   [`Handle::stat`] reports. If that returns [`SmbError::NotSupported`],
116//!   it retries with READONLY alone when that was asked for; the CREATE
117//!   succeeds either way.
118//! - FileBasicInformation passes [`Handle::set_attributes`] and
119//!   [`Handle::set_times`] only the values that differ from what
120//!   [`Handle::stat`] reports. After a write or truncate, `set_times` also
121//!   puts back the times FileBasicInformation froze or set.
122//!   [`Handle::truncate`] is never called on a directory.
123//! - QUERY_DIRECTORY calls [`Handle::list_dir`] with the search pattern on
124//!   the first query and on a restart, then pages through the returned
125//!   entries itself. It adds `.` and `..` when the pattern matches them,
126//!   and opens the parent directory to describe `..`; at the share root,
127//!   `..` describes the root itself, with file id 0.
128//! - FileStandardInformation and FileAllInformation report
129//!   [`Handle::link_count`] as NumberOfLinks, and DeletePending when the
130//!   file is delete-pending or has no links left. The filesystem
131//!   QUERY_INFO classes, and the VolumeId of the on-disk id CREATE context,
132//!   come from [`ShareBackend::volume_info`].
133//! - Leases: on every share unless [`Share::leases`] turns them off, files
134//!   get read, handle and write caching leases. A client holding one
135//!   caches what it reads, keeps files open after its applications close
136//!   them, and caches writes while every other open of the file holds the
137//!   same lease or is attribute-only. An open, write, size change,
138//!   byte-range lock, rename or delete made through an open that does not
139//!   hold the lease breaks it when it needs what the lease caches, whether
140//!   that open belongs to another client or to the same client under
141//!   another lease key or none; attribute-only opens and opens holding the
142//!   same lease break nothing. An open or rename that needs the client to
143//!   write back or close first waits until the client acknowledges the
144//!   break or closes, or until the break times out 35 seconds after the
145//!   server sent it; meanwhile its backend handle stays open, except for
146//!   one that truncates, which calls `open` after the wait. A byte-range
147//!   lock asked for while another lease still caches writes is refused
148//!   with STATUS_LOCK_NOT_GRANTED until that client has written back.
149//!   Changes made outside the server, including through another share over
150//!   the same directory, break nothing: clients keep serving stale cached
151//!   data. Turn leases off on such shares.
152//! - Durable handles: on a share with leases, unless
153//!   [`Share::durable_handles`] turns them off, a file opened with a
154//!   durable handle request (DHnQ, or DH2Q on SMB 3.x) and a lease that
155//!   caches handles stays open when the client's connection drops, when it
156//!   logs off, when its session's reauthentication fails, or when a new
157//!   session names its session as the previous one. A request without such
158//!   a lease gets an open that is not durable and no durable context in the
159//!   response. The backend handle stays open, and the file keeps its share
160//!   mode, byte-range locks and lease, for
161//!   [`SmbServerBuilder::durable_handle_timeout`], or for the time a DH2Q
162//!   asked for, up to that timeout or 5 minutes, whichever is longer; the
163//!   DH2Q response carries the time granted. The PERSISTENT flag is
164//!   ignored. A file whose lease is being broken, or that holds byte-range
165//!   locks under a lease that does not cache writes, closes with its
166//!   session instead. Meanwhile the same user, from the same client, takes
167//!   the file back with a durable handle reconnect (DHnC, or DH2C naming
168//!   the CreateGuid of a DH2Q open) on a tree of the same share that names
169//!   the file and its lease; the backend handle, share mode, byte-range
170//!   locks and lease carry on, and later lease breaks go to the new
171//!   connection. A reconnect fails with STATUS_ACCESS_DENIED from another
172//!   user, STATUS_INVALID_PARAMETER for a DHnC naming another file, and
173//!   STATUS_INSUFFICIENT_RESOURCES past the connection's open limit; from
174//!   another client, on another share, naming another lease, lease version
175//!   or CreateGuid, a DH2C naming another file, or for a file that is not
176//!   kept, with STATUS_OBJECT_NAME_NOT_FOUND. The file stays kept after a
177//!   failed reconnect. One that comes while the connection holding the file
178//!   is still closing waits up to 5 seconds for it. A file whose rights
179//!   exceed what the user's tree on the share grants now is closed instead
180//!   of reconnected. [`Handle::close`] runs when the time runs out; at once
181//!   when an open, write, size change, byte-range lock, rename or delete
182//!   through an open that does not hold the lease needs what the lease
183//!   caches, or when the lease stops caching handles; on [`ConfigHandle`]
184//!   changes that end the user's sessions or the share's trees; and at
185//!   shutdown. At most [`SmbServerBuilder::max_disconnected_opens`] files
186//!   are kept at once, and a quarter of that, rounded up, for one user;
187//!   past that, files close with their session. Anonymous sessions and
188//!   clients that send a nil ClientGuid get no durable handle. A DH2Q that
189//!   repeats the CreateGuid of a live version 2 open of the same client,
190//!   with access to its data or to delete it, fails with
191//!   STATUS_DUPLICATE_OBJECTID unless it is marked as a replay; one marked
192//!   as a replay opens the file anew rather than answering with that
193//!   open.
194//! - Change notifications: on every share unless [`Share::change_notify`]
195//!   turns them off, a CHANGE_NOTIFY on a directory waits until a file or
196//!   directory in it, or below it when the client asks for the whole tree,
197//!   changes through any connection to the share:
198//!   - A create or delete is reported as an addition or a removal.
199//!   - A rename within one directory is reported as its old and new name
200//!     together, a move to another directory as a removal from one and an
201//!     addition to the other. Either is followed by a modification, under
202//!     LAST_WRITE, of the directory the entry is in afterwards, unless that
203//!     is the share root. An entry the rename replaces,
204//!     or the renamed entry itself when only the case of its name changes,
205//!     is first reported removed under its name as stored. A watched
206//!     directory can be renamed, and its watches follow it.
207//!   - Attributes and times set through FileBasicInformation are reported
208//!     at once as a modification, under ATTRIBUTES and the bit of each time
209//!     changed but the change time. What changed is what [`Handle::stat`]
210//!     shows differently afterwards, so a value the backend does not keep
211//!     reports nothing.
212//!   - New contents are reported as a modification under SIZE, LAST_WRITE
213//!     and ATTRIBUTES: a write once, when the open that wrote closes, unless
214//!     that close deletes the file; a change of size through
215//!     FileEndOfFileInformation, a truncation through
216//!     FileAllocationInformation, and an overwrite or supersede by CREATE,
217//!     at once.
218//!
219//!   A watched directory marked for deletion, through
220//!   FileDispositionInformation or by the close of an open that asked for
221//!   delete-on-close while other opens of it remain, ends every watch of
222//!   it: the requests waiting on them, and any request on an open of the
223//!   directory while it stays delete-pending, get STATUS_DELETE_PENDING. An
224//!   open that marked the directory, and any open made with delete-on-close,
225//!   always gets STATUS_DELETE_PENDING; once the mark is cleared, other
226//!   opens watch again. Watches of the directories above it stay, and hear
227//!   the removal once the directory is deleted.
228//!
229//!   Changes are buffered on the directory handle between requests, up to
230//!   the buffer size of its first request and at most 64 KiB; when more
231//!   arrive, or they do not fit the request being answered, the answer is
232//!   STATUS_NOTIFY_ENUM_DIR. Watches follow paths: a change made through a
233//!   symlink inside the share reaches the watchers of the path it was made
234//!   through, and on Linux, as a change on disk, those of the directory
235//!   the symlink leads to. Names are spelled as the client that made the
236//!   change spelled them, but for the stored names above.
237//!
238//!   Changes made outside the server, or through another share over the
239//!   same directory, are reported when the backend's [`Handle::watch`]
240//!   reports them. `LocalFsBackend` does on Linux, through inotify, unless
241//!   its `watch_host_changes` turns it off: additions, removals, renames
242//!   within the directory, new contents when a writer closes the file
243//!   (under SIZE, LAST_WRITE and ATTRIBUTES) and attribute or time changes
244//!   (under ATTRIBUTES) of the entries directly in a watched directory,
245//!   also for a client that asks for the whole tree. A move out of or into
246//!   the directory is a removal or an addition, and so is a rename from or
247//!   to a name the server cannot use. A lost kernel queue, and a watched
248//!   directory renamed or moved outside the server, are answered
249//!   STATUS_NOTIFY_ENUM_DIR; such a directory stays watched under its old
250//!   name. A watched directory deleted outside the server, or replaced by a
251//!   rename, ends its watches with STATUS_DELETE_PENDING, and every later
252//!   CHANGE_NOTIFY on its handles gets the same. The parent of each watched
253//!   directory is watched too, the share root's parent included, only to
254//!   see the directory go. A change in a parent is reported only to the
255//!   watchers of that parent, so a change in the share root's parent is
256//!   reported to no one. One backend holds at most 4096 kernel watches,
257//!   parents included. A directory past that, or one the kernel will not
258//!   watch, past `fs.inotify.max_user_watches` or
259//!   `fs.inotify.max_user_instances` or without `/proc`, gets only the
260//!   changes made through the server, with a warning logged once. Other
261//!   backends and platforms report only changes made through the server.
262//!
263//!   The server leaves out the backend's reports of its own changes. Each
264//!   addition, removal or rename it made in the last 5 seconds drops one
265//!   matching backend report. A modification or attribute change is
266//!   dropped while an open through the server that may write the entry's
267//!   data or attributes has it open, for 5 seconds after the server
268//!   reported a change to it or closed an open that wrote it or restored
269//!   times fixed through it, and once after it closed an open that could
270//!   write it, or created or overwrote it, and wrote nothing. A backend
271//!   report waits up to 200 milliseconds for that comparison, and goes out
272//!   before any change the server reports after it arrived in the same
273//!   directory, or below it to a watch of the whole tree.
274//!
275//!   The backend is called for these reports in four cases:
276//!   [`Handle::watch`], through an open of a watched directory, on the
277//!   first request on that directory and on the next request after the
278//!   backend's reports stopped; a
279//!   FileBasicInformation that passed something to the backend calls
280//!   [`Handle::stat`] once more; a size change on a share with watches
281//!   calls `stat` before and after; and a rename into a watched directory
282//!   that may replace an entry or changes the case of a name calls, on a
283//!   case-sensitive backend, [`ShareBackend::open`] of the target and
284//!   `stat`, otherwise `open` of the target's directory and
285//!   [`Handle::list_dir`] with the target's name.
286//! - Share listing: unless [`SmbServerBuilder::share_listing`] turns it
287//!   off, IPC$ serves the `srvsvc` pipe, so clients can list the server's
288//!   shares. A session sees the shares it may connect to, in the order
289//!   they were added, and IPC$; for an anonymous session that is the
290//!   public shares, and a session that cannot encrypt does not see shares
291//!   whose traffic is encrypted. [`Share::listed`] leaves a share out of
292//!   the list without hiding it from lookups by name, and
293//!   [`Share::remark`] sets the comment shown next to it. Backends are not
294//!   called. Other pipe names fail with STATUS_OBJECT_NAME_NOT_FOUND,
295//!   DCE/RPC binds that carry authentication are refused, and one
296//!   connection may hold 16 pipes at once.
297//! - READ and WRITE lengths are bounded by the negotiated maximum sizes.
298//! - Each [`SmbError`] maps to one NTSTATUS for the client; see
299//!   [`SmbError::to_nt_status`].
300//!
301//! A handle is dropped without [`Handle::close`] when the task serving its
302//! connection panics or is cancelled, and when a [`ConfigHandle`] call that
303//! ends its session or tree is cancelled, so release resources in `Drop` as
304//! well.
305//!
306//! Later releases may add methods with default bodies, fields to
307//! [`FileInfo`], [`BackendCapabilities`], [`VolumeInfo`] and [`DirChange`],
308//! and variants to [`OpenIntent`] and [`DirChangeKind`]. A backend that
309//! implements the required methods, builds those types through
310//! [`FileInfo::new`], [`DirChange::new`] and the `Default` impls, and
311//! matches `OpenIntent` and `DirChangeKind` with a wildcard arm keeps
312//! compiling.
313
314mod access_mask;
315mod auth_policy;
316mod backend;
317mod builder;
318pub(crate) mod conn;
319#[cfg(feature = "discovery")]
320mod discovery;
321mod dispatch;
322mod error;
323mod files;
324#[cfg(feature = "localfs")]
325mod fs;
326mod handlers;
327pub(crate) mod info_class;
328pub mod ntstatus;
329mod path;
330mod proto;
331mod rpc;
332mod server;
333#[cfg(test)]
334mod tests {
335    mod async_requests;
336    #[cfg(feature = "discovery")]
337    mod discovery;
338    mod durable;
339    mod dynamic_config;
340    pub(crate) mod memfs;
341    mod notify;
342    pub(crate) mod peer;
343    mod pipes;
344}
345mod utils;
346mod wildcard;
347
348pub use backend::{
349    BackendCapabilities, DirChange, DirChangeKind, DirEntry, DirWatch, FileInfo, FileTimes, Handle,
350    OpenAction, OpenIntent, OpenOptions, ShareBackend, VolumeInfo,
351};
352pub use builder::{Access, BuildError, Share, SmbServerBuilder};
353pub use bytes::Bytes;
354#[cfg(feature = "discovery")]
355pub use discovery::Discovery;
356pub use error::{SmbError, SmbResult};
357pub use files::{
358    DEFAULT_DURABLE_HANDLE_TIMEOUT, DEFAULT_MAX_DISCONNECTED_OPENS, DEFAULT_MAX_LOCKS_PER_OPEN,
359    DEFAULT_MAX_OPENS_PER_CONNECTION,
360};
361#[cfg(feature = "localfs")]
362pub use fs::LocalFsBackend;
363pub use path::SmbPath;
364pub use proto::auth::ntlm::Identity;
365pub use server::{ConfigError, ConfigHandle, ShareMode, ShutdownHandle, SmbServer};
366
367pub mod wire {
368    pub use crate::proto::header;
369    pub use crate::proto::messages;
370}
371
372/// Entry points for the cargo-fuzz targets in `fuzz/`. Built only with
373/// `--cfg fuzzing`, which `cargo fuzz` sets.
374#[cfg(fuzzing)]
375#[doc(hidden)]
376pub mod fuzzing {
377    use std::sync::Arc;
378
379    use crate::conn::state::Connection;
380    use crate::proto::auth::{ntlm, spnego};
381    use crate::proto::framing;
382    use crate::proto::header::Smb2Header;
383
384    /// Decodes the start of `data` as a transport frame header.
385    pub fn frame(data: &[u8]) {
386        if let Some(hdr) = data.first_chunk::<{ framing::FRAME_HEADER_LEN }>() {
387            let _ = framing::decode_frame_header(hdr);
388        }
389    }
390
391    /// Parses `data` as an SMB2 header.
392    pub fn header(data: &[u8]) {
393        let _ = Smb2Header::parse(data);
394    }
395
396    /// Decodes `data` as a SPNEGO NegTokenInit and as a NegTokenResp.
397    pub fn spnego(data: &[u8]) {
398        let _ = spnego::decode_init_token(data);
399        let _ = spnego::decode_resp_token(data);
400    }
401
402    /// Parses `data` as each NTLM message the server receives.
403    pub fn ntlm(data: &[u8]) {
404        let _ = ntlm::NtlmNegotiate::parse(data);
405        let _ = ntlm::NtlmAuthenticate::parse(data);
406    }
407
408    /// Parses `data` as the data of a lease create context.
409    pub fn lease_context(data: &[u8]) {
410        let _ = crate::proto::messages::LeaseContext::parse(data);
411    }
412
413    /// Parses `data` as a lease break acknowledgment.
414    pub fn lease_ack(data: &[u8]) {
415        let _ = crate::proto::messages::LeaseBreakAck::parse(data);
416    }
417
418    /// Parses `data` as the data of each durable handle create context.
419    pub fn durable_context(data: &[u8]) {
420        use crate::proto::messages::{
421            DurableReconnect, DurableReconnectV2, DurableRequest, DurableRequestV2,
422        };
423        let _ = DurableRequest::parse(data);
424        let _ = DurableReconnect::parse(data);
425        let _ = DurableRequestV2::parse(data);
426        let _ = DurableReconnectV2::parse(data);
427    }
428
429    /// Parses `data` as a create context chain and reads its durable handle
430    /// contexts on each dialect.
431    pub fn durable_ask(data: &[u8]) {
432        use crate::proto::messages::{CreateContext, Dialect};
433        let Ok(contexts) = CreateContext::parse_chain(data) else {
434            return;
435        };
436        for dialect in [
437            None,
438            Some(Dialect::Smb202),
439            Some(Dialect::Smb210),
440            Some(Dialect::Smb300),
441            Some(Dialect::Smb302),
442            Some(Dialect::Smb311),
443            Some(Dialect::Smb2Wildcard),
444        ] {
445            let _ = crate::handlers::create::durable_ask(&contexts, dialect);
446        }
447    }
448
449    /// Parses `data` as a DCE/RPC PDU a client sends.
450    pub fn rpc_pdu(data: &[u8]) {
451        let _ = crate::rpc::pdu::parse(data);
452    }
453
454    /// Writes `data` to an association in chunks whose size the first
455    /// byte picks, answering every call with a fault and with its stub as
456    /// a response. Every PDU sent back parses, a response fits in the size
457    /// the bind negotiated, and what the association holds stays bounded.
458    pub fn rpc_association(data: &[u8]) {
459        use crate::rpc::association::{Association, Fault, Step};
460        use crate::rpc::pdu::{
461            self, MAX_FRAG, NCA_OP_RNG_ERROR, PTYPE_ALTER_CONTEXT_RESP, PTYPE_BIND_ACK,
462            PTYPE_RESPONSE,
463        };
464
465        let Some((&chunk, data)) = data.split_first() else {
466            return;
467        };
468        let chunk = usize::from(chunk).max(1);
469        let mut assoc = Association::default();
470        let mut max_frag = MAX_FRAG;
471        for mut piece in data.chunks(chunk) {
472            while let Some(step) = assoc.next_step(&mut piece) {
473                let sent = match step {
474                    Step::Send(pdu) => vec![pdu],
475                    Step::Call(call) => {
476                        let fault = Fault {
477                            status: NCA_OP_RNG_ERROR,
478                            did_not_execute: true,
479                        };
480                        let mut replies = assoc.reply(&call, Err(fault));
481                        replies.extend(assoc.reply(&call, Ok(call.stub.clone())));
482                        replies
483                    }
484                };
485                for pdu in sent {
486                    assert!(pdu::parse(&pdu).is_some());
487                    match pdu[2] {
488                        PTYPE_BIND_ACK => max_frag = u16::from_le_bytes([pdu[16], pdu[17]]),
489                        PTYPE_RESPONSE => assert!(pdu.len() <= usize::from(max_frag)),
490                        PTYPE_ALTER_CONTEXT_RESP => {}
491                        _ => assert!(pdu.len() <= usize::from(MAX_FRAG)),
492                    }
493                }
494                assert!(assoc.held() <= (64 << 10) + usize::from(u16::MAX));
495            }
496        }
497    }
498
499    /// Runs `data` as a srvsvc request stub. The first byte picks the
500    /// operation: NetrShareEnum, NetrShareGetInfo, NetrServerGetInfo or,
501    /// with the second byte, any opnum. The caller sees three shares.
502    pub fn srvsvc_request(data: &[u8]) {
503        use crate::rpc::srvsvc::{self, ListedShare, ShareView};
504
505        let Some((&pick, stub)) = data.split_first() else {
506            return;
507        };
508        let (opnum, stub) = match pick % 4 {
509            0 => (srvsvc::OPNUM_SHARE_ENUM, stub),
510            1 => (srvsvc::OPNUM_SHARE_GET_INFO, stub),
511            2 => (srvsvc::OPNUM_SERVER_GET_INFO, stub),
512            _ => match stub.split_first() {
513                Some((&opnum, stub)) => (u16::from(opnum), stub),
514                None => return,
515            },
516        };
517        let share = |name: &str, kind, remark: &str| ListedShare {
518            name: name.to_string(),
519            kind,
520            remark: remark.to_string(),
521        };
522        let view = ShareView {
523            server_name: "FUZZ".to_string(),
524            shares: vec![
525                share("public", 0, ""),
526                share("d\u{f6}cs$", 0, "\u{1F9A4} remark"),
527                share("IPC$", 0x8000_0003, "Remote IPC"),
528            ],
529        };
530        let _ = srvsvc::call(opnum, stub, &view);
531    }
532
533    /// Runs `data` through the WS-Discovery target service: the first byte
534    /// picks the family of the sender, the next 4 or 16 bytes its address
535    /// and 2 its port, and the rest is the datagram. A reply goes only to a
536    /// sender on the link, and is a well-formed envelope that fits a
537    /// datagram.
538    #[cfg(all(feature = "discovery", unix))]
539    pub fn wsd_datagram(data: &[u8]) {
540        crate::discovery::wsd::fuzz_datagram(data);
541    }
542
543    /// Answers `data` as a whole request to the WS-Discovery metadata
544    /// endpoint.
545    #[cfg(all(feature = "discovery", unix))]
546    pub fn wsd_http(data: &[u8]) {
547        crate::discovery::wsd::fuzz_http(data);
548    }
549
550    /// Dispatches one frame payload on a fresh connection to `server`.
551    pub async fn dispatch(server: &crate::SmbServer, frame: &[u8]) -> Option<Vec<u8>> {
552        let state = server.state();
553        let conn = Arc::new(Connection::new(
554            state.config.server_guid,
555            state.config.max_read_size,
556            state.config.max_write_size,
557        ));
558        crate::dispatch::dispatch_frame(&state, &conn, frame)
559            .await
560            .map(|out| out.bytes)
561    }
562}