Skip to main content

smb_server/fs/
local.rs

1//! `LocalFsBackend`: a `ShareBackend` backed by a real on-disk directory.
2//!
3//! The share root is opened once via `Dir::open_ambient_dir` and kept as the
4//! sole authority handle. All subsequent path operations are resolved
5//! relative to that handle, one name at a time, so a malicious symlink or
6//! `..` smuggled through `SmbPath` cannot escape the sandbox: `cap-std`
7//! enforces this at every step on Unix, and `windows_dir` on Windows.
8//!
9//! - Blocking FS calls run on `tokio::task::spawn_blocking`.
10//! - `read_only()` flips a flag that makes write-class opens reject early
11//!   with `SmbError::AccessDenied`.
12//! - `list_dir` applies the MS-FSA 2.1.4.4 wildcards (`*`, `?`, `<`, `>`,
13//!   `"`) itself, since a `Dir` only lists raw `entries()`. Matching
14//!   ignores case only where the host looks names up case-insensitively.
15//!   `"*.*"` matches every name, as `"*"` does.
16//! - Listings leave out names a client could not open again: names that are
17//!   not valid UTF-8 or not valid `SmbPath` components.
18//! - Name lookups are case-sensitive or not as the host filesystem reports
19//!   for the share root.
20//! - On Windows, directory handles share delete access, so a client can
21//!   rename or delete a directory it or another client has open.
22
23use std::io;
24use std::path::{Path, PathBuf};
25use std::sync::Arc;
26use std::time::{Duration, SystemTime, UNIX_EPOCH};
27
28use async_trait::async_trait;
29use bytes::Bytes;
30use tokio::task::spawn_blocking;
31use tracing::debug;
32
33use crate::backend::{
34    BackendCapabilities, DirEntry as SmbDirEntry, FileInfo, FileTimes, Handle, OpenAction,
35    OpenIntent, OpenOptions, ShareBackend,
36};
37use crate::error::{SmbError, SmbResult};
38use crate::path::{SmbPath, same_path};
39#[cfg(any(target_os = "linux", target_os = "macos", windows))]
40use crate::stream::StreamName;
41use crate::utils::{FILETIME_OFFSET, system_time_to_filetime};
42
43use super::dir::{Dir, Metadata, OpenOptions as DirOpenOptions, ambient_authority};
44use super::volume;
45use crate::backend::VolumeInfo;
46use crate::path::is_valid_component;
47use crate::wildcard::Pattern;
48
49// ---------------------------------------------------------------------------
50// Backend
51// ---------------------------------------------------------------------------
52
53/// Local-filesystem backend, sandboxed at a single root directory.
54///
55/// Handles set access and write times on every host. The creation time is
56/// set on Windows and macOS; other hosts have no call that sets it, so a
57/// requested creation time is ignored there and the other times still apply.
58/// The host keeps the change time.
59///
60/// On Unix, FIFOs, sockets and device nodes are listed, and an open of one,
61/// or of a symlink to one, fails with STATUS_IO_REPARSE_TAG_NOT_HANDLED.
62/// On Linux, an open that conflicts with a file lease (`F_SETLEASE`) fails
63/// with STATUS_SHARING_VIOLATION instead of waiting; the kernel starts
64/// breaking the lease, so a retry succeeds once the holder releases it.
65///
66/// On Linux, the backend reports [`BackendCapabilities::block_cloning`] when
67/// the filesystem of the share root clones ranges between files, as Btrfs and
68/// XFS with reflinks do. It asks the kernel once, when it is made, with two
69/// temporary files that have no name in the share root, so a share root the
70/// server cannot create files in, or one on a filesystem without unnamed
71/// temporary files, reports none. A read-only backend reports none.
72///
73/// On Windows, it reports `block_cloning` when the volume of the share root
74/// reports FILE_SUPPORTS_BLOCK_REFCOUNTING, which ReFS does. A clone of a
75/// sparse file makes the target sparse first.
76///
77/// On Linux, a file's or directory's named streams are its extended
78/// attributes named `user.DosStream.<name>:$DATA`, each holding the
79/// stream's data followed by one NUL byte. A share moves between this
80/// server and Samba's `vfs_streams_xattr` with its streams. Of attributes
81/// whose names differ only in case, the one that sorts first in byte order
82/// is the stream; removing or replacing the stream removes them all.
83///
84/// A stream that outgrows its extended attribute, past 65535 bytes or past
85/// the room the filesystem gives a file's extended attributes (one block
86/// for all of them on ext4), moves to the stream store, and stays there
87/// until it is removed or cut to zero. The store is the directory
88/// `.smb-streams` in the share root, mode 0700, or the one
89/// [`LocalFsBackend::stream_store`] names, made with the first request to a
90/// writable share. Clients cannot open, list or rename into it under any
91/// name, and cannot create its name in the share root; with a store, paths
92/// are looked up one name at a time from the share root, each directory
93/// opened from the one before. The store has a directory per file, named by
94/// a random id that the file keeps in the extended attribute
95/// `user.smb-server.streams` (its record) with its identity, so its streams
96/// follow it through renames and hard links. A file that carries another
97/// file's record, as a copy with its extended attributes does, reads that
98/// file's streams, and gets an id of its own with a copy of them before any
99/// of them changes. The identity is the file handle where the filesystem
100/// gives one, else the inode number and birth time; on filesystems whose
101/// inode numbers or handles change, such as some FUSE filesystems, every
102/// file looks like a copy and copies its streams once more each time, and a
103/// file in a snapshot reads the live file's streams in the store. A record
104/// of another store is left alone, and that file's streams stay in extended
105/// attributes. Removed files leave their streams in the store until
106/// [`LocalFsBackend::sweep_streams`] removes them. A stream whose name
107/// takes more than 126 bytes in UTF-8 cannot move to the store, and a
108/// write past what its extended attribute holds fails with
109/// STATUS_DISK_FULL, as does a new stream on a file with 4096. A rename
110/// between the default stream and a named one copies at most 64 MiB where
111/// the filesystem cannot clone the data.
112///
113/// Whether the share has named streams is decided once, by probing the
114/// share root for user extended attributes. Below the root, a mount
115/// without them lists no streams, and a stream request there fails with
116/// STATUS_ACCESS_DENIED.
117///
118/// On macOS, a file's or directory's named streams are its extended
119/// attributes, and the host's Finder shows the tags, comments, labels and
120/// icons clients set. `AFP_AfpInfo` is `com.apple.FinderInfo`, in the
121/// 60-byte AfpInfo layout around its 32 bytes: a write must be those 60
122/// bytes at offset 0, starting with `AFP\0`, or it fails with
123/// STATUS_INVALID_PARAMETER, and Finder info of all zeros, a cut to zero
124/// or an overwrite removes the attribute. An `AFP_AfpInfo` stream without
125/// the attribute reads as AfpInfo with Finder info of all zeros and is not
126/// listed; a client can create it, and the first write stores it.
127/// `AFP_Resource` is `com.apple.ResourceFork`, which holds no empty fork:
128/// an `AFP_Resource` stream exists once it has data. Directories have no
129/// resource fork. Any other stream is the attribute of the same name, with
130/// the characters macOS clients send as U+F001 to U+F029 mapped back, so
131/// `com.apple.metadata\u{F022}_kMDItemUserTags` is the attribute
132/// `com.apple.metadata:_kMDItemUserTags`, and attributes list under those
133/// names. A stream name holds such characters only that way: `a*b` is an
134/// invalid name, and `a\u{F021}b` names the attribute `a*b`. Attribute
135/// names no stream name leads to, and `com.apple.FinderInfo` and
136/// `com.apple.ResourceFork` spelled in another case, are left out; a
137/// stream name that maps to one of them, or to more than 127 bytes, is
138/// invalid. Attributes whose names differ only in case are one stream, as
139/// on Linux. A write or size change that would leave `AFP_Resource` larger
140/// than 16 MiB, or another stream larger than 1 MiB, fails with
141/// STATUS_DISK_FULL, as does a rename that moves more than the target
142/// holds, and a read of a stream other than those two that the host made
143/// larger than 1 MiB fails with STATUS_ACCESS_DENIED. Reads of a resource
144/// fork stop at 4 GiB. An overwrite or supersede of a file removes every
145/// attribute it lists as a stream, `com.apple.quarantine` and others the
146/// host set included. A share on a volume that keeps extended attributes
147/// only in `._` files, such as FAT or exFAT, has no named streams.
148///
149/// On Windows, a file's or directory's named streams are its NTFS
150/// alternate data streams, under the names clients send, each opened
151/// relative to a handle of its file inside the share without following
152/// reparse points. NTFS compares stream names by the uppercase form of
153/// each character and keeps the spelling a stream was made with; names
154/// that differ only in a character without a one-character uppercase form,
155/// such as U+00DF and U+1E9E, are two streams to NTFS and one to the
156/// server's share modes and locks, while U+03C2 and U+03C3 are one stream
157/// to NTFS and two to the server. A file lists at most 4096 named streams,
158/// and a new stream past that fails with STATUS_DISK_FULL. Whether the
159/// share has named streams is decided once, from the volume of the share
160/// root: FAT and exFAT volumes have none. ReFS cannot rename streams: a
161/// stream rename there fails with STATUS_INVALID_PARAMETER, and a stream
162/// larger than the volume holds fails with STATUS_DISK_FULL.
163///
164/// On Linux, a file's or directory's extended attributes are its extended
165/// attributes named `user.<name>`, the layout Samba uses, when the
166/// filesystem of the share root stores user extended attributes. Names
167/// compare without regard to ASCII case: a set or a removal acts on the
168/// attribute as the host spells it, and a new one keeps the client's
169/// spelling. Of attributes whose names differ only in case, the one that
170/// sorts first in byte order is listed, and a set or removal of the name
171/// replaces or removes them all. Names longer than 250 bytes fail with
172/// STATUS_INVALID_EA_NAME. These host attributes are hidden, and a set of
173/// one of their names fails with STATUS_ACCESS_DENIED, in any case: names
174/// clients cannot send, `user.DosStream.*`, `user.smb-server.*`, and
175/// Samba's `user.DOSATTRIB`, `user.SAMBA_PAI`, `user.SAMBA_STREAMS`,
176/// `user.SmbReparse` and `user.org.netatalk.Metadata`. FILE_NEED_EA is not
177/// kept. A set that does not fit, past the room the filesystem gives a
178/// file's extended attributes (one block for all of them on ext4), fails
179/// with STATUS_EA_TOO_LARGE and changes nothing. A set on a read-only file
180/// fails with STATUS_ACCESS_DENIED unless the server may write the file
181/// whatever its mode.
182///
183/// On Windows, a share root may be a UNC path or a mapped drive. A lookup
184/// holds each directory on its way open without delete sharing until it
185/// ends, so the server's account needs traverse rights on the share's
186/// directories, and a rename or delete of a directory a lookup is passing
187/// through fails with STATUS_SHARING_VIOLATION.
188///
189/// On Windows, a rename refused with STATUS_ACCESS_DENIED, as a directory
190/// rename is while another program has an entry below it open, is tried
191/// again for up to one second before it fails.
192///
193/// On Windows, where the share root is on another machine, the SMB client
194/// of Windows can store a new name in the case another program uses to
195/// open it at the same moment, as a virus scanner does, and can drop a
196/// rename that changes only the case of a name. So after each create and
197/// rename of a file, a directory or a named stream there, the backend
198/// reads back the name the server stored. A name stored in another
199/// spelling is renamed to `~smb-<32 hex digits>` in its directory, or among
200/// the streams of its file, then to the name asked for. In between, the
201/// entry lists under the temporary name and an open of its name can miss
202/// it; if the server stops then, the entry stays under the temporary name
203/// in its directory, where nothing removes it. A case-only rename that
204/// cannot be corrected fails and leaves the name as it was. A create whose
205/// entry another program holds open without sharing delete access
206/// succeeds under the spelling the server stored, with a warning logged. A
207/// create whose name another client takes during the correction fails
208/// with STATUS_SHARING_VIOLATION, and the entry it made is deleted.
209///
210/// On Windows, where the volume of the share root refuses POSIX deletes,
211/// as an SMB share does, a delete moves the entry into the hidden directory
212/// `.smb-deleted` in the share root and marks it to be deleted when its
213/// last handle closes, so its name is free at once; the file system
214/// removes it at that close. The first delete that needs `.smb-deleted`
215/// makes it, and the backend keeps it open from then on and deletes what
216/// earlier runs left in it, except a directory that still has entries,
217/// which stays with a warning logged. If something else has that name,
218/// deleted names stay until their last handle closes. A read-only backend
219/// never makes it. On every Windows volume, clients cannot open, list or
220/// rename into `.smb-deleted` under any spelling, and cannot create its
221/// name in the share root.
222///
223/// On Windows, extended attributes are the NTFS ones, on volumes that
224/// store them; NTFS keeps the letters a-z of their names in uppercase.
225/// macOS hosts have none: every extended attribute there is a named
226/// stream.
227pub struct LocalFsBackend {
228    root: Arc<Dir>,
229    /// Device of the share root; see `file_index`.
230    root_dev: Option<u64>,
231    read_only: bool,
232    /// Case rule of name lookups in the share root.
233    case_sensitive: bool,
234    /// The share root's filesystem stores extended attributes.
235    eas: bool,
236    /// The share root's filesystem clones ranges between files.
237    block_cloning: bool,
238    /// Watches directories for changes made outside the server.
239    #[cfg(target_os = "linux")]
240    hub: Option<Arc<super::inotify::Hub>>,
241    /// The named streams open through the backend; `None` when the share
242    /// has none.
243    #[cfg(any(target_os = "linux", target_os = "macos"))]
244    streams: Option<Arc<super::open_streams::OpenStreams>>,
245    /// The named streams of the share root's volume; `None` when it has
246    /// none.
247    #[cfg(windows)]
248    volume: Option<super::windows_streams::Volume>,
249    /// Where streams too large for an extended attribute go; `None` when
250    /// the share has no named streams.
251    #[cfg(target_os = "linux")]
252    store: Option<Arc<super::streams::Store>>,
253    /// Where deleted entries go on a volume without POSIX deletes.
254    #[cfg(windows)]
255    trash: Arc<super::windows_trash::Trash>,
256    /// Runs between the lookup of a path and its open.
257    #[cfg(test)]
258    after_locate: Option<Arc<dyn Fn() + Send + Sync>>,
259}
260
261impl LocalFsBackend {
262    /// Open `path` as the share root. Errors if the path does not exist or is
263    /// not a directory.
264    pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
265        let dir = Dir::open_ambient_dir(path, ambient_authority())?;
266        let root_key = file_key(&dir.dir_metadata()?);
267        let root_dev = root_key.map(|(dev, _)| dev);
268        let case_sensitive = volume::is_case_sensitive(&dir);
269        #[cfg(windows)]
270        let dir = dir.reserve(super::windows_trash::TRASH_NAME, case_sensitive);
271        let root = Arc::new(dir);
272        #[cfg(target_os = "linux")]
273        let streams = super::streams::supported(&root).then(Arc::default);
274        #[cfg(target_os = "macos")]
275        let streams = super::macos_streams::supported(&root).then(Arc::default);
276        #[cfg(windows)]
277        let volume = super::windows_streams::volume(&root);
278        #[cfg(target_os = "linux")]
279        let eas = streams.is_some();
280        #[cfg(windows)]
281        let eas = super::windows_eas::supported(&root);
282        #[cfg(not(any(target_os = "linux", windows)))]
283        let eas = false;
284        #[cfg(target_os = "linux")]
285        let block_cloning = super::reflink::supported(&root);
286        #[cfg(windows)]
287        let block_cloning = super::windows_clone::supported(&root);
288        #[cfg(not(any(target_os = "linux", windows)))]
289        let block_cloning = false;
290        #[cfg(target_os = "linux")]
291        let store = streams
292            .is_some()
293            .then(|| Arc::new(super::streams::Store::in_share(Arc::clone(&root))));
294        Ok(Self {
295            root,
296            root_dev,
297            read_only: false,
298            case_sensitive,
299            eas,
300            block_cloning,
301            #[cfg(target_os = "linux")]
302            hub: Some(Arc::default()),
303            #[cfg(any(target_os = "linux", target_os = "macos"))]
304            streams,
305            #[cfg(windows)]
306            volume,
307            #[cfg(target_os = "linux")]
308            store,
309            #[cfg(windows)]
310            trash: Arc::new(super::windows_trash::Trash::new(root_key, case_sensitive)),
311            #[cfg(test)]
312            after_locate: None,
313        })
314    }
315
316    #[cfg(all(test, target_os = "linux"))]
317    pub(crate) fn after_locate(self, f: impl Fn() + Send + Sync + 'static) -> Self {
318        Self {
319            after_locate: Some(Arc::new(f)),
320            ..self
321        }
322    }
323
324    /// Makes the backend delete as on a volume that refuses POSIX deletes.
325    #[cfg(all(test, windows))]
326    pub(crate) fn without_posix_delete(self) -> Self {
327        self.trash.refuse_posix();
328        self
329    }
330
331    /// Makes `hook` run before each rename on a remote root, as
332    /// [`RenameHook`](super::windows_dir::RenameHook) says.
333    #[cfg(all(test, windows))]
334    pub(crate) fn before_rename(self, hook: super::windows_dir::RenameHook) -> Self {
335        self.root.volume().before_rename(hook);
336        self
337    }
338
339    /// How many names stored in another spelling the backend has corrected.
340    #[cfg(all(test, windows))]
341    pub(crate) fn corrections(&self) -> usize {
342        self.root.volume().corrections()
343    }
344
345    /// Mark the backend as read-only. All write-class opens and writes return
346    /// an access-denied SMB error.
347    #[must_use]
348    pub fn read_only(mut self) -> Self {
349        self.read_only = true;
350        self
351    }
352
353    /// Report changes made to the share's directories outside the server,
354    /// by other programs on the host or through other shares, to clients
355    /// that watch them. On Linux only, through inotify: only the entries
356    /// directly in a watched directory are seen. The parent of each watched
357    /// directory, the share root's parent included, is watched too, to see
358    /// the directory deleted. The backend holds at most 4096 kernel
359    /// watches; a directory past that, or one the kernel will not watch,
360    /// past `fs.inotify.max_user_watches` or `fs.inotify.max_user_instances`
361    /// or without `/proc`, gets only the changes made through the server,
362    /// with a warning logged once. On by default.
363    #[must_use]
364    pub fn watch_host_changes(self, enabled: bool) -> Self {
365        #[cfg(target_os = "linux")]
366        {
367            Self {
368                hub: enabled.then(Arc::default),
369                ..self
370            }
371        }
372        #[cfg(not(target_os = "linux"))]
373        {
374            let _ = enabled;
375            self
376        }
377    }
378
379    /// Keep the named streams that do not fit in an extended attribute in
380    /// the directory `path` instead of `.smb-streams` in the share root.
381    /// The directory must exist, lie outside the share, belong to the
382    /// server's user and give no access to group or others. Space taken
383    /// there does not count against the share's filesystem or its quotas
384    /// when it is on another filesystem. Backends that name the same
385    /// directory share it, and [`LocalFsBackend::sweep_streams`] on one of
386    /// them removes what none of its own files refers to, so each needs
387    /// its own directory unless their shares are swept together. Linux
388    /// only; elsewhere the directory is opened and not used.
389    pub fn stream_store(self, path: impl AsRef<Path>) -> io::Result<Self> {
390        let dir = Dir::open_ambient_dir(path, ambient_authority())?;
391        #[cfg(target_os = "linux")]
392        {
393            let store = self
394                .streams
395                .as_ref()
396                .map(|_| super::streams::Store::at(dir, &self.root).map(Arc::new))
397                .transpose()?;
398            Ok(Self { store, ..self })
399        }
400        #[cfg(not(target_os = "linux"))]
401        {
402            drop(dir);
403            Ok(self)
404        }
405    }
406
407    /// Remove what the stream store keeps for files that are gone: files
408    /// deleted, through the server or on the host, or replaced without
409    /// their extended attributes. Returns how many files' streams went.
410    ///
411    /// An entry of the store goes once two sweeps in a row found no file
412    /// referring to it and no request used it in between, so a file moved
413    /// while one sweep walked the share keeps its streams; space a deleted
414    /// file took comes back after the second sweep. The walk reads an
415    /// extended attribute of every file and directory of the share and
416    /// holds nothing; the pass over the store that follows makes stream
417    /// requests that use the store wait until it is done, a pause that
418    /// grows with the number of entries and with the size of those it
419    /// removes. Any `user.smb-server.streams` attribute keeps the entry it
420    /// names. A file or directory the walk cannot read fails the sweep
421    /// before anything is removed; a failure in the pass over the store
422    /// leaves the entries it had not reached yet. Linux only; elsewhere it
423    /// removes nothing.
424    pub async fn sweep_streams(&self) -> io::Result<usize> {
425        #[cfg(target_os = "linux")]
426        {
427            let Some(store) = self.store.clone() else {
428                return Ok(0);
429            };
430            if self.read_only {
431                return Err(io::ErrorKind::PermissionDenied.into());
432            }
433            let root = Arc::clone(&self.root);
434            spawn_blocking(move || store.sweep(&root))
435                .await
436                .map_err(join_to_io)?
437        }
438        #[cfg(not(target_os = "linux"))]
439        {
440            Ok(0)
441        }
442    }
443
444    /// True if `path` is the name the stream store takes in the share
445    /// root, or on Windows the directory deleted entries go to, which no
446    /// client may make.
447    fn reserves(&self, path: &SmbPath) -> bool {
448        #[cfg(target_os = "linux")]
449        let hidden = self.store.as_ref().and_then(|store| store.hidden_name());
450        #[cfg(windows)]
451        let hidden = Some(super::windows_trash::TRASH_NAME);
452        #[cfg(not(any(target_os = "linux", windows)))]
453        let hidden: Option<&str> = None;
454        hidden.is_some_and(
455            |hidden| matches!(path.components(), [name] if is_hidden(name, hidden, self.case_sensitive)),
456        )
457    }
458
459    /// Makes the stream store of a writable share, so it exists before a
460    /// client could take its name.
461    async fn prepare_store(&self) {
462        #[cfg(target_os = "linux")]
463        if !self.read_only
464            && let Some(store) = self.store.clone()
465            && !store.prepared()
466        {
467            let _ = spawn_blocking(move || store.prepare()).await;
468        }
469    }
470
471    /// [`LocalFsBackend::locate`], once more when a directory on the way
472    /// moved during the lookup; moved again, the path is not found.
473    async fn locate_again(&self, path: &SmbPath, follow_last: bool) -> io::Result<Located> {
474        match self.locate(path, follow_last).await {
475            Err(e) if is_changed(&e) => match self.locate(path, follow_last).await {
476                Err(e) if is_changed(&e) => Err(io::ErrorKind::NotFound.into()),
477                located => located,
478            },
479            located => located,
480        }
481    }
482
483    /// Where `path` is: a directory, open, and the path in it. With a
484    /// stream store, the path is resolved one name at a time from the share
485    /// root, each directory on the way opened from the one before, so the
486    /// result is a directory that is not the store or below it, and the
487    /// last name in it; a path that leads into the store fails with
488    /// [`in_store`]. A symlink as the last name is followed only with
489    /// `follow_last`. Without a store, it is the share root and the whole
490    /// path.
491    async fn locate(&self, path: &SmbPath, follow_last: bool) -> io::Result<Located> {
492        #[cfg(target_os = "linux")]
493        if let Some(store) = self.store.clone() {
494            let root = Arc::clone(&self.root);
495            let rel = to_rel_path(path);
496            return spawn_blocking(move || match store.key() {
497                Some(key) => resolve(&root, &rel, key, follow_last),
498                None => Ok(Located {
499                    base: root,
500                    rel,
501                    checked: false,
502                }),
503            })
504            .await
505            .map_err(join_to_io)?;
506        }
507        let _ = follow_last;
508        Ok(Located {
509            base: Arc::clone(&self.root),
510            rel: to_rel_path(path),
511            checked: false,
512        })
513    }
514}
515
516/// A path below the share root, as [`LocalFsBackend::locate`] found it.
517#[derive(Clone)]
518struct Located {
519    /// The directory the path is in.
520    base: Arc<Dir>,
521    /// The path in `base`: one name, or `.` for `base` itself, when
522    /// `checked`.
523    rel: PathBuf,
524    /// `base` was reached one name at a time, and none of it is the
525    /// stream store.
526    checked: bool,
527}
528
529impl Located {
530    /// Fails unless the object `opened` is the one the last name of a
531    /// checked path names now, without following a symlink: the name was
532    /// swapped since it was resolved.
533    #[cfg(target_os = "linux")]
534    fn verify(&self, opened: &impl std::os::fd::AsFd) -> io::Result<()> {
535        if self.checked && self.rel != Path::new(".") {
536            let named = rustix::fs::statat(
537                &*self.base,
538                &self.rel,
539                rustix::fs::AtFlags::SYMLINK_NOFOLLOW,
540            )?;
541            let opened = rustix::fs::fstat(opened)?;
542            if (named.st_dev, named.st_ino) != (opened.st_dev, opened.st_ino) {
543                return Err(changed());
544            }
545        }
546        Ok(())
547    }
548
549    #[cfg(not(target_os = "linux"))]
550    fn verify<T>(&self, _opened: &T) -> io::Result<()> {
551        Ok(())
552    }
553}
554
555/// The error for a path that leads into the stream store.
556#[cfg(target_os = "linux")]
557fn in_store() -> io::Error {
558    io::Error::new(io::ErrorKind::NotFound, InStore)
559}
560
561/// What [`special_file`] carries.
562#[cfg(any(target_os = "linux", target_os = "macos", windows))]
563#[derive(Debug)]
564struct Special;
565
566#[cfg(any(target_os = "linux", target_os = "macos", windows))]
567impl std::fmt::Display for Special {
568    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
569        f.write_str("not a regular file or directory")
570    }
571}
572
573#[cfg(any(target_os = "linux", target_os = "macos", windows))]
574impl std::error::Error for Special {}
575
576/// The error for an open of a FIFO, a socket or a device node, or on
577/// Windows of a link of a kind the share does not follow, which
578/// [`io_to_smb`] makes [`SmbError::SpecialFile`].
579#[cfg(any(target_os = "linux", target_os = "macos", windows))]
580pub(super) fn special_file() -> io::Error {
581    io::Error::other(Special)
582}
583
584/// The error for a name that changed between its lookup and its open.
585#[cfg(unix)]
586fn changed() -> io::Error {
587    io::Error::new(
588        io::ErrorKind::Interrupted,
589        "a name changed while it was looked up",
590    )
591}
592
593#[cfg(target_os = "linux")]
594#[derive(Debug)]
595struct InStore;
596
597#[cfg(target_os = "linux")]
598impl std::fmt::Display for InStore {
599    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
600        f.write_str("the path leads into the stream store")
601    }
602}
603
604#[cfg(target_os = "linux")]
605impl std::error::Error for InStore {}
606
607/// True if `e` says a path leads into the stream store.
608fn is_in_store(e: &io::Error) -> bool {
609    #[cfg(target_os = "linux")]
610    {
611        e.kind() == io::ErrorKind::NotFound
612            && e.get_ref().is_some_and(|inner| inner.is::<InStore>())
613    }
614    #[cfg(not(target_os = "linux"))]
615    {
616        let _ = e;
617        false
618    }
619}
620
621/// True if `e` says a name changed between its lookup and its open.
622fn is_changed(e: &io::Error) -> bool {
623    e.kind() == io::ErrorKind::Interrupted
624}
625
626/// Resolves `rel` below `root` one name at a time, as
627/// [`LocalFsBackend::locate`] says. Symlinks are followed as the share
628/// follows them: relative ones within the share, absolute ones not at all;
629/// with `follow_last` unset, a symlink as the last name is the result
630/// itself. Only the directory reached so far is held open; a `..` opens
631/// its parent again and checks it is the one it came through.
632#[cfg(target_os = "linux")]
633fn resolve(
634    root: &Arc<Dir>,
635    rel: &Path,
636    store: (u64, u64),
637    follow_last: bool,
638) -> io::Result<Located> {
639    use std::collections::VecDeque;
640    use std::ffi::{OsStr, OsString};
641    use std::os::unix::ffi::OsStrExt as _;
642    use std::path::Component;
643
644    use rustix::fs::{AtFlags, FileType, Mode, OFlags};
645
646    let escape = || {
647        io::Error::new(
648            io::ErrorKind::PermissionDenied,
649            "a symlink leads outside the share",
650        )
651    };
652    let key = |fd: &dyn std::os::fd::AsFd| -> io::Result<(u64, u64)> {
653        let st = rustix::fs::fstat(fd.as_fd())?;
654        Ok((st.st_dev, st.st_ino))
655    };
656    let dir_flags = OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
657    let mut top: Arc<Dir> = Arc::clone(root);
658    // The device and inode of each directory from the root to `top`.
659    let mut keys = vec![key(&**root)?];
660    let mut pending: VecDeque<OsString> = rel
661        .components()
662        .filter_map(|c| match c {
663            Component::Normal(name) => Some(name.to_os_string()),
664            _ => None,
665        })
666        .collect();
667    let mut links = 0;
668    while let Some(name) = pending.pop_front() {
669        if name == ".." {
670            if keys.len() == 1 {
671                return Err(escape());
672            }
673            #[cfg(test)]
674            if let Some(f) = lock_hook().as_ref() {
675                f();
676            }
677            let parent = rustix::fs::openat(&*top, "..", dir_flags, Mode::empty())?;
678            keys.pop();
679            if Some(&key(&parent)?) != keys.last() {
680                return Err(changed());
681            }
682            top = Arc::new(Dir::from_std_file(std::fs::File::from(parent)));
683            continue;
684        }
685        if name == "." {
686            continue;
687        }
688        let st = match rustix::fs::statat(&*top, &name, AtFlags::SYMLINK_NOFOLLOW) {
689            Ok(st) => Some(st),
690            Err(rustix::io::Errno::NOENT) => None,
691            Err(e) => return Err(e.into()),
692        };
693        let is_link = st
694            .as_ref()
695            .is_some_and(|st| FileType::from_raw_mode(st.st_mode) == FileType::Symlink);
696        match st {
697            Some(_) if is_link && (follow_last || !pending.is_empty()) => {
698                links += 1;
699                if links > 40 {
700                    return Err(rustix::io::Errno::LOOP.into());
701                }
702                let target = rustix::fs::readlinkat(&*top, &name, Vec::new())?;
703                let target = Path::new(OsStr::from_bytes(target.as_bytes()));
704                for c in target.components().rev() {
705                    match c {
706                        Component::Normal(n) => pending.push_front(n.to_os_string()),
707                        Component::ParentDir => pending.push_front("..".into()),
708                        Component::CurDir => {}
709                        Component::RootDir | Component::Prefix(_) => return Err(escape()),
710                    }
711                }
712            }
713            Some(st) if (st.st_dev, st.st_ino) == store => return Err(in_store()),
714            _ if pending.is_empty() => {
715                return Ok(Located {
716                    base: top,
717                    rel: PathBuf::from(name),
718                    checked: true,
719                });
720            }
721            None => return Err(io::ErrorKind::NotFound.into()),
722            Some(_) => {
723                let fd = rustix::fs::openat(&*top, &name, dir_flags, Mode::empty())?;
724                let at = key(&fd)?;
725                if at == store {
726                    return Err(in_store());
727                }
728                keys.push(at);
729                top = Arc::new(Dir::from_std_file(std::fs::File::from(fd)));
730            }
731        }
732    }
733    Ok(Located {
734        base: top,
735        rel: PathBuf::from("."),
736        checked: true,
737    })
738}
739
740/// Runs in [`resolve`] before it goes up a directory.
741#[cfg(all(test, target_os = "linux"))]
742pub(crate) static BEFORE_PARENT: std::sync::Mutex<Option<Box<dyn Fn() + Send>>> =
743    std::sync::Mutex::new(None);
744
745#[cfg(all(test, target_os = "linux"))]
746fn lock_hook() -> std::sync::MutexGuard<'static, Option<Box<dyn Fn() + Send>>> {
747    BEFORE_PARENT
748        .lock()
749        .unwrap_or_else(std::sync::PoisonError::into_inner)
750}
751
752/// True if `name` is `hidden` under the case rule `case_sensitive`.
753pub(super) fn is_hidden(name: &str, hidden: &str, case_sensitive: bool) -> bool {
754    name == hidden || (!case_sensitive && name.to_lowercase() == hidden.to_lowercase())
755}
756
757// ---------------------------------------------------------------------------
758// Path translation
759// ---------------------------------------------------------------------------
760
761/// Convert a validated `SmbPath` into a relative `PathBuf` suitable for
762/// `Dir` lookups.
763///
764/// `SmbPath` is already validated (no `..`, no forbidden chars, no doubled
765/// separators), so this is purely a join. The empty `SmbPath` (root) yields
766/// `PathBuf::from(".")`, which a `Dir` accepts for `metadata` etc.
767pub(super) fn to_rel_path(path: &SmbPath) -> PathBuf {
768    if path.is_root() {
769        return PathBuf::from(".");
770    }
771    let mut out = PathBuf::new();
772    for c in path.components() {
773        out.push(c);
774    }
775    out
776}
777
778// ---------------------------------------------------------------------------
779// Error mapping
780// ---------------------------------------------------------------------------
781
782pub(super) fn io_to_smb(err: io::Error) -> SmbError {
783    use io::ErrorKind::*;
784    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
785    if err.get_ref().is_some_and(|inner| inner.is::<Special>()) {
786        return SmbError::SpecialFile;
787    }
788    #[cfg(windows)]
789    if err.raw_os_error() == Some(super::windows_dir::ERROR_SHARING_VIOLATION)
790        || super::windows_dir::collided(&err).is_some()
791    {
792        return SmbError::Sharing;
793    }
794    match err.kind() {
795        NotFound => SmbError::NotFound,
796        PermissionDenied => SmbError::AccessDenied,
797        AlreadyExists => SmbError::Exists,
798        DirectoryNotEmpty => SmbError::NotEmpty,
799        IsADirectory => SmbError::IsDirectory,
800        NotADirectory => SmbError::NotADirectory,
801        InvalidInput | InvalidFilename => SmbError::NameInvalid,
802        CrossesDevices => SmbError::NotSameDevice,
803        StorageFull => SmbError::DiskFull,
804        QuotaExceeded => SmbError::QuotaExceeded,
805        _ => SmbError::Io(err),
806    }
807}
808
809/// Convert a `spawn_blocking` join error (panic or cancellation) into
810/// `io::ErrorKind::Other`.
811pub(super) fn join_to_io(_e: tokio::task::JoinError) -> io::Error {
812    io::Error::other("blocking task panicked or was cancelled")
813}
814
815// ---------------------------------------------------------------------------
816// Host-specific file access
817// ---------------------------------------------------------------------------
818
819// On Windows these also move the file cursor, which nothing here reads.
820
821fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
822    #[cfg(unix)]
823    {
824        std::os::unix::fs::FileExt::read_at(file, buf, offset)
825    }
826    #[cfg(windows)]
827    {
828        std::os::windows::fs::FileExt::seek_read(file, buf, offset)
829    }
830}
831
832fn write_at(file: &std::fs::File, data: &[u8], offset: u64) -> io::Result<usize> {
833    #[cfg(unix)]
834    {
835        std::os::unix::fs::FileExt::write_at(file, data, offset)
836    }
837    #[cfg(windows)]
838    {
839        std::os::windows::fs::FileExt::seek_write(file, data, offset)
840    }
841}
842
843/// `handle` as a handle of this backend, `None` for any other.
844#[cfg(any(target_os = "linux", windows))]
845fn local_handle(handle: &dyn Handle) -> Option<&LocalHandle> {
846    handle.as_any()?.downcast_ref()
847}
848
849/// The files behind the handles of a copy or a clone, the source first. A
850/// directory, or a destination another backend gave, is not supported; a
851/// source no `LocalFsBackend` gave is on another device; a destination of a
852/// read-only backend is refused.
853#[cfg(any(target_os = "linux", windows))]
854fn local_files(
855    src: &dyn Handle,
856    dst: &dyn Handle,
857) -> SmbResult<(Arc<std::fs::File>, Arc<std::fs::File>)> {
858    let Some(LocalHandle::File {
859        file: dst,
860        read_only,
861        ..
862    }) = local_handle(dst)
863    else {
864        return Err(SmbError::NotSupported);
865    };
866    let src = match local_handle(src) {
867        Some(LocalHandle::File { file, .. }) => file,
868        Some(LocalHandle::Dir { .. }) => return Err(SmbError::NotSupported),
869        None => return Err(SmbError::NotSameDevice),
870    };
871    if *read_only {
872        return Err(SmbError::AccessDenied);
873    }
874    Ok((Arc::clone(src), Arc::clone(dst)))
875}
876
877/// Copies `len` bytes at `src_offset` of `src` to `dst_offset` of `dst` with
878/// copy_file_range(2) until they are copied or `src` ends. Returns the
879/// bytes copied and the error that ended the copy early, if any.
880///
881/// Overlapping ranges of one file fail with EINVAL before anything is
882/// copied. The kernel checks the overlap after it cuts the range at the end
883/// of `src`, so a range cut short can pass its check.
884#[cfg(target_os = "linux")]
885fn copy_file_range_loop(
886    src: &std::fs::File,
887    mut src_offset: u64,
888    dst: &std::fs::File,
889    mut dst_offset: u64,
890    len: u64,
891) -> (u64, Option<rustix::io::Errno>) {
892    use rustix::io::Errno;
893
894    let overlap =
895        src_offset.saturating_add(len) > dst_offset && dst_offset.saturating_add(len) > src_offset;
896    // If the files cannot be compared, they count as the same file.
897    if overlap && same_file(src, dst).unwrap_or(true) {
898        return (0, Some(Errno::INVAL));
899    }
900    let mut copied = 0;
901    while copied < len {
902        let want = usize::try_from(len - copied).unwrap_or(usize::MAX);
903        match rustix::fs::copy_file_range(
904            src,
905            Some(&mut src_offset),
906            dst,
907            Some(&mut dst_offset),
908            want,
909        ) {
910            Ok(0) => break,
911            Ok(n) => copied += n as u64,
912            Err(Errno::INTR) => {}
913            Err(errno) => return (copied, Some(errno)),
914        }
915    }
916    (copied, None)
917}
918
919/// True if `a` and `b` are open on one file.
920#[cfg(target_os = "linux")]
921fn same_file(a: &std::fs::File, b: &std::fs::File) -> io::Result<bool> {
922    let key = |file| Metadata::from_file(file).map(|md| file_key(&md));
923    Ok(key(a)? == key(b)?)
924}
925
926/// The error of a copy_file_range(2) call that copied nothing. A copy the
927/// kernel cannot make between these files is left to reads and writes.
928#[cfg(target_os = "linux")]
929fn copy_error(errno: rustix::io::Errno) -> SmbError {
930    use rustix::io::Errno;
931    match errno {
932        Errno::XDEV
933        | Errno::OPNOTSUPP
934        | Errno::NOSYS
935        | Errno::INVAL
936        | Errno::PERM
937        | Errno::BADF => SmbError::NotSupported,
938        errno => io_to_smb(errno.into()),
939    }
940}
941
942/// The error of a FICLONERANGE call: EINVAL for ranges the filesystem
943/// refuses, EOPNOTSUPP for a filesystem that cannot clone. Other errors,
944/// EXDEV for files on two filesystems included, go through `io_to_smb`.
945#[cfg(target_os = "linux")]
946fn clone_error(errno: rustix::io::Errno) -> SmbError {
947    use rustix::io::Errno;
948    match errno {
949        Errno::INVAL => SmbError::InvalidParameter,
950        Errno::OPNOTSUPP => SmbError::NotSupported,
951        errno => io_to_smb(errno.into()),
952    }
953}
954
955/// Host identity of a file: device and inode number on Unix, volume serial
956/// number and file index on Windows. `None` if `md` does not carry it.
957pub(super) fn file_key(md: &Metadata) -> Option<(u64, u64)> {
958    #[cfg(unix)]
959    {
960        use cap_std::fs::MetadataExt as _;
961        Some((md.dev(), md.ino()))
962    }
963    #[cfg(windows)]
964    {
965        Some((md.volume_serial_number()?.into(), md.file_index()?))
966    }
967}
968
969/// File id for a file with host identity `key`. Files on the share root's
970/// device report the inode (file index on Windows). Files on other mounts
971/// below the root have their device mixed into the id, so equal inodes on
972/// different devices give different ids.
973pub(super) fn file_index(root_dev: Option<u64>, key: Option<(u64, u64)>) -> u64 {
974    let Some((dev, ino)) = key else {
975        return 0;
976    };
977    if root_dev.is_none_or(|root| root == dev) {
978        return ino;
979    }
980    // splitmix64 finalizer: spreads the device over all 64 bits.
981    let mut x = dev;
982    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
983    x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
984    ino ^ x ^ (x >> 31)
985}
986
987/// Number of hard links to a file. `None` if `md` does not carry it.
988pub(super) fn link_count(md: &Metadata) -> Option<u64> {
989    #[cfg(unix)]
990    {
991        use cap_std::fs::MetadataExt as _;
992        Some(md.nlink())
993    }
994    #[cfg(windows)]
995    {
996        md.number_of_links().map(u64::from)
997    }
998}
999
1000/// Whether an entry, given its metadata read without following a final
1001/// symlink, is a directory to the host and is deleted with `remove_dir`. On
1002/// Unix that holds for directories only; a symlink to a directory is a plain
1003/// link. On Windows it holds for anything with the directory attribute,
1004/// which includes directory symlinks and junctions.
1005fn is_dir_entry(md: &Metadata) -> bool {
1006    #[cfg(unix)]
1007    {
1008        md.is_dir()
1009    }
1010    #[cfg(windows)]
1011    {
1012        const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
1013        md.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0
1014    }
1015}
1016
1017/// Metadata for a directory listing entry, carrying the host file id. On
1018/// Windows, `DirEntry::metadata` comes from the directory scan and has no
1019/// file index, so the entry is opened for it, falling back to the scan data
1020/// when the open fails.
1021#[cfg_attr(unix, expect(unused_variables, reason = "dir is used on Windows only"))]
1022fn entry_metadata(dir: &Dir, entry: &super::dir::DirEntry) -> io::Result<Metadata> {
1023    #[cfg(unix)]
1024    {
1025        entry.metadata()
1026    }
1027    #[cfg(windows)]
1028    {
1029        dir.symlink_metadata(entry.file_name())
1030            .or_else(|_| entry.metadata())
1031    }
1032}
1033
1034/// Opens the directory `rel` below `root`. On Windows the handle shares
1035/// delete access and has `FILE_WRITE_ATTRIBUTES` when `write_attributes` is
1036/// set.
1037#[cfg_attr(
1038    unix,
1039    expect(unused_variables, reason = "write_attributes is used on Windows only")
1040)]
1041fn open_dir_handle(root: &Dir, rel: &Path, write_attributes: bool) -> io::Result<Dir> {
1042    #[cfg(unix)]
1043    {
1044        root.open_dir(rel)
1045    }
1046    #[cfg(windows)]
1047    {
1048        const GENERIC_READ: u32 = 0x8000_0000;
1049        const FILE_WRITE_ATTRIBUTES: u32 = 0x0000_0100;
1050        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
1051
1052        let mut opts = DirOpenOptions::new();
1053        opts.read(true).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
1054        if write_attributes {
1055            opts.access_mode(GENERIC_READ | FILE_WRITE_ATTRIBUTES);
1056        }
1057        root.open_dir(rel, &opts)
1058    }
1059}
1060
1061/// A `File` on the same open directory, for setting its times. On Linux a
1062/// `Dir` holds an `O_PATH` descriptor, which cannot change times, so the
1063/// directory is opened again through it.
1064pub(super) fn dir_as_file(dir: &Dir) -> io::Result<std::fs::File> {
1065    #[cfg(unix)]
1066    {
1067        Ok(dir.open(".")?.into_std())
1068    }
1069    #[cfg(windows)]
1070    {
1071        use std::os::windows::io::AsHandle as _;
1072        Ok(dir.as_handle().try_clone_to_owned()?.into())
1073    }
1074}
1075
1076/// Sets or clears the read-only state of an open file: a read-only file has
1077/// no write permission bits, and clearing it gives the owner write
1078/// permission back. A file already in that state is left alone, so a file
1079/// the server can write but does not own takes the other attributes.
1080#[cfg(unix)]
1081fn set_read_only(file: &std::fs::File, read_only: bool) -> io::Result<()> {
1082    use std::os::unix::fs::PermissionsExt as _;
1083    let mut perms = file.metadata()?.permissions();
1084    let mode = perms.mode();
1085    let wanted = if read_only {
1086        mode & !0o222
1087    } else {
1088        mode | 0o200
1089    };
1090    if wanted == mode {
1091        return Ok(());
1092    }
1093    perms.set_mode(wanted);
1094    file.set_permissions(perms)
1095}
1096
1097/// Gives the file or directory `file` is open on the attributes
1098/// `attributes` (MS-FSCC 2.6). Windows stores them as the host's
1099/// attributes; a handle opened without FILE_WRITE_ATTRIBUTES sets them
1100/// through a second handle that has only that access. Other hosts store
1101/// READONLY on a file and ignore the rest.
1102#[cfg_attr(
1103    windows,
1104    expect(unused_variables, reason = "is_dir is used on Unix only")
1105)]
1106pub(super) fn set_host_attributes(
1107    file: &std::fs::File,
1108    attributes: u32,
1109    is_dir: bool,
1110) -> io::Result<()> {
1111    #[cfg(unix)]
1112    {
1113        if is_dir {
1114            return Ok(());
1115        }
1116        set_read_only(
1117            file,
1118            attributes & crate::backend::FILE_ATTRIBUTE_READONLY != 0,
1119        )
1120    }
1121    #[cfg(windows)]
1122    {
1123        use std::os::windows::io::AsRawHandle as _;
1124        use windows_sys::Win32::Foundation::HANDLE;
1125        use windows_sys::Win32::Storage::FileSystem::{
1126            FILE_ATTRIBUTE_NORMAL, FILE_BASIC_INFO, FILE_WRITE_ATTRIBUTES, FileBasicInfo,
1127            SetFileInformationByHandle,
1128        };
1129        // 0 leaves a time unchanged, and attributes of 0 would too, so no
1130        // attributes are sent as FILE_ATTRIBUTE_NORMAL.
1131        let info = FILE_BASIC_INFO {
1132            CreationTime: 0,
1133            LastAccessTime: 0,
1134            LastWriteTime: 0,
1135            ChangeTime: 0,
1136            FileAttributes: if attributes == 0 {
1137                FILE_ATTRIBUTE_NORMAL
1138            } else {
1139                attributes
1140            },
1141        };
1142        let set = |file: &std::fs::File| {
1143            // SAFETY: `info` is a live local of the size passed, and the
1144            // handle stays open for the call.
1145            let ok = unsafe {
1146                SetFileInformationByHandle(
1147                    file.as_raw_handle() as HANDLE,
1148                    FileBasicInfo,
1149                    (&raw const info).cast(),
1150                    std::mem::size_of::<FILE_BASIC_INFO>() as u32,
1151                )
1152            };
1153            if ok == 0 {
1154                Err(io::Error::last_os_error())
1155            } else {
1156                Ok(())
1157            }
1158        };
1159        match set(file) {
1160            Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
1161                set(&super::windows_dir::reopen(file, FILE_WRITE_ATTRIBUTES)?)
1162            }
1163            result => result,
1164        }
1165    }
1166}
1167
1168/// Host times for `times`. The change time is left to the host. Hosts other
1169/// than Windows and macOS have no call that sets the creation time, so it is
1170/// ignored there, as is a time the host's clock cannot hold.
1171pub(super) fn host_file_times(times: FileTimes) -> std::fs::FileTimes {
1172    let host_time = |ft: Option<u64>| ft.and_then(filetime_to_system_time);
1173    let mut out = std::fs::FileTimes::new();
1174    if let Some(t) = host_time(times.last_write_time) {
1175        out = out.set_modified(t);
1176    }
1177    if let Some(t) = host_time(times.last_access_time) {
1178        out = out.set_accessed(t);
1179    }
1180    #[cfg(any(windows, target_os = "macos"))]
1181    if let Some(t) = host_time(times.creation_time) {
1182        out = set_created(out, t);
1183    }
1184    out
1185}
1186
1187#[cfg(windows)]
1188fn set_created(times: std::fs::FileTimes, t: SystemTime) -> std::fs::FileTimes {
1189    use std::os::windows::fs::FileTimesExt as _;
1190    times.set_created(t)
1191}
1192
1193#[cfg(target_os = "macos")]
1194fn set_created(times: std::fs::FileTimes, t: SystemTime) -> std::fs::FileTimes {
1195    use std::os::macos::fs::FileTimesExt as _;
1196    times.set_created(t)
1197}
1198
1199// ---------------------------------------------------------------------------
1200// FILETIME conversion
1201// ---------------------------------------------------------------------------
1202
1203/// The host time of the FILETIME `ft`, before 1970 too; `None` where the
1204/// host's clock cannot hold it.
1205pub(super) fn filetime_to_system_time(ft: u64) -> Option<SystemTime> {
1206    let ticks = |n: u64| Duration::new(n / 10_000_000, (n % 10_000_000) as u32 * 100);
1207    match ft.checked_sub(FILETIME_OFFSET) {
1208        Some(after) => UNIX_EPOCH.checked_add(ticks(after)),
1209        None => UNIX_EPOCH.checked_sub(ticks(FILETIME_OFFSET - ft)),
1210    }
1211}
1212
1213// ---------------------------------------------------------------------------
1214// FileInfo construction
1215// ---------------------------------------------------------------------------
1216
1217pub(super) fn file_info_from_metadata(
1218    name: String,
1219    md: &Metadata,
1220    root_dev: Option<u64>,
1221) -> FileInfo {
1222    // Unix hosts report the size of a directory's index; clients expect 0.
1223    let len = if md.is_dir() { 0 } else { md.len() };
1224    let modified = md.modified().ok().map(|t| t.into_std());
1225    let accessed = md.accessed().ok().map(|t| t.into_std());
1226    let created = md.created().ok().map(|t| t.into_std());
1227
1228    // A missing timestamp falls back to another available one, then to the
1229    // UNIX epoch.
1230    let modified = modified
1231        .or(created)
1232        .or(accessed)
1233        .unwrap_or(SystemTime::UNIX_EPOCH);
1234    let accessed = accessed.unwrap_or(modified);
1235    let created = created.unwrap_or(modified);
1236
1237    FileInfo {
1238        name,
1239        end_of_file: len,
1240        allocation_size: len,
1241        creation_time: system_time_to_filetime(created),
1242        last_access_time: system_time_to_filetime(accessed),
1243        last_write_time: system_time_to_filetime(modified),
1244        change_time: system_time_to_filetime(modified),
1245        is_directory: md.is_dir(),
1246        // On Unix a directory reports no READONLY.
1247        read_only: (cfg!(windows) || !md.is_dir()) && md.permissions().readonly(),
1248        file_index: file_index(root_dev, file_key(md)),
1249        unix_mode: unix_mode(md),
1250        ea_size: 0,
1251        file_attributes: host_attributes(md),
1252    }
1253}
1254
1255/// The attributes the host stores for the file of `md`: those of Windows,
1256/// none elsewhere.
1257fn host_attributes(md: &Metadata) -> u32 {
1258    #[cfg(unix)]
1259    {
1260        let _ = md;
1261        0
1262    }
1263    #[cfg(windows)]
1264    {
1265        md.file_attributes()
1266    }
1267}
1268
1269/// The POSIX mode of `md`, on hosts that have one.
1270fn unix_mode(md: &Metadata) -> Option<u32> {
1271    #[cfg(unix)]
1272    {
1273        use cap_std::fs::MetadataExt as _;
1274        Some(md.mode())
1275    }
1276    #[cfg(not(unix))]
1277    {
1278        let _ = md;
1279        None
1280    }
1281}
1282
1283// ---------------------------------------------------------------------------
1284// Directory listing
1285// ---------------------------------------------------------------------------
1286
1287/// Entries of `dir` whose names match `pattern`, every entry for `None`.
1288/// Names a client could not open again are left out, entries that resolve
1289/// to the object with the host identity `hidden`, and the name of
1290/// `hidden_name` under its case rule. With `eas`, each entry carries the
1291/// size of its extended attributes. On Windows, `dir` is held for the whole
1292/// listing, and every entry is looked up from that hold.
1293#[cfg_attr(
1294    not(any(target_os = "linux", windows)),
1295    expect(
1296        unused_variables,
1297        reason = "only Linux and Windows list extended attributes"
1298    )
1299)]
1300fn list_entries(
1301    dir: &Dir,
1302    pattern: Option<&str>,
1303    root_dev: Option<u64>,
1304    hidden: Option<(u64, u64)>,
1305    hidden_name: Option<(&str, bool)>,
1306    eas: bool,
1307) -> io::Result<Vec<SmbDirEntry>> {
1308    #[cfg(windows)]
1309    let held = dir.pin()?;
1310    #[cfg(windows)]
1311    let dir = &held;
1312    let pattern = pattern.filter(|p| !matches!(*p, "" | "*" | "*.*"));
1313    #[cfg(windows)]
1314    let ea_sizes = if eas {
1315        super::windows_eas::listing_sizes(dir, pattern).unwrap_or_else(|e| {
1316            debug!(error = %e, "extended attribute sizes not listed");
1317            Default::default()
1318        })
1319    } else {
1320        Default::default()
1321    };
1322    let pattern = pattern.map(|p| Pattern::new(p, !volume::is_case_sensitive(dir)));
1323    let mut out = Vec::new();
1324    for entry in dir.entries()? {
1325        let entry = entry?;
1326        let os_name = entry.file_name();
1327        if os_name == "." || os_name == ".." {
1328            continue;
1329        }
1330        let Some(name) = os_name.to_str().filter(|n| is_valid_component(n)) else {
1331            debug!(name = ?os_name, "listing leaves out a name clients cannot open");
1332            continue;
1333        };
1334        if pattern.as_ref().is_some_and(|p| !p.matches(name))
1335            || hidden_name
1336                .is_some_and(|(hidden, case_sensitive)| is_hidden(name, hidden, case_sensitive))
1337        {
1338            continue;
1339        }
1340        let md = match listed_metadata(dir, &entry) {
1341            Ok(md) => md,
1342            // Removed since the directory was read.
1343            Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
1344            Err(e) => return Err(e),
1345        };
1346        if hidden.is_some() && file_key(&md) == hidden {
1347            continue;
1348        }
1349        #[cfg_attr(
1350            not(any(target_os = "linux", windows)),
1351            expect(unused_mut, reason = "only Linux and Windows list extended attributes")
1352        )]
1353        let mut info = file_info_from_metadata(name.to_owned(), &md, root_dev);
1354        #[cfg(target_os = "linux")]
1355        if eas {
1356            info.ea_size = listed_ea_size(dir, &entry, name, &md);
1357        }
1358        #[cfg(windows)]
1359        if eas {
1360            info.ea_size = match ea_sizes.get(name) {
1361                Some(Some(size)) => *size,
1362                Some(None) => super::windows_eas::entry_size(dir, name).unwrap_or_else(|e| {
1363                    debug!(error = %e, name, "extended attribute size not read");
1364                    0
1365                }),
1366                None => 0,
1367            };
1368        }
1369        out.push(SmbDirEntry { info });
1370    }
1371    Ok(out)
1372}
1373
1374/// [`FileInfo::ea_size`] of a listed entry with metadata `md`, as an open
1375/// of its name sees it; 0 when it cannot be read.
1376#[cfg(target_os = "linux")]
1377fn listed_ea_size(dir: &Dir, entry: &super::dir::DirEntry, name: &str, md: &Metadata) -> u32 {
1378    use super::eas::{Source, size};
1379    if !md.is_file() && !md.is_dir() {
1380        return 0;
1381    }
1382    let sized = if entry.file_type().is_ok_and(|ty| ty.is_symlink()) {
1383        // The target, opened without reading it, inside the share.
1384        use cap_std::fs::OpenOptionsExt as _;
1385        let mut opts = DirOpenOptions::new();
1386        opts.read(true).custom_flags(libc::O_PATH);
1387        dir.open_with(name, &opts).and_then(|target| {
1388            let md = target.metadata()?;
1389            if md.is_file() || md.is_dir() {
1390                size(&Source::fd(&target))
1391            } else {
1392                Ok(0)
1393            }
1394        })
1395    } else {
1396        size(&Source::entry(dir, name))
1397    };
1398    sized.unwrap_or_else(|e| {
1399        debug!(error = %e, name, "extended attribute size not read");
1400        0
1401    })
1402}
1403
1404/// Metadata of a listed entry as an open of its name sees it: a symlink
1405/// reports its target, or itself when the target cannot be reached inside
1406/// the share.
1407fn listed_metadata(dir: &Dir, entry: &super::dir::DirEntry) -> io::Result<Metadata> {
1408    if entry.file_type()?.is_symlink()
1409        && let Ok(md) = dir.metadata(entry.file_name())
1410    {
1411        return Ok(md);
1412    }
1413    entry_metadata(dir, entry)
1414}
1415
1416/// [`FileInfo::ea_size`] of the file `file` is open on, 0 when it cannot
1417/// be read: a stat does not fail on it.
1418fn host_ea_size(file: &std::fs::File) -> u32 {
1419    #[cfg(target_os = "linux")]
1420    let size = super::eas::size(&super::eas::Source::File(file));
1421    #[cfg(windows)]
1422    let size = super::windows_eas::size(file);
1423    #[cfg(not(any(target_os = "linux", windows)))]
1424    let size: io::Result<u32> = {
1425        let _ = file;
1426        Ok(0)
1427    };
1428    best_effort(size)
1429}
1430
1431/// [`FileInfo::ea_size`] of the directory `dir` is open on, 0 when it
1432/// cannot be read. On Linux it is read through the descriptor's path, so a
1433/// directory the server may only traverse costs no open.
1434fn dir_ea_size(dir: &Dir) -> u32 {
1435    #[cfg(target_os = "linux")]
1436    let size = super::eas::size(&super::eas::Source::fd(dir));
1437    #[cfg(windows)]
1438    let size = dir_as_file(dir).and_then(|file| super::windows_eas::size(&file));
1439    #[cfg(not(any(target_os = "linux", windows)))]
1440    let size: io::Result<u32> = {
1441        let _ = dir;
1442        Ok(0)
1443    };
1444    best_effort(size)
1445}
1446
1447fn best_effort(size: io::Result<u32>) -> u32 {
1448    size.unwrap_or_else(|e| {
1449        debug!(error = %e, "extended attribute size not read");
1450        0
1451    })
1452}
1453
1454/// The extended attributes of the file or directory `file` is open on.
1455fn host_eas(file: &std::fs::File) -> io::Result<Vec<crate::Ea>> {
1456    #[cfg(target_os = "linux")]
1457    {
1458        super::eas::list(file)
1459    }
1460    #[cfg(windows)]
1461    {
1462        super::windows_eas::list(file)
1463    }
1464    #[cfg(not(any(target_os = "linux", windows)))]
1465    {
1466        let _ = file;
1467        Ok(Vec::new())
1468    }
1469}
1470
1471/// Changes the extended attributes of the file or directory `file` is open
1472/// on, as [`Handle::set_eas`] does. On Linux, the lock of the file among
1473/// `open` is held throughout, as for every change of its named streams.
1474#[cfg_attr(
1475    not(target_os = "linux"),
1476    expect(unused_variables, reason = "only Linux shares a lock with the streams")
1477)]
1478fn host_set_eas(
1479    file: &std::fs::File,
1480    eas: &[crate::Ea],
1481    open: Option<&Arc<OpenStreamsOf>>,
1482) -> SmbResult<()> {
1483    #[cfg(target_os = "linux")]
1484    {
1485        let entry = match open {
1486            Some(open) => {
1487                let md = Metadata::from_file(file).map_err(io_to_smb)?;
1488                let key = file_key(&md).ok_or(SmbError::NotSupported)?;
1489                Some(open.file(key))
1490            }
1491            None => None,
1492        };
1493        let _locked = entry
1494            .as_ref()
1495            .map(|entry| super::open_streams::lock(&entry.open));
1496        super::eas::set(file, eas)
1497    }
1498    #[cfg(windows)]
1499    {
1500        super::windows_eas::set(file, eas)
1501    }
1502    #[cfg(not(any(target_os = "linux", windows)))]
1503    {
1504        let _ = (file, eas);
1505        Err(SmbError::NotSupported)
1506    }
1507}
1508
1509/// The named streams open through a backend, whose per-file lock changes of
1510/// extended attributes take on Linux.
1511#[cfg(target_os = "linux")]
1512type OpenStreamsOf = super::open_streams::OpenStreams;
1513#[cfg(not(target_os = "linux"))]
1514type OpenStreamsOf = ();
1515
1516/// What the extended attribute calls of a handle work on.
1517enum EaTarget {
1518    File(Arc<std::fs::File>),
1519    Dir(Arc<Dir>),
1520}
1521
1522impl EaTarget {
1523    /// A file handle on it; a directory is opened again for one.
1524    fn file(&self) -> io::Result<Arc<std::fs::File>> {
1525        match self {
1526            EaTarget::File(file) => Ok(Arc::clone(file)),
1527            EaTarget::Dir(dir) => dir_as_file(dir).map(Arc::new),
1528        }
1529    }
1530}
1531
1532/// True if `dir` has no entries besides `.` and `..`.
1533fn dir_is_empty(dir: &Dir) -> io::Result<bool> {
1534    for entry in dir.entries()? {
1535        let name = entry?.file_name();
1536        if name != "." && name != ".." {
1537            return Ok(false);
1538        }
1539    }
1540    Ok(true)
1541}
1542
1543// ---------------------------------------------------------------------------
1544// ShareBackend impl
1545// ---------------------------------------------------------------------------
1546
1547impl LocalFsBackend {
1548    /// True if a directory on the way to `path` is missing or is not a
1549    /// directory.
1550    async fn parent_missing(&self, path: &SmbPath) -> bool {
1551        let Some(parent) = path.parent().filter(|p| !p.is_root()) else {
1552            return false;
1553        };
1554        let rel = to_rel_path(&parent);
1555        let root = Arc::clone(&self.root);
1556        spawn_blocking(move || !root.metadata(&rel).is_ok_and(|md| md.is_dir()))
1557            .await
1558            .unwrap_or(false)
1559    }
1560
1561    /// `made`, the result of a create at `at`. A create whose name another
1562    /// entry took while the name was corrected left the entry it made
1563    /// under a temporary name, which is deleted here, a directory with
1564    /// `is_dir`.
1565    #[cfg(windows)]
1566    async fn discard_collided<T>(
1567        &self,
1568        at: &Located,
1569        is_dir: bool,
1570        made: io::Result<T>,
1571    ) -> io::Result<T> {
1572        use std::os::windows::ffi::OsStringExt as _;
1573
1574        let Err(e) = made else {
1575            return made;
1576        };
1577        let Some(left) = super::windows_dir::collided(&e) else {
1578            return Err(e);
1579        };
1580        let name = std::ffi::OsString::from_wide(&left.aside);
1581        let rel = at.rel.parent().unwrap_or(Path::new("")).join(name);
1582        let shown = rel.display().to_string();
1583        let (trash, root) = (Arc::clone(&self.trash), Arc::clone(&at.base));
1584        let removed = spawn_blocking(move || trash.remove(&root, &rel, is_dir))
1585            .await
1586            .map_err(join_to_io)
1587            .and_then(|removed| removed);
1588        if let Err(removed) = removed {
1589            tracing::warn!(name = %shown, error = %removed, "a new entry was left under a temporary name");
1590        }
1591        Err(e)
1592    }
1593
1594    async fn open_entry(
1595        &self,
1596        path: &SmbPath,
1597        located: Located,
1598        opts: OpenOptions,
1599    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
1600        // 1. Read-only check: any open that requests creation, write access,
1601        //    truncation, or overwrite is rejected up front. Pure read opens
1602        //    pass through.
1603        if self.read_only && writes(&opts) {
1604            return Err(SmbError::AccessDenied);
1605        }
1606
1607        let root = Arc::clone(&located.base);
1608        let rel = located.rel.clone();
1609        let read_only = self.read_only;
1610        let directory = opts.directory;
1611        let non_directory = opts.non_directory;
1612        let write_attributes = opts.write_attributes;
1613
1614        let existing = {
1615            let root = Arc::clone(&root);
1616            let rel = rel.clone();
1617            spawn_blocking(move || -> io::Result<Option<super::dir::FileType>> {
1618                match root.metadata(&rel) {
1619                    Ok(md) => Ok(Some(md.file_type())),
1620                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
1621                    Err(e) => Err(e),
1622                }
1623            })
1624            .await
1625            .map_err(join_to_io)
1626            .map_err(io_to_smb)?
1627            .map_err(io_to_smb)?
1628        };
1629        if existing.is_some_and(|ty| is_special(&ty)) {
1630            return Err(SmbError::SpecialFile);
1631        }
1632
1633        if directory {
1634            // Directory CREATE intents: Create / OpenOrCreate / OverwriteOrCreate
1635            // imply mkdir; Open / Truncate require existing.
1636            let intent = opts.intent;
1637            let at = located.clone();
1638            let made = spawn_blocking(move || -> io::Result<(Dir, OpenAction)> {
1639                let action = match intent {
1640                    OpenIntent::Open => OpenAction::Opened,
1641                    OpenIntent::Create => {
1642                        root.create_dir(&rel)?;
1643                        OpenAction::Created
1644                    }
1645                    OpenIntent::OpenOrCreate => match root.create_dir(&rel) {
1646                        Ok(()) => OpenAction::Created,
1647                        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => OpenAction::Opened,
1648                        Err(e) => return Err(e),
1649                    },
1650                    OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
1651                        // Truncating a directory has no meaning; reject.
1652                        return Err(io::Error::from(io::ErrorKind::InvalidInput));
1653                    }
1654                };
1655                let dir = open_dir_handle(&root, &rel, write_attributes)?;
1656                at.verify(&dir)?;
1657                Ok((dir, action))
1658            })
1659            .await
1660            .map_err(join_to_io)
1661            .map_err(io_to_smb)?;
1662            #[cfg(windows)]
1663            let made = self.discard_collided(&located, true, made).await;
1664            let (dir_handle, action) = made.map_err(io_to_smb)?;
1665
1666            let handle: Box<dyn Handle> = Box::new(LocalHandle::Dir {
1667                name: file_name_for(path),
1668                root_dev: self.root_dev,
1669                dir_handle: Arc::new(dir_handle),
1670                read_only,
1671                eas: self.eas,
1672                #[cfg(target_os = "linux")]
1673                open: self.streams.clone(),
1674                #[cfg(target_os = "linux")]
1675                hub: self.hub.clone(),
1676                #[cfg(target_os = "linux")]
1677                store: self.store.clone(),
1678                #[cfg(windows)]
1679                trash: Arc::clone(&self.trash),
1680            });
1681            return Ok((handle, action));
1682        }
1683
1684        if existing.is_some_and(|ty| ty.is_dir()) {
1685            if non_directory {
1686                return Err(SmbError::IsDirectory);
1687            }
1688            match opts.intent {
1689                OpenIntent::Open | OpenIntent::OpenOrCreate => {
1690                    let root = Arc::clone(&root);
1691                    let rel = rel.clone();
1692                    let located = located.clone();
1693                    let dir_handle = spawn_blocking(move || {
1694                        let dir = open_dir_handle(&root, &rel, write_attributes)?;
1695                        located.verify(&dir)?;
1696                        Ok::<_, io::Error>(dir)
1697                    })
1698                    .await
1699                    .map_err(join_to_io)
1700                    .map_err(io_to_smb)?
1701                    .map_err(io_to_smb)?;
1702                    let handle: Box<dyn Handle> = Box::new(LocalHandle::Dir {
1703                        name: file_name_for(path),
1704                        root_dev: self.root_dev,
1705                        dir_handle: Arc::new(dir_handle),
1706                        read_only,
1707                        eas: self.eas,
1708                        #[cfg(target_os = "linux")]
1709                        open: self.streams.clone(),
1710                        #[cfg(target_os = "linux")]
1711                        hub: self.hub.clone(),
1712                        #[cfg(target_os = "linux")]
1713                        store: self.store.clone(),
1714                        #[cfg(windows)]
1715                        trash: Arc::clone(&self.trash),
1716                    });
1717                    return Ok((handle, OpenAction::Opened));
1718                }
1719                OpenIntent::Create => return Err(SmbError::Exists),
1720                OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
1721                    return Err(SmbError::IsDirectory);
1722                }
1723            }
1724        }
1725
1726        // 2. Open the file for the intent.
1727        #[cfg(windows)]
1728        let at = located.clone();
1729        let opened = spawn_blocking(move || {
1730            #[cfg(target_os = "linux")]
1731            if located.checked {
1732                let (file, action) = open_file_nofollow(&root, &rel, opts)?;
1733                located.verify(&file)?;
1734                return Ok((file, action));
1735            }
1736            let (file, action) = open_file(&root, &rel, opts)?;
1737            located.verify(&file)?;
1738            Ok::<_, io::Error>((file.into_std(), action))
1739        })
1740        .await
1741        .map_err(join_to_io)
1742        .map_err(io_to_smb)?;
1743        #[cfg(windows)]
1744        let opened = self.discard_collided(&at, false, opened).await;
1745        let (std_file, action) = opened.map_err(open_to_smb)?;
1746
1747        let handle: Box<dyn Handle> = Box::new(LocalHandle::File {
1748            name: file_name_for(path),
1749            root_dev: self.root_dev,
1750            file: Arc::new(std_file),
1751            read_only,
1752            eas: self.eas,
1753            #[cfg(target_os = "linux")]
1754            open: self.streams.clone(),
1755            #[cfg(target_os = "linux")]
1756            store: self.store.clone(),
1757        });
1758        Ok((handle, action))
1759    }
1760}
1761
1762/// True for a FIFO, a socket or a device node. Opening one can block or
1763/// act on a device, so such entries are refused before any open.
1764fn is_special(ty: &super::dir::FileType) -> bool {
1765    #[cfg(unix)]
1766    {
1767        use cap_std::fs::FileTypeExt as _;
1768        ty.is_fifo() || ty.is_socket() || ty.is_char_device() || ty.is_block_device()
1769    }
1770    #[cfg(windows)]
1771    {
1772        let _ = ty;
1773        false
1774    }
1775}
1776
1777/// Fails as changed unless `fd` is open on a regular file, as a name
1778/// replaced since it was checked may not be, then clears the O_NONBLOCK
1779/// the open used, so reads and writes of the file block as usual.
1780#[cfg(unix)]
1781fn check_regular_and_clear_nonblock(fd: &impl std::os::fd::AsFd) -> io::Result<()> {
1782    use rustix::fs::{FileType, OFlags};
1783    if FileType::from_raw_mode(rustix::fs::fstat(fd)?.st_mode) != FileType::RegularFile {
1784        return Err(changed());
1785    }
1786    let flags = rustix::fs::fcntl_getfl(fd)?;
1787    rustix::fs::fcntl_setfl(fd, flags.difference(OFlags::NONBLOCK))?;
1788    Ok(())
1789}
1790
1791/// The error of a file open. On Linux an open that a file lease of another
1792/// process conflicts with fails with EWOULDBLOCK, as the open does not
1793/// block, after the kernel has started breaking the lease; it becomes a
1794/// sharing violation, which clients retry.
1795fn open_to_smb(e: io::Error) -> SmbError {
1796    #[cfg(target_os = "linux")]
1797    if e.kind() == io::ErrorKind::WouldBlock {
1798        return SmbError::Sharing;
1799    }
1800    io_to_smb(e)
1801}
1802
1803/// Opens `rel` below `root` with `options`. On Unix an open that fails on a
1804/// name a FIFO, a socket or a device node took since it was checked fails
1805/// as changed, so the open is looked at again.
1806#[cfg(unix)]
1807fn open_with(root: &Dir, rel: &Path, options: &DirOpenOptions) -> io::Result<super::dir::File> {
1808    root.open_with(rel, options).map_err(|e| {
1809        if root
1810            .metadata(rel)
1811            .is_ok_and(|md| is_special(&md.file_type()))
1812        {
1813            changed()
1814        } else {
1815            e
1816        }
1817    })
1818}
1819
1820#[cfg(windows)]
1821fn open_with(root: &Dir, rel: &Path, options: &DirOpenOptions) -> io::Result<super::dir::File> {
1822    root.open_with(rel, options)
1823}
1824
1825/// True if `name` in `dir`, not following a final symlink, is a FIFO, a
1826/// socket or a device node.
1827#[cfg(target_os = "linux")]
1828fn special_at(dir: &Dir, name: &Path) -> bool {
1829    use rustix::fs::{AtFlags, FileType};
1830    rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW).is_ok_and(|st| {
1831        matches!(
1832            FileType::from_raw_mode(st.st_mode),
1833            FileType::Fifo | FileType::Socket | FileType::CharacterDevice | FileType::BlockDevice
1834        )
1835    })
1836}
1837
1838/// True if an open with `opts` may change the file: it asks for write
1839/// access, or its disposition may create or truncate.
1840fn writes(opts: &OpenOptions) -> bool {
1841    opts.write || opts.write_attributes || opts.intent != OpenIntent::Open
1842}
1843
1844/// Opens the file `rel` below `root` for `opts.intent`. OPEN_IF opens an
1845/// existing file with the access `opts` asks for, so a read-only file opens
1846/// for reading.
1847fn open_file(
1848    root: &Dir,
1849    rel: &Path,
1850    opts: OpenOptions,
1851) -> io::Result<(super::dir::File, OpenAction)> {
1852    let existing = existing_file_options(&opts);
1853    let mut created = DirOpenOptions::new();
1854    created.read(opts.read).write(true).create_new(true);
1855    let mut truncated = DirOpenOptions::new();
1856    truncated.read(opts.read).write(true);
1857    // Windows refuses to truncate a HIDDEN or SYSTEM file as it opens it;
1858    // the file is emptied once open instead.
1859    #[cfg(unix)]
1860    truncated.truncate(true);
1861    #[cfg(unix)]
1862    for options in [&mut created, &mut truncated] {
1863        use cap_std::fs::OpenOptionsExt as _;
1864        options.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY);
1865    }
1866    let not_found = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
1867    let exists = |e: &io::Error| e.kind() == io::ErrorKind::AlreadyExists;
1868    let (file, action) = match opts.intent {
1869        OpenIntent::Open => (open_with(root, rel, &existing)?, OpenAction::Opened),
1870        OpenIntent::Create => (open_with(root, rel, &created)?, OpenAction::Created),
1871        OpenIntent::Truncate => (open_with(root, rel, &truncated)?, OpenAction::Overwritten),
1872        // The file can appear or vanish between the two calls, so each pair
1873        // is tried a second time.
1874        OpenIntent::OpenOrCreate => {
1875            let mut attempt = 0;
1876            loop {
1877                attempt += 1;
1878                match open_with(root, rel, &existing) {
1879                    Ok(f) => break (f, OpenAction::Opened),
1880                    Err(e) if not_found(&e) => {}
1881                    Err(e) => return Err(e),
1882                }
1883                match open_with(root, rel, &created) {
1884                    Ok(f) => break (f, OpenAction::Created),
1885                    Err(e) if exists(&e) && attempt < 2 => {}
1886                    Err(e) => return Err(e),
1887                }
1888            }
1889        }
1890        OpenIntent::OverwriteOrCreate => {
1891            let mut attempt = 0;
1892            loop {
1893                attempt += 1;
1894                match open_with(root, rel, &created) {
1895                    Ok(f) => break (f, OpenAction::Created),
1896                    Err(e) if exists(&e) => {}
1897                    Err(e) => return Err(e),
1898                }
1899                match open_with(root, rel, &truncated) {
1900                    Ok(f) => break (f, OpenAction::Overwritten),
1901                    Err(e) if not_found(&e) && attempt < 2 => {}
1902                    Err(e) => return Err(e),
1903                }
1904            }
1905        }
1906    };
1907    #[cfg(unix)]
1908    check_regular_and_clear_nonblock(&file)?;
1909    #[cfg(windows)]
1910    if action == OpenAction::Overwritten {
1911        file.set_len(0)?;
1912    }
1913    Ok((file, action))
1914}
1915
1916/// Opens the file `name` in `dir` for `opts.intent`, as [`open_file`]
1917/// does, without following a symlink: a name that became one since it was
1918/// looked up fails as changed, before anything is truncated.
1919#[cfg(target_os = "linux")]
1920fn open_file_nofollow(
1921    dir: &Dir,
1922    name: &Path,
1923    opts: OpenOptions,
1924) -> io::Result<(std::fs::File, OpenAction)> {
1925    use rustix::fs::{Mode, OFlags};
1926
1927    let base = OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK | OFlags::NOCTTY;
1928    let access = |write: bool| match (opts.read, write) {
1929        (true, true) => OFlags::RDWR,
1930        (false, true) => OFlags::WRONLY,
1931        _ => OFlags::RDONLY,
1932    };
1933    let existing = base
1934        | if opts.write {
1935            OFlags::RDWR
1936        } else {
1937            OFlags::RDONLY
1938        };
1939    let created = base | access(true) | OFlags::CREATE | OFlags::EXCL;
1940    let truncated = base | access(true) | OFlags::TRUNC;
1941    let open = |flags: OFlags| -> io::Result<std::fs::File> {
1942        match rustix::fs::openat(dir, name, flags, Mode::from_raw_mode(0o666)) {
1943            Ok(fd) => Ok(std::fs::File::from(fd)),
1944            Err(rustix::io::Errno::LOOP) => Err(changed()),
1945            Err(_) if special_at(dir, name) => Err(changed()),
1946            Err(e) => Err(e.into()),
1947        }
1948    };
1949    let not_found = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
1950    let exists = |e: &io::Error| e.kind() == io::ErrorKind::AlreadyExists;
1951    let (file, action) = match opts.intent {
1952        OpenIntent::Open => (open(existing)?, OpenAction::Opened),
1953        OpenIntent::Create => (open(created)?, OpenAction::Created),
1954        OpenIntent::Truncate => (open(truncated)?, OpenAction::Overwritten),
1955        // The file can appear or vanish between the two calls, so each pair
1956        // is tried a second time.
1957        OpenIntent::OpenOrCreate => {
1958            let mut attempt = 0;
1959            loop {
1960                attempt += 1;
1961                match open(existing) {
1962                    Ok(f) => break (f, OpenAction::Opened),
1963                    Err(e) if not_found(&e) => {}
1964                    Err(e) => return Err(e),
1965                }
1966                match open(created) {
1967                    Ok(f) => break (f, OpenAction::Created),
1968                    Err(e) if exists(&e) && attempt < 2 => {}
1969                    Err(e) => return Err(e),
1970                }
1971            }
1972        }
1973        OpenIntent::OverwriteOrCreate => {
1974            let mut attempt = 0;
1975            loop {
1976                attempt += 1;
1977                match open(created) {
1978                    Ok(f) => break (f, OpenAction::Created),
1979                    Err(e) if exists(&e) => {}
1980                    Err(e) => return Err(e),
1981                }
1982                match open(truncated) {
1983                    Ok(f) => break (f, OpenAction::Overwritten),
1984                    Err(e) if not_found(&e) && attempt < 2 => {}
1985                    Err(e) => return Err(e),
1986                }
1987            }
1988        }
1989    };
1990    check_regular_and_clear_nonblock(&file)?;
1991    Ok((file, action))
1992}
1993
1994/// `Dir` options that open an existing file with the access `opts` asks
1995/// for, and on Unix without blocking.
1996fn existing_file_options(opts: &OpenOptions) -> DirOpenOptions {
1997    let mut dir_opts = DirOpenOptions::new();
1998    dir_opts.read(true).write(opts.write);
1999    #[cfg(unix)]
2000    {
2001        use cap_std::fs::OpenOptionsExt as _;
2002        dir_opts.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY);
2003    }
2004    // Unix sets times and permissions through a read-only descriptor.
2005    // Windows needs the access right, which a read-only file grants without
2006    // write access.
2007    #[cfg(windows)]
2008    if opts.write_attributes && !opts.write {
2009        const GENERIC_READ: u32 = 0x8000_0000;
2010        const FILE_WRITE_ATTRIBUTES: u32 = 0x0000_0100;
2011        dir_opts.access_mode(GENERIC_READ | FILE_WRITE_ATTRIBUTES);
2012    }
2013    dir_opts
2014}
2015
2016#[async_trait]
2017impl ShareBackend for LocalFsBackend {
2018    async fn open(
2019        &self,
2020        path: &SmbPath,
2021        opts: OpenOptions,
2022    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
2023        let refused = match opts.intent {
2024            OpenIntent::Open | OpenIntent::Truncate => SmbError::NotFound,
2025            _ => SmbError::AccessDenied,
2026        };
2027        if self.reserves(path) {
2028            return Err(refused);
2029        }
2030        self.prepare_store().await;
2031        let mut tries = 0;
2032        let result = loop {
2033            let located = match self.locate_again(path, true).await {
2034                Ok(located) => located,
2035                Err(e) if is_in_store(&e) => return Err(refused),
2036                Err(e) => break Err(io_to_smb(e)),
2037            };
2038            #[cfg(test)]
2039            if let Some(f) = &self.after_locate {
2040                f();
2041            }
2042            match self.open_entry(path, located, opts).await {
2043                // The last name changed after it was looked up.
2044                Err(SmbError::Io(e)) if is_changed(&e) && tries == 0 => tries += 1,
2045                Err(SmbError::Io(e)) if is_changed(&e) => break Err(SmbError::NotFound),
2046                result => break result,
2047            }
2048        };
2049        if matches!(result, Err(SmbError::NotFound | SmbError::NotADirectory))
2050            && self.parent_missing(path).await
2051        {
2052            return Err(SmbError::PathNotFound);
2053        }
2054        result
2055    }
2056
2057    async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
2058        if self.read_only {
2059            return Err(SmbError::AccessDenied);
2060        }
2061        if path.is_root() {
2062            // Refusing to delete the share root itself.
2063            return Err(SmbError::AccessDenied);
2064        }
2065        if self.reserves(path) {
2066            return Err(SmbError::NotFound);
2067        }
2068        self.prepare_store().await;
2069        let located = match self.locate_again(path, false).await {
2070            Ok(located) => located,
2071            Err(e) if is_in_store(&e) => return Err(SmbError::NotFound),
2072            Err(e) => return Err(io_to_smb(e)),
2073        };
2074        if located.checked && located.rel == Path::new(".") {
2075            return Err(SmbError::AccessDenied);
2076        }
2077        let Located {
2078            base: root, rel, ..
2079        } = located;
2080        #[cfg(windows)]
2081        let trash = Arc::clone(&self.trash);
2082
2083        spawn_blocking(move || -> io::Result<()> {
2084            // Pick the call from the entry itself: the error `remove_file`
2085            // returns for a directory differs between hosts. Neither call
2086            // follows a final symlink, so a link is removed as a link.
2087            let is_dir = is_dir_entry(&root.symlink_metadata(&rel)?);
2088            #[cfg(windows)]
2089            {
2090                trash.remove(&root, &rel, is_dir)
2091            }
2092            #[cfg(unix)]
2093            {
2094                if is_dir {
2095                    root.remove_dir(&rel)
2096                } else {
2097                    root.remove_file(&rel)
2098                }
2099            }
2100        })
2101        .await
2102        .map_err(join_to_io)
2103        .map_err(io_to_smb)?
2104        .map_err(io_to_smb)
2105    }
2106
2107    async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()> {
2108        if self.read_only {
2109            return Err(SmbError::AccessDenied);
2110        }
2111        if from.is_root() || to.is_root() {
2112            return Err(SmbError::NameInvalid);
2113        }
2114        if self.reserves(from) {
2115            return Err(SmbError::NotFound);
2116        }
2117        if self.reserves(to) {
2118            return Err(SmbError::AccessDenied);
2119        }
2120        self.prepare_store().await;
2121        let from_at = match self.locate_again(from, false).await {
2122            Ok(located) => located,
2123            Err(e) if is_in_store(&e) => return Err(SmbError::NotFound),
2124            Err(e) => return Err(io_to_smb(e)),
2125        };
2126        let to_at = match self.locate_again(to, false).await {
2127            Ok(located) => located,
2128            Err(e) if is_in_store(&e) => return Err(SmbError::AccessDenied),
2129            Err(e) if e.kind() == io::ErrorKind::NotFound && self.parent_missing(to).await => {
2130                return Err(SmbError::PathNotFound);
2131            }
2132            Err(e) => return Err(io_to_smb(e)),
2133        };
2134        let dot = Path::new(".");
2135        if (from_at.checked && from_at.rel == dot) || (to_at.checked && to_at.rel == dot) {
2136            return Err(SmbError::AccessDenied);
2137        }
2138        let same_name = same_path(from, to, self.capabilities().case_sensitive);
2139        let (root, from) = (from_at.base, from_at.rel);
2140        let (to_root, to_path) = (to_at.base, to_at.rel);
2141        #[cfg(windows)]
2142        let trash = Arc::clone(&self.trash);
2143
2144        // On Windows the target of a case-only rename is the source itself,
2145        // and a stat of it would open it under the target's spelling.
2146        let target_checked = !(cfg!(windows) && same_name);
2147
2148        let result = spawn_blocking(move || -> io::Result<()> {
2149            let from_md = root.symlink_metadata(&from)?;
2150            let to_md = if target_checked {
2151                to_root.symlink_metadata(&to_path)
2152            } else {
2153                Err(io::ErrorKind::NotFound.into())
2154            };
2155            match to_md {
2156                Ok(to_md) => {
2157                    let from_key = file_key(&from_md);
2158                    let same_file = from_key.is_some() && from_key == file_key(&to_md);
2159                    // A target that is the source under the same name, such
2160                    // as a case-only rename on a case-insensitive host, is
2161                    // not a collision.
2162                    if !(same_file && same_name) {
2163                        if !replace_if_exists {
2164                            return Err(io::ErrorKind::AlreadyExists.into());
2165                        }
2166                        if is_dir_entry(&to_md) {
2167                            return Err(io::ErrorKind::PermissionDenied.into());
2168                        }
2169                    }
2170                    // The host leaves both names in place when renaming one
2171                    // hard link over another, so the source link is removed.
2172                    // A file with one link reached under two spellings is a
2173                    // single entry and goes through the rename.
2174                    if same_file && !same_name && link_count(&from_md) > Some(1) {
2175                        #[cfg(windows)]
2176                        return trash.remove(&root, &from, false);
2177                        #[cfg(unix)]
2178                        return root.remove_file(&from);
2179                    }
2180                }
2181                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
2182                Err(e) => return Err(e),
2183            }
2184            root.rename(&from, &to_root, &to_path)
2185        })
2186        .await
2187        .map_err(join_to_io)
2188        .map_err(io_to_smb)?
2189        .map_err(io_to_smb);
2190        if matches!(result, Err(SmbError::NotFound | SmbError::NotADirectory))
2191            && self.parent_missing(to).await
2192        {
2193            return Err(SmbError::PathNotFound);
2194        }
2195        result
2196    }
2197
2198    fn capabilities(&self) -> BackendCapabilities {
2199        BackendCapabilities {
2200            is_read_only: self.read_only,
2201            case_sensitive: self.case_sensitive,
2202            #[cfg(any(target_os = "linux", target_os = "macos"))]
2203            named_streams: self.streams.is_some(),
2204            #[cfg(windows)]
2205            named_streams: self.volume.is_some(),
2206            #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
2207            named_streams: false,
2208            extended_attributes: self.eas,
2209            block_cloning: self.block_cloning && !self.read_only,
2210        }
2211    }
2212
2213    async fn volume_info(&self) -> SmbResult<VolumeInfo> {
2214        let root = Arc::clone(&self.root);
2215        let root_dev = self.root_dev;
2216        spawn_blocking(move || volume::volume_info(&root, root_dev))
2217            .await
2218            .map_err(join_to_io)
2219            .map_err(io_to_smb)?
2220            .map_err(io_to_smb)
2221    }
2222
2223    #[cfg(target_os = "linux")]
2224    async fn copy_range(
2225        &self,
2226        src: &dyn Handle,
2227        src_offset: u64,
2228        dst: &dyn Handle,
2229        dst_offset: u64,
2230        len: u64,
2231    ) -> SmbResult<u64> {
2232        let (src, dst) = local_files(src, dst)?;
2233        let (copied, stopped) =
2234            spawn_blocking(move || copy_file_range_loop(&src, src_offset, &dst, dst_offset, len))
2235                .await
2236                .map_err(join_to_io)
2237                .map_err(io_to_smb)?;
2238        match stopped {
2239            Some(errno) if copied == 0 => Err(copy_error(errno)),
2240            _ => Ok(copied),
2241        }
2242    }
2243
2244    #[cfg(target_os = "linux")]
2245    async fn clone_range(
2246        &self,
2247        src: &dyn Handle,
2248        src_offset: u64,
2249        dst: &dyn Handle,
2250        dst_offset: u64,
2251        len: u64,
2252    ) -> SmbResult<()> {
2253        let (src, dst) = local_files(src, dst)?;
2254        // FICLONERANGE reads a length of 0 as "to the end of the source".
2255        if len == 0 {
2256            return Ok(());
2257        }
2258        spawn_blocking(move || super::reflink::clone_range(&src, src_offset, &dst, dst_offset, len))
2259            .await
2260            .map_err(join_to_io)
2261            .map_err(io_to_smb)?
2262            .map_err(clone_error)
2263    }
2264
2265    #[cfg(windows)]
2266    async fn clone_range(
2267        &self,
2268        src: &dyn Handle,
2269        src_offset: u64,
2270        dst: &dyn Handle,
2271        dst_offset: u64,
2272        len: u64,
2273    ) -> SmbResult<()> {
2274        let (src, dst) = local_files(src, dst)?;
2275        if len == 0 {
2276            return Ok(());
2277        }
2278        spawn_blocking(move || {
2279            super::windows_clone::clone_range(&src, src_offset, &dst, dst_offset, len)
2280        })
2281        .await
2282        .map_err(join_to_io)
2283        .map_err(io_to_smb)?
2284    }
2285
2286    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
2287    async fn open_stream(
2288        &self,
2289        file: Box<dyn Handle>,
2290        path: &SmbPath,
2291        stream: &StreamName,
2292        opts: OpenOptions,
2293    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
2294        let id = file.stat().await.map(|info| info.file_index);
2295        if let Err(e) = file.close().await {
2296            debug!(error = %e, path = %path, "backend close failed");
2297        }
2298        if self.read_only && writes(&opts) {
2299            return Err(SmbError::AccessDenied);
2300        }
2301        self.stream_place()?
2302            .open_stream(
2303                to_rel_path(path),
2304                file_name_for(path),
2305                id?,
2306                stream.clone(),
2307                opts,
2308            )
2309            .await
2310    }
2311
2312    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
2313    async fn remove_stream(
2314        &self,
2315        path: &SmbPath,
2316        file_index: u64,
2317        stream: &StreamName,
2318    ) -> SmbResult<()> {
2319        if self.read_only {
2320            return Err(SmbError::AccessDenied);
2321        }
2322        self.stream_place()?
2323            .remove_stream(to_rel_path(path), file_index, stream.clone())
2324            .await
2325    }
2326
2327    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
2328    async fn rename_stream(
2329        &self,
2330        path: &SmbPath,
2331        file_index: u64,
2332        from: Option<&StreamName>,
2333        to: Option<&StreamName>,
2334        replace_if_exists: bool,
2335    ) -> SmbResult<()> {
2336        if self.read_only {
2337            return Err(SmbError::AccessDenied);
2338        }
2339        self.stream_place()?
2340            .rename_stream(
2341                to_rel_path(path),
2342                file_index,
2343                from.cloned(),
2344                to.cloned(),
2345                replace_if_exists,
2346            )
2347            .await
2348    }
2349}
2350
2351#[cfg(any(target_os = "linux", target_os = "macos", windows))]
2352impl LocalFsBackend {
2353    #[cfg(target_os = "linux")]
2354    fn stream_place(&self) -> SmbResult<super::streams::Place> {
2355        Ok(super::streams::Place {
2356            root: Arc::clone(&self.root),
2357            root_dev: self.root_dev,
2358            read_only: self.read_only,
2359            open: self.streams.clone().ok_or(SmbError::NotSupported)?,
2360            store: self.store.clone().ok_or(SmbError::NotSupported)?,
2361        })
2362    }
2363
2364    #[cfg(target_os = "macos")]
2365    fn stream_place(&self) -> SmbResult<super::macos_streams::Place> {
2366        Ok(super::macos_streams::Place {
2367            root: Arc::clone(&self.root),
2368            root_dev: self.root_dev,
2369            read_only: self.read_only,
2370            open: self.streams.clone().ok_or(SmbError::NotSupported)?,
2371        })
2372    }
2373
2374    #[cfg(windows)]
2375    fn stream_place(&self) -> SmbResult<super::windows_streams::Place> {
2376        Ok(super::windows_streams::Place {
2377            root: Arc::clone(&self.root),
2378            root_dev: self.root_dev,
2379            read_only: self.read_only,
2380            volume: self.volume.ok_or(SmbError::NotSupported)?,
2381        })
2382    }
2383}
2384
2385// ---------------------------------------------------------------------------
2386// Handle
2387// ---------------------------------------------------------------------------
2388
2389/// Internal handle variant. `File` carries a `std::fs::File` (after the
2390/// `Dir` has done the safe open); `Dir` keeps the `Dir` for listing and
2391/// setting times.
2392enum LocalHandle {
2393    File {
2394        name: String,
2395        root_dev: Option<u64>,
2396        file: Arc<std::fs::File>,
2397        read_only: bool,
2398        /// The share stores extended attributes.
2399        eas: bool,
2400        /// The named streams open through the backend.
2401        #[cfg(target_os = "linux")]
2402        open: Option<Arc<super::open_streams::OpenStreams>>,
2403        #[cfg(target_os = "linux")]
2404        store: Option<Arc<super::streams::Store>>,
2405    },
2406    Dir {
2407        name: String,
2408        root_dev: Option<u64>,
2409        dir_handle: Arc<Dir>,
2410        read_only: bool,
2411        /// The share stores extended attributes.
2412        eas: bool,
2413        /// The named streams open through the backend.
2414        #[cfg(target_os = "linux")]
2415        open: Option<Arc<super::open_streams::OpenStreams>>,
2416        #[cfg(target_os = "linux")]
2417        hub: Option<Arc<super::inotify::Hub>>,
2418        #[cfg(target_os = "linux")]
2419        store: Option<Arc<super::streams::Store>>,
2420        /// Where deleted entries go, which listings of the share root
2421        /// leave out.
2422        #[cfg(windows)]
2423        trash: Arc<super::windows_trash::Trash>,
2424    },
2425}
2426
2427impl LocalHandle {
2428    /// What the extended attribute calls work on; `NotSupported` when the
2429    /// share stores none.
2430    fn ea_target(&self) -> SmbResult<EaTarget> {
2431        match self {
2432            LocalHandle::File { eas: false, .. } | LocalHandle::Dir { eas: false, .. } => {
2433                Err(SmbError::NotSupported)
2434            }
2435            LocalHandle::File { file, .. } => Ok(EaTarget::File(Arc::clone(file))),
2436            LocalHandle::Dir { dir_handle, .. } => Ok(EaTarget::Dir(Arc::clone(dir_handle))),
2437        }
2438    }
2439
2440    /// The named streams open through the backend, on Linux.
2441    fn open_streams(&self) -> Option<Arc<OpenStreamsOf>> {
2442        #[cfg(target_os = "linux")]
2443        {
2444            let (LocalHandle::File { open, .. } | LocalHandle::Dir { open, .. }) = self;
2445            open.clone()
2446        }
2447        #[cfg(not(target_os = "linux"))]
2448        {
2449            None
2450        }
2451    }
2452
2453    /// The stream store of the share, which listings leave out.
2454    #[cfg(target_os = "linux")]
2455    fn store(&self) -> Option<Arc<super::streams::Store>> {
2456        let (LocalHandle::File { store, .. } | LocalHandle::Dir { store, .. }) = self;
2457        store.clone()
2458    }
2459}
2460
2461/// The changes of a watch, without those to entries named `hidden`.
2462#[cfg(target_os = "linux")]
2463struct Hiding {
2464    inner: Box<dyn crate::backend::DirWatch>,
2465    hidden: &'static str,
2466}
2467
2468#[cfg(target_os = "linux")]
2469#[async_trait]
2470impl crate::backend::DirWatch for Hiding {
2471    async fn next(&mut self) -> Option<Vec<crate::backend::DirChange>> {
2472        use crate::backend::{DirChange, DirChangeKind};
2473        loop {
2474            let changes = self.inner.next().await?;
2475            let hidden = |name: &str| name == self.hidden;
2476            let kept: Vec<DirChange> = changes
2477                .into_iter()
2478                .filter_map(|change| match &change.kind {
2479                    DirChangeKind::Renamed { from } => match (hidden(from), hidden(&change.name)) {
2480                        (false, false) => Some(change),
2481                        (true, false) => Some(DirChange::new(
2482                            change.name,
2483                            DirChangeKind::Added,
2484                            change.is_directory,
2485                        )),
2486                        (false, true) => Some(DirChange::new(
2487                            from.clone(),
2488                            DirChangeKind::Removed,
2489                            change.is_directory,
2490                        )),
2491                        (true, true) => None,
2492                    },
2493                    _ if hidden(&change.name) => None,
2494                    _ => Some(change),
2495                })
2496                .collect();
2497            if !kept.is_empty() {
2498                return Some(kept);
2499            }
2500        }
2501    }
2502}
2503
2504pub(super) fn file_name_for(path: &SmbPath) -> String {
2505    path.file_name().unwrap_or("").to_string()
2506}
2507
2508#[async_trait]
2509impl Handle for LocalHandle {
2510    async fn read(&self, offset: u64, len: u32) -> SmbResult<Bytes> {
2511        match self {
2512            LocalHandle::File { file, .. } => {
2513                let file = Arc::clone(file);
2514                let n = len as usize;
2515                let bytes = spawn_blocking(move || -> io::Result<Bytes> {
2516                    let mut buf = vec![0u8; n];
2517                    let read = read_at(&file, &mut buf, offset)?;
2518                    buf.truncate(read);
2519                    Ok(Bytes::from(buf))
2520                })
2521                .await
2522                .map_err(join_to_io)
2523                .map_err(io_to_smb)?
2524                .map_err(io_to_smb)?;
2525                Ok(bytes)
2526            }
2527            LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
2528        }
2529    }
2530
2531    async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32> {
2532        self.write_owned(offset, data.to_vec()).await
2533    }
2534
2535    async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
2536        match self {
2537            LocalHandle::File {
2538                file, read_only, ..
2539            } => {
2540                if *read_only {
2541                    return Err(SmbError::AccessDenied);
2542                }
2543                let file = Arc::clone(file);
2544                let written = spawn_blocking(move || write_at(&file, &data, offset))
2545                    .await
2546                    .map_err(join_to_io)
2547                    .map_err(io_to_smb)?
2548                    .map_err(io_to_smb)?;
2549                Ok(u32::try_from(written).unwrap_or(u32::MAX))
2550            }
2551            LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
2552        }
2553    }
2554
2555    async fn flush(&self) -> SmbResult<()> {
2556        match self {
2557            LocalHandle::File { file, .. } => {
2558                let file = Arc::clone(file);
2559                spawn_blocking(move || file.sync_data())
2560                    .await
2561                    .map_err(join_to_io)
2562                    .map_err(io_to_smb)?
2563                    .map_err(io_to_smb)
2564            }
2565            // Flushing a directory is a no-op in SMB semantics.
2566            LocalHandle::Dir { .. } => Ok(()),
2567        }
2568    }
2569
2570    async fn stat(&self) -> SmbResult<FileInfo> {
2571        match self {
2572            LocalHandle::File {
2573                file,
2574                name,
2575                root_dev,
2576                eas,
2577                ..
2578            } => {
2579                let file = Arc::clone(file);
2580                let name = name.clone();
2581                let (root_dev, eas) = (*root_dev, *eas);
2582                spawn_blocking(move || -> io::Result<FileInfo> {
2583                    let md = Metadata::from_file(&file)?;
2584                    let mut info = file_info_from_metadata(name, &md, root_dev);
2585                    if eas {
2586                        info.ea_size = host_ea_size(&file);
2587                    }
2588                    Ok(info)
2589                })
2590                .await
2591                .map_err(join_to_io)
2592                .map_err(io_to_smb)?
2593                .map_err(io_to_smb)
2594            }
2595            LocalHandle::Dir {
2596                dir_handle,
2597                name,
2598                root_dev,
2599                eas,
2600                ..
2601            } => {
2602                let dir_handle = Arc::clone(dir_handle);
2603                let name = name.clone();
2604                let (root_dev, eas) = (*root_dev, *eas);
2605                spawn_blocking(move || -> io::Result<FileInfo> {
2606                    let md = dir_handle.dir_metadata()?;
2607                    let mut info = file_info_from_metadata(name, &md, root_dev);
2608                    if eas {
2609                        info.ea_size = dir_ea_size(&dir_handle);
2610                    }
2611                    Ok(info)
2612                })
2613                .await
2614                .map_err(join_to_io)
2615                .map_err(io_to_smb)?
2616                .map_err(io_to_smb)
2617            }
2618        }
2619    }
2620
2621    async fn set_times(&self, times: FileTimes) -> SmbResult<()> {
2622        let host_times = host_file_times(times);
2623        match self {
2624            LocalHandle::File {
2625                file, read_only, ..
2626            } => {
2627                if *read_only {
2628                    return Err(SmbError::AccessDenied);
2629                }
2630                let file = Arc::clone(file);
2631                spawn_blocking(move || file.set_times(host_times))
2632                    .await
2633                    .map_err(join_to_io)
2634                    .map_err(io_to_smb)?
2635                    .map_err(io_to_smb)
2636            }
2637            LocalHandle::Dir { dir_handle, .. } => {
2638                let dir_handle = Arc::clone(dir_handle);
2639                spawn_blocking(move || dir_as_file(&dir_handle)?.set_times(host_times))
2640                    .await
2641                    .map_err(join_to_io)
2642                    .map_err(io_to_smb)?
2643                    .map_err(io_to_smb)
2644            }
2645        }
2646    }
2647
2648    async fn set_attributes(&self, attributes: u32) -> SmbResult<()> {
2649        let set = match self {
2650            LocalHandle::File {
2651                file, read_only, ..
2652            } => {
2653                if *read_only {
2654                    return Err(SmbError::AccessDenied);
2655                }
2656                let file = Arc::clone(file);
2657                spawn_blocking(move || set_host_attributes(&file, attributes, false))
2658            }
2659            LocalHandle::Dir {
2660                dir_handle,
2661                read_only,
2662                ..
2663            } => {
2664                if *read_only {
2665                    return Err(SmbError::AccessDenied);
2666                }
2667                if cfg!(unix) {
2668                    return Ok(());
2669                }
2670                let dir_handle = Arc::clone(dir_handle);
2671                spawn_blocking(move || {
2672                    set_host_attributes(&dir_as_file(&dir_handle)?, attributes, true)
2673                })
2674            }
2675        };
2676        set.await
2677            .map_err(join_to_io)
2678            .map_err(io_to_smb)?
2679            .map_err(io_to_smb)
2680    }
2681
2682    async fn truncate(&self, len: u64) -> SmbResult<()> {
2683        match self {
2684            LocalHandle::File {
2685                file, read_only, ..
2686            } => {
2687                if *read_only {
2688                    return Err(SmbError::AccessDenied);
2689                }
2690                let file = Arc::clone(file);
2691                spawn_blocking(move || file.set_len(len))
2692                    .await
2693                    .map_err(join_to_io)
2694                    .map_err(io_to_smb)?
2695                    .map_err(io_to_smb)
2696            }
2697            // Protocol layer rejects truncate on dir handles before this; if
2698            // it ever reaches us, surface as NotSupported.
2699            LocalHandle::Dir { .. } => Err(SmbError::NotSupported),
2700        }
2701    }
2702
2703    async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<SmbDirEntry>> {
2704        self.list_dir_sized(pattern, true).await
2705    }
2706
2707    async fn list_dir_sized(
2708        &self,
2709        pattern: Option<&str>,
2710        ea_size: bool,
2711    ) -> SmbResult<Vec<SmbDirEntry>> {
2712        match self {
2713            LocalHandle::File { .. } => Err(SmbError::NotADirectory),
2714            LocalHandle::Dir {
2715                dir_handle,
2716                root_dev,
2717                eas,
2718                #[cfg(windows)]
2719                trash,
2720                ..
2721            } => {
2722                let dir_handle = Arc::clone(dir_handle);
2723                let (root_dev, eas) = (*root_dev, *eas && ea_size);
2724                let pat = pattern.map(|s| s.to_owned());
2725                #[cfg(target_os = "linux")]
2726                let store = self.store();
2727                #[cfg(windows)]
2728                let trash = Arc::clone(trash);
2729                spawn_blocking(move || {
2730                    #[cfg(target_os = "linux")]
2731                    let hidden = store.and_then(|store| store.key());
2732                    #[cfg(not(target_os = "linux"))]
2733                    let hidden = None;
2734                    #[cfg(windows)]
2735                    let hidden_name = trash.hidden_in(&dir_handle);
2736                    #[cfg(not(windows))]
2737                    let hidden_name = None;
2738                    list_entries(
2739                        &dir_handle,
2740                        pat.as_deref(),
2741                        root_dev,
2742                        hidden,
2743                        hidden_name,
2744                        eas,
2745                    )
2746                })
2747                .await
2748                .map_err(join_to_io)
2749                .map_err(io_to_smb)?
2750                .map_err(io_to_smb)
2751            }
2752        }
2753    }
2754
2755    #[cfg(target_os = "linux")]
2756    async fn watch(&self) -> SmbResult<Option<Box<dyn crate::backend::DirWatch>>> {
2757        match self {
2758            LocalHandle::Dir {
2759                dir_handle,
2760                hub: Some(hub),
2761                ..
2762            } => {
2763                let watch = hub.watch(&**dir_handle);
2764                let hidden = self.store().and_then(|store| store.hidden_in(dir_handle));
2765                Ok(match (watch, hidden) {
2766                    (Some(watch), Some(hidden)) => Some(Box::new(Hiding {
2767                        inner: watch,
2768                        hidden,
2769                    })),
2770                    (watch, _) => watch,
2771                })
2772            }
2773            _ => Ok(None),
2774        }
2775    }
2776
2777    async fn close(self: Box<Self>) -> SmbResult<()> {
2778        // Drop is sufficient: closing the underlying handle is what the OS
2779        // does when the last `Arc` ref goes away. No flush here: SMB CLOSE
2780        // does not imply fsync.
2781        Ok(())
2782    }
2783
2784    /// The host link count of a file. A directory reports one link, as it
2785    /// has one name, or none once it has been removed.
2786    async fn link_count(&self) -> SmbResult<u32> {
2787        let md = match self {
2788            LocalHandle::File { file, .. } => {
2789                let file = Arc::clone(file);
2790                spawn_blocking(move || Metadata::from_file(&file)).await
2791            }
2792            LocalHandle::Dir { dir_handle, .. } => {
2793                let dir_handle = Arc::clone(dir_handle);
2794                spawn_blocking(move || dir_handle.dir_metadata()).await
2795            }
2796        }
2797        .map_err(join_to_io)
2798        .map_err(io_to_smb)?
2799        .map_err(io_to_smb)?;
2800        let links = link_count(&md).map_or(1, |n| u32::try_from(n).unwrap_or(u32::MAX));
2801        Ok(if md.is_dir() { links.min(1) } else { links })
2802    }
2803
2804    async fn dir_is_empty(&self) -> SmbResult<bool> {
2805        match self {
2806            LocalHandle::File { .. } => Err(SmbError::NotADirectory),
2807            LocalHandle::Dir { dir_handle, .. } => {
2808                let dir_handle = Arc::clone(dir_handle);
2809                spawn_blocking(move || dir_is_empty(&dir_handle))
2810                    .await
2811                    .map_err(join_to_io)
2812                    .map_err(io_to_smb)?
2813                    .map_err(io_to_smb)
2814            }
2815        }
2816    }
2817
2818    async fn eas(&self) -> SmbResult<Vec<crate::Ea>> {
2819        let target = self.ea_target()?;
2820        spawn_blocking(move || host_eas(&*target.file()?))
2821            .await
2822            .map_err(join_to_io)
2823            .map_err(io_to_smb)?
2824            .map_err(io_to_smb)
2825    }
2826
2827    async fn set_eas(&self, eas: &[crate::Ea]) -> SmbResult<()> {
2828        let (LocalHandle::File { read_only, .. } | LocalHandle::Dir { read_only, .. }) = self;
2829        if *read_only {
2830            return Err(SmbError::AccessDenied);
2831        }
2832        let target = self.ea_target()?;
2833        let open = self.open_streams();
2834        let eas = eas.to_vec();
2835        spawn_blocking(move || {
2836            let file = target.file().map_err(io_to_smb)?;
2837            host_set_eas(&file, &eas, open.as_ref())
2838        })
2839        .await
2840        .map_err(join_to_io)
2841        .map_err(io_to_smb)?
2842    }
2843
2844    #[cfg(target_os = "linux")]
2845    async fn streams(&self) -> SmbResult<Vec<crate::stream::StreamInfo>> {
2846        let listed = match self {
2847            LocalHandle::File {
2848                file,
2849                store: Some(store),
2850                ..
2851            } => {
2852                let (file, store) = (Arc::clone(file), Arc::clone(store));
2853                spawn_blocking(move || super::streams::list_smb(&file, &store)).await
2854            }
2855            LocalHandle::Dir {
2856                dir_handle,
2857                store: Some(store),
2858                ..
2859            } => {
2860                let (dir_handle, store) = (Arc::clone(dir_handle), Arc::clone(store));
2861                spawn_blocking(move || {
2862                    let fd = dir_as_file(&dir_handle).map_err(io_to_smb)?;
2863                    super::streams::list_smb(&fd, &store)
2864                })
2865                .await
2866            }
2867            _ => return Ok(Vec::new()),
2868        };
2869        listed.map_err(join_to_io).map_err(io_to_smb)?
2870    }
2871
2872    #[cfg(any(target_os = "macos", windows))]
2873    async fn streams(&self) -> SmbResult<Vec<crate::stream::StreamInfo>> {
2874        #[cfg(target_os = "macos")]
2875        use super::macos_streams::list_smb;
2876        #[cfg(windows)]
2877        use super::windows_streams::list_smb;
2878        match self {
2879            LocalHandle::File { file, .. } => {
2880                let file = Arc::clone(file);
2881                spawn_blocking(move || list_smb(&file)).await
2882            }
2883            LocalHandle::Dir { dir_handle, .. } => {
2884                let dir_handle = Arc::clone(dir_handle);
2885                spawn_blocking(move || {
2886                    let fd = dir_as_file(&dir_handle).map_err(io_to_smb)?;
2887                    list_smb(&fd)
2888                })
2889                .await
2890            }
2891        }
2892        .map_err(join_to_io)
2893        .map_err(io_to_smb)?
2894    }
2895
2896    /// Each entry is opened from this directory, a symlink followed only
2897    /// to a target below it, and its streams are read on that descriptor.
2898    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
2899    async fn peek_streams(
2900        &self,
2901        entries: &[(&str, &[(StreamName, u32)])],
2902    ) -> SmbResult<Vec<Vec<Option<(u64, Bytes)>>>> {
2903        let LocalHandle::Dir { dir_handle, .. } = self else {
2904            return Err(SmbError::NotADirectory);
2905        };
2906        let dir = Arc::clone(dir_handle);
2907        let entries: Vec<_> = entries
2908            .iter()
2909            .map(|&(name, streams)| (name.to_owned(), streams.to_vec()))
2910            .collect();
2911        #[cfg(target_os = "linux")]
2912        let peek = {
2913            let (open, store) = self
2914                .open_streams()
2915                .zip(self.store())
2916                .ok_or(SmbError::NotSupported)?;
2917            move || super::streams::peek_entries(&dir, &open, &store, &entries)
2918        };
2919        #[cfg(target_os = "macos")]
2920        let peek = move || super::macos_streams::peek_entries(&dir, &entries);
2921        #[cfg(windows)]
2922        let peek = move || super::windows_streams::peek_entries(&dir, &entries);
2923        spawn_blocking(peek)
2924            .await
2925            .map_err(join_to_io)
2926            .map_err(io_to_smb)
2927    }
2928
2929    fn as_any(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
2930        Some(self)
2931    }
2932}
2933
2934// ---------------------------------------------------------------------------
2935// Tests
2936// ---------------------------------------------------------------------------
2937
2938#[cfg(test)]
2939pub(super) mod tests {
2940    use super::*;
2941    use crate::backend::{OpenIntent, OpenOptions};
2942    use crate::path::SmbPath;
2943    use tempfile::tempdir;
2944
2945    fn p(s: &str) -> SmbPath {
2946        s.parse::<SmbPath>().unwrap()
2947    }
2948
2949    fn opts_create() -> OpenOptions {
2950        OpenOptions {
2951            read: true,
2952            write: true,
2953            write_attributes: true,
2954            intent: OpenIntent::Create,
2955            directory: false,
2956            non_directory: false,
2957            delete_on_close: false,
2958        }
2959    }
2960
2961    fn opts_open_rw() -> OpenOptions {
2962        OpenOptions {
2963            read: true,
2964            write: true,
2965            write_attributes: true,
2966            intent: OpenIntent::Open,
2967            directory: false,
2968            non_directory: false,
2969            delete_on_close: false,
2970        }
2971    }
2972
2973    fn opts_open_ro() -> OpenOptions {
2974        OpenOptions {
2975            read: true,
2976            write: false,
2977            write_attributes: false,
2978            intent: OpenIntent::Open,
2979            directory: false,
2980            non_directory: false,
2981            delete_on_close: false,
2982        }
2983    }
2984
2985    fn opts_open_dir() -> OpenOptions {
2986        OpenOptions {
2987            read: true,
2988            write: false,
2989            write_attributes: false,
2990            intent: OpenIntent::Open,
2991            directory: true,
2992            non_directory: false,
2993            delete_on_close: false,
2994        }
2995    }
2996
2997    /// Opens the existing file `name` of `backend` for reading and writing.
2998    #[cfg(any(target_os = "linux", windows))]
2999    async fn open(backend: &LocalFsBackend, name: &str) -> Box<dyn Handle> {
3000        backend.open(&p(name), opts_open_rw()).await.unwrap().0
3001    }
3002
3003    /// Opens the existing file `name` of `backend` for reading.
3004    #[cfg(any(target_os = "linux", windows))]
3005    async fn open_ro(backend: &LocalFsBackend, name: &str) -> Box<dyn Handle> {
3006        backend.open(&p(name), opts_open_ro()).await.unwrap().0
3007    }
3008
3009    /// The root directory of `backend`, and a file of another backend.
3010    #[cfg(any(target_os = "linux", windows))]
3011    async fn dir_and_foreign(backend: &LocalFsBackend) -> (Box<dyn Handle>, Box<dyn Handle>) {
3012        use crate::tests::memfs::MemFsBackend;
3013
3014        let dir = backend
3015            .open(&SmbPath::root(), opts_open_dir())
3016            .await
3017            .unwrap()
3018            .0;
3019        let memory = MemFsBackend::new().with_file("m", &[0; 8192]);
3020        let foreign = memory.open(&p("m"), opts_open_rw()).await.unwrap().0;
3021        (dir, foreign)
3022    }
3023
3024    #[tokio::test]
3025    async fn create_write_read_stat_close() {
3026        let td = tempdir().unwrap();
3027        let backend = LocalFsBackend::new(td.path()).unwrap();
3028
3029        // Create
3030        let h = backend
3031            .open(&p("hello.txt"), opts_create())
3032            .await
3033            .unwrap()
3034            .0;
3035        let n = h.write(0, b"hello world").await.unwrap();
3036        assert_eq!(n, 11);
3037        h.flush().await.unwrap();
3038
3039        // Stat
3040        let info = h.stat().await.unwrap();
3041        assert_eq!(info.name, "hello.txt");
3042        assert_eq!(info.end_of_file, 11);
3043        assert!(!info.is_directory);
3044        assert!(info.last_write_time > 0);
3045        h.close().await.unwrap();
3046
3047        // Reopen for read
3048        let h2 = backend
3049            .open(&p("hello.txt"), opts_open_ro())
3050            .await
3051            .unwrap()
3052            .0;
3053        let bytes = h2.read(0, 1024).await.unwrap();
3054        assert_eq!(&bytes[..], b"hello world");
3055
3056        // Short-read past EOF returns truncated
3057        let bytes = h2.read(6, 1024).await.unwrap();
3058        assert_eq!(&bytes[..], b"world");
3059
3060        // Read past EOF returns empty
3061        let bytes = h2.read(100, 1024).await.unwrap();
3062        assert!(bytes.is_empty());
3063        h2.close().await.unwrap();
3064    }
3065
3066    #[tokio::test]
3067    async fn list_dir_finds_created_file() {
3068        let td = tempdir().unwrap();
3069        let backend = LocalFsBackend::new(td.path()).unwrap();
3070        let h = backend.open(&p("a.txt"), opts_create()).await.unwrap().0;
3071        h.close().await.unwrap();
3072
3073        let dir_h = backend
3074            .open(&SmbPath::root(), opts_open_dir())
3075            .await
3076            .unwrap()
3077            .0;
3078        let entries = dir_h.list_dir(None).await.unwrap();
3079        assert!(entries.iter().any(|e| e.info.name == "a.txt"));
3080        dir_h.close().await.unwrap();
3081    }
3082
3083    #[tokio::test]
3084    async fn read_only_rejects_writes() {
3085        let td = tempdir().unwrap();
3086        // Pre-create a file via a writable backend so we have something to
3087        // attempt to open RW.
3088        {
3089            let writable = LocalFsBackend::new(td.path()).unwrap();
3090            let h = writable.open(&p("x.txt"), opts_create()).await.unwrap().0;
3091            h.close().await.unwrap();
3092        }
3093
3094        let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
3095        assert!(backend.capabilities().is_read_only);
3096
3097        // RW open should be rejected.
3098        let err = backend
3099            .open(&p("x.txt"), opts_open_rw())
3100            .await
3101            .err()
3102            .unwrap();
3103        assert!(matches!(err, SmbError::AccessDenied));
3104
3105        // Create should be rejected.
3106        let err = backend
3107            .open(&p("y.txt"), opts_create())
3108            .await
3109            .err()
3110            .unwrap();
3111        assert!(matches!(err, SmbError::AccessDenied));
3112
3113        // Pure read open is fine; writes through it are rejected.
3114        let h = backend.open(&p("x.txt"), opts_open_ro()).await.unwrap().0;
3115        assert!(matches!(
3116            h.write(0, b"x").await,
3117            Err(SmbError::AccessDenied)
3118        ));
3119        h.close().await.unwrap();
3120
3121        // unlink rejected.
3122        let err = backend.unlink(&p("x.txt")).await.err().unwrap();
3123        assert!(matches!(err, SmbError::AccessDenied));
3124    }
3125
3126    #[tokio::test]
3127    async fn unlink_file_then_nonempty_dir_errors() {
3128        let td = tempdir().unwrap();
3129        let backend = LocalFsBackend::new(td.path()).unwrap();
3130
3131        // Create & remove a file.
3132        let h = backend
3133            .open(&p("doomed.txt"), opts_create())
3134            .await
3135            .unwrap()
3136            .0;
3137        h.close().await.unwrap();
3138        backend.unlink(&p("doomed.txt")).await.unwrap();
3139        assert!(matches!(
3140            backend.unlink(&p("doomed.txt")).await.err().unwrap(),
3141            SmbError::NotFound
3142        ));
3143
3144        // Create a non-empty directory; unlink should fail with NotEmpty.
3145        std::fs::create_dir(td.path().join("dir1")).unwrap();
3146        std::fs::write(td.path().join("dir1").join("inside"), b"x").unwrap();
3147
3148        let err = backend.unlink(&p("dir1")).await.err().unwrap();
3149        assert!(
3150            matches!(err, SmbError::NotEmpty),
3151            "expected NotEmpty, got {err:?}"
3152        );
3153
3154        // Empty it and retry.
3155        std::fs::remove_file(td.path().join("dir1").join("inside")).unwrap();
3156        backend.unlink(&p("dir1")).await.unwrap();
3157    }
3158
3159    #[tokio::test]
3160    async fn rename_within_root() {
3161        let td = tempdir().unwrap();
3162        let backend = LocalFsBackend::new(td.path()).unwrap();
3163
3164        let h = backend.open(&p("old.txt"), opts_create()).await.unwrap().0;
3165        h.write(0, b"data").await.unwrap();
3166        h.close().await.unwrap();
3167
3168        backend
3169            .rename(&p("old.txt"), &p("new.txt"), false)
3170            .await
3171            .unwrap();
3172        assert!(td.path().join("new.txt").exists());
3173        assert!(!td.path().join("old.txt").exists());
3174
3175        // Renaming over an existing target should fail.
3176        let h = backend
3177            .open(&p("other.txt"), opts_create())
3178            .await
3179            .unwrap()
3180            .0;
3181        h.close().await.unwrap();
3182        let err = backend
3183            .rename(&p("other.txt"), &p("new.txt"), false)
3184            .await
3185            .err()
3186            .unwrap();
3187        assert!(matches!(err, SmbError::Exists), "got {err:?}");
3188    }
3189
3190    #[tokio::test]
3191    async fn rename_onto_itself_is_not_a_collision() {
3192        let td = tempdir().unwrap();
3193        std::fs::write(td.path().join("doc.txt"), b"old").unwrap();
3194        let backend = LocalFsBackend::new(td.path()).unwrap();
3195        backend
3196            .rename(&p("doc.txt"), &p("doc.txt"), false)
3197            .await
3198            .unwrap();
3199        assert_eq!(std::fs::read(td.path().join("doc.txt")).unwrap(), b"old");
3200    }
3201
3202    #[cfg(unix)]
3203    #[tokio::test]
3204    async fn rename_between_hard_links_follows_collision_rules() {
3205        let td = tempdir().unwrap();
3206        let root = td.path();
3207        std::fs::write(root.join("a.txt"), b"data").unwrap();
3208        std::fs::hard_link(root.join("a.txt"), root.join("b.txt")).unwrap();
3209        let backend = LocalFsBackend::new(root).unwrap();
3210
3211        let err = backend
3212            .rename(&p("a.txt"), &p("b.txt"), false)
3213            .await
3214            .unwrap_err();
3215        assert!(matches!(err, SmbError::Exists), "got {err:?}");
3216        assert!(root.join("a.txt").exists());
3217
3218        backend
3219            .rename(&p("a.txt"), &p("b.txt"), true)
3220            .await
3221            .unwrap();
3222        assert!(!root.join("a.txt").exists());
3223        assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"data");
3224    }
3225
3226    #[tokio::test]
3227    async fn directory_file_index_is_the_same_for_every_open_and_listing() {
3228        let td = tempdir().unwrap();
3229        std::fs::create_dir(td.path().join("d")).unwrap();
3230        let backend = LocalFsBackend::new(td.path()).unwrap();
3231
3232        let root = backend
3233            .open(&SmbPath::root(), opts_open_dir())
3234            .await
3235            .unwrap()
3236            .0;
3237        let listed = root.list_dir(None).await.unwrap();
3238        let first = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
3239        let second = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
3240        let id = first.stat().await.unwrap().file_index;
3241        assert_ne!(id, 0);
3242        assert_eq!(second.stat().await.unwrap().file_index, id);
3243        let entry = listed.iter().find(|e| e.info.name == "d").unwrap();
3244        assert_eq!(entry.info.file_index, id);
3245    }
3246
3247    #[test]
3248    fn file_index_keeps_root_device_inodes_and_separates_other_devices() {
3249        let root = Some(0x803);
3250        assert_eq!(file_index(root, Some((0x803, 42))), 42);
3251        assert_eq!(file_index(None, Some((0x803, 42))), 42);
3252        assert_eq!(file_index(root, None), 0);
3253        assert_ne!(
3254            file_index(root, Some((0x803, 1))),
3255            file_index(root, Some((0x2b, 1)))
3256        );
3257    }
3258
3259    #[cfg(unix)]
3260    #[tokio::test]
3261    async fn file_index_is_the_inode_on_the_root_device() {
3262        use std::os::unix::fs::MetadataExt as _;
3263
3264        let td = tempdir().unwrap();
3265        std::fs::write(td.path().join("f.txt"), b"x").unwrap();
3266        let backend = LocalFsBackend::new(td.path()).unwrap();
3267        let h = backend.open(&p("f.txt"), opts_open_ro()).await.unwrap().0;
3268        let ino = std::fs::metadata(td.path().join("f.txt")).unwrap().ino();
3269        assert_eq!(h.stat().await.unwrap().file_index, ino);
3270    }
3271
3272    #[tokio::test]
3273    async fn stat_and_listings_report_the_host_mode() {
3274        let td = tempdir().unwrap();
3275        std::fs::write(td.path().join("f.txt"), b"x").unwrap();
3276        std::fs::create_dir(td.path().join("d")).unwrap();
3277        #[cfg(unix)]
3278        {
3279            use std::os::unix::fs::PermissionsExt as _;
3280            let mode = |name: &str, mode| {
3281                let perms = std::fs::Permissions::from_mode(mode);
3282                std::fs::set_permissions(td.path().join(name), perms).unwrap();
3283            };
3284            mode("f.txt", 0o751);
3285            mode("d", 0o710);
3286        }
3287        let backend = LocalFsBackend::new(td.path()).unwrap();
3288        let root = backend
3289            .open(&SmbPath::root(), opts_open_dir())
3290            .await
3291            .unwrap()
3292            .0;
3293        let listed = root.list_dir(None).await.unwrap();
3294        let listed_mode = |name: &str| {
3295            listed
3296                .iter()
3297                .find(|e| e.info.name == name)
3298                .expect(name)
3299                .info
3300                .unix_mode
3301        };
3302        let h = backend.open(&p("f.txt"), opts_open_ro()).await.unwrap().0;
3303        let stat = h.stat().await.unwrap().unix_mode;
3304        let (file, dir) = if cfg!(unix) {
3305            (Some(0o100_751), Some(0o040_710))
3306        } else {
3307            (None, None)
3308        };
3309        assert_eq!(stat, file);
3310        assert_eq!(listed_mode("f.txt"), file);
3311        assert_eq!(listed_mode("d"), dir);
3312    }
3313
3314    /// Needs mounts below `/` whose roots share an inode number, as procfs,
3315    /// sysfs and tmpfs roots do on Linux.
3316    #[cfg(target_os = "linux")]
3317    #[tokio::test]
3318    async fn file_index_differs_across_mounts_with_equal_inodes() {
3319        use std::os::unix::fs::MetadataExt as _;
3320
3321        let mounts: Vec<_> = ["proc", "sys", "dev", "tmp"]
3322            .into_iter()
3323            .filter_map(|name| {
3324                let md = std::fs::metadata(Path::new("/").join(name)).ok()?;
3325                Some((name, md.dev(), md.ino()))
3326            })
3327            .collect();
3328        let pair = mounts.iter().enumerate().find_map(|(i, a)| {
3329            mounts[i + 1..]
3330                .iter()
3331                .find(|b| a.1 != b.1 && a.2 == b.2)
3332                .map(|b| (a.0, b.0))
3333        });
3334        let Some((a, b)) = pair else {
3335            eprintln!("no two mounts below / share an inode number; skipping");
3336            return;
3337        };
3338        let backend = LocalFsBackend::new("/").unwrap();
3339        let root = backend
3340            .open(&SmbPath::root(), opts_open_dir())
3341            .await
3342            .unwrap()
3343            .0;
3344        let listed = root.list_dir(None).await.unwrap();
3345        let mut ids = Vec::new();
3346        for name in [a, b] {
3347            let h = backend.open(&p(name), opts_open_dir()).await.unwrap().0;
3348            let id = h.stat().await.unwrap().file_index;
3349            let entry = listed.iter().find(|e| e.info.name == name).unwrap();
3350            assert_eq!(entry.info.file_index, id, "{name}");
3351            ids.push(id);
3352        }
3353        assert_ne!(ids[0], ids[1], "{a} and {b}");
3354    }
3355
3356    #[cfg(unix)]
3357    #[tokio::test]
3358    async fn unlink_removes_empty_dirs_and_symlinks_as_links() {
3359        use std::os::unix::fs::symlink;
3360
3361        let td = tempdir().unwrap();
3362        let outside = tempdir().unwrap();
3363        std::fs::write(outside.path().join("keep.txt"), b"x").unwrap();
3364        let root = td.path();
3365        std::fs::create_dir(root.join("empty")).unwrap();
3366        std::fs::create_dir(root.join("target")).unwrap();
3367        std::fs::write(root.join("target").join("inside.txt"), b"x").unwrap();
3368        symlink(root.join("target"), root.join("link_in")).unwrap();
3369        symlink(outside.path(), root.join("link_out")).unwrap();
3370        symlink(root.join("missing"), root.join("dangling")).unwrap();
3371        let backend = LocalFsBackend::new(root).unwrap();
3372
3373        backend.unlink(&p("empty")).await.unwrap();
3374        assert!(!root.join("empty").exists());
3375
3376        for link in ["link_in", "link_out", "dangling"] {
3377            backend.unlink(&p(link)).await.unwrap();
3378            assert!(root.join(link).symlink_metadata().is_err(), "{link}");
3379        }
3380        assert!(root.join("target").join("inside.txt").exists());
3381        assert!(outside.path().join("keep.txt").exists());
3382    }
3383
3384    #[test]
3385    fn cross_device_error_maps_to_not_same_device() {
3386        assert!(matches!(
3387            io_to_smb(io::ErrorKind::CrossesDevices.into()),
3388            SmbError::NotSameDevice
3389        ));
3390    }
3391
3392    #[tokio::test]
3393    async fn list_dir_pattern_matching() {
3394        let td = tempdir().unwrap();
3395        let backend = LocalFsBackend::new(td.path()).unwrap();
3396
3397        for name in ["a.txt", "b.txt", "c.log", "README"] {
3398            let h = backend.open(&p(name), opts_create()).await.unwrap().0;
3399            h.close().await.unwrap();
3400        }
3401
3402        let dir_h = backend
3403            .open(&SmbPath::root(), opts_open_dir())
3404            .await
3405            .unwrap()
3406            .0;
3407
3408        let txts = dir_h.list_dir(Some("*.txt")).await.unwrap();
3409        let names: Vec<_> = txts.iter().map(|e| e.info.name.as_str()).collect();
3410        assert_eq!(names.len(), 2, "expected 2 .txt files, got {names:?}");
3411        assert!(names.contains(&"a.txt"));
3412        assert!(names.contains(&"b.txt"));
3413
3414        // Single-char wildcard.
3415        let one = dir_h.list_dir(Some("?.log")).await.unwrap();
3416        let names: Vec<_> = one.iter().map(|e| e.info.name.as_str()).collect();
3417        assert_eq!(names, vec!["c.log"]);
3418
3419        // Case follows the host's lookup rule.
3420        let any_txt = dir_h.list_dir(Some("*.TXT")).await.unwrap();
3421        let expected = if backend.capabilities().case_sensitive {
3422            0
3423        } else {
3424            2
3425        };
3426        assert_eq!(any_txt.len(), expected);
3427
3428        // "*" matches everything.
3429        let all = dir_h.list_dir(Some("*")).await.unwrap();
3430        assert_eq!(all.len(), 4);
3431
3432        dir_h.close().await.unwrap();
3433    }
3434
3435    #[cfg(windows)]
3436    #[test]
3437    fn sharing_violation_maps_to_sharing() {
3438        use crate::fs::windows_dir::ERROR_SHARING_VIOLATION;
3439        assert!(matches!(
3440            io_to_smb(io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)),
3441            SmbError::Sharing
3442        ));
3443    }
3444
3445    #[tokio::test]
3446    async fn directory_unlinks_while_open() {
3447        let td = tempdir().unwrap();
3448        std::fs::create_dir(td.path().join("d")).unwrap();
3449        let backend = LocalFsBackend::new(td.path()).unwrap();
3450        let h = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
3451        backend.unlink(&p("d")).await.unwrap();
3452        assert!(!td.path().join("d").exists());
3453        h.close().await.unwrap();
3454    }
3455
3456    fn filetime(secs: u64) -> u64 {
3457        system_time_to_filetime(UNIX_EPOCH + Duration::from_secs(secs))
3458    }
3459
3460    #[tokio::test]
3461    async fn creation_time_is_set_where_the_host_can() {
3462        let td = tempdir().unwrap();
3463        let backend = LocalFsBackend::new(td.path()).unwrap();
3464        let h = backend.open(&p("f.txt"), opts_create()).await.unwrap().0;
3465        let before = h.stat().await.unwrap();
3466        let t = filetime(1_557_126_489);
3467        h.set_times(FileTimes {
3468            creation_time: Some(t),
3469            ..FileTimes::default()
3470        })
3471        .await
3472        .unwrap();
3473        let after = h.stat().await.unwrap();
3474        if cfg!(any(windows, target_os = "macos")) {
3475            assert_eq!(after.creation_time, t);
3476        } else {
3477            assert_eq!(after.creation_time, before.creation_time);
3478        }
3479        assert_eq!(after.last_write_time, before.last_write_time);
3480        h.close().await.unwrap();
3481    }
3482
3483    #[tokio::test]
3484    async fn creation_time_does_not_block_the_other_times() {
3485        let td = tempdir().unwrap();
3486        let backend = LocalFsBackend::new(td.path()).unwrap();
3487        let h = backend.open(&p("f.txt"), opts_create()).await.unwrap().0;
3488        let created = filetime(1_557_126_489);
3489        let written = filetime(1_577_934_245);
3490        h.set_times(FileTimes {
3491            creation_time: Some(created),
3492            last_access_time: Some(written),
3493            last_write_time: Some(written),
3494            ..FileTimes::default()
3495        })
3496        .await
3497        .unwrap();
3498        let info = h.stat().await.unwrap();
3499        assert_eq!(info.last_write_time, written);
3500        assert_eq!(info.last_access_time, written);
3501        if cfg!(any(windows, target_os = "macos")) {
3502            assert_eq!(info.creation_time, created);
3503        }
3504        h.close().await.unwrap();
3505    }
3506
3507    #[tokio::test]
3508    async fn attributes_are_stored_where_the_host_keeps_them() {
3509        use crate::backend::{
3510            FILE_ATTRIBUTE_ARCHIVE, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_HIDDEN,
3511            FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_SYSTEM,
3512        };
3513        let td = tempdir().unwrap();
3514        std::fs::create_dir(td.path().join("d")).unwrap();
3515        std::fs::write(td.path().join("f.txt"), b"x").unwrap();
3516        let backend = LocalFsBackend::new(td.path()).unwrap();
3517        async fn listed(backend: &LocalFsBackend, name: &str) -> u32 {
3518            let root = backend
3519                .open(&SmbPath::root(), opts_open_dir())
3520                .await
3521                .unwrap()
3522                .0;
3523            let entries = root.list_dir(None).await.unwrap();
3524            root.close().await.unwrap();
3525            let entry = entries.into_iter().find(|e| e.info.name == name).unwrap();
3526            entry.info.attributes()
3527        }
3528
3529        // A handle opened without attribute access sets them too.
3530        let others = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE;
3531        let h = backend.open(&p("f.txt"), opts_open_ro()).await.unwrap().0;
3532        for (set, windows, unix) in [
3533            (others, others, FILE_ATTRIBUTE_NORMAL),
3534            (
3535                FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN,
3536                FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN,
3537                FILE_ATTRIBUTE_READONLY,
3538            ),
3539            (0, FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_NORMAL),
3540        ] {
3541            h.set_attributes(set).await.unwrap();
3542            let expected = if cfg!(windows) { windows } else { unix };
3543            assert_eq!(h.stat().await.unwrap().attributes(), expected, "{set:#x}");
3544            assert_eq!(listed(&backend, "f.txt").await, expected, "{set:#x} listed");
3545        }
3546        h.close().await.unwrap();
3547
3548        let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
3549        let set = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN;
3550        dir.set_attributes(set).await.unwrap();
3551        let expected = if cfg!(windows) {
3552            FILE_ATTRIBUTE_DIRECTORY | set
3553        } else {
3554            FILE_ATTRIBUTE_DIRECTORY
3555        };
3556        assert_eq!(dir.stat().await.unwrap().attributes(), expected);
3557        assert_eq!(listed(&backend, "d").await, expected);
3558        dir.set_attributes(0).await.unwrap();
3559        assert_eq!(
3560            dir.stat().await.unwrap().attributes(),
3561            FILE_ATTRIBUTE_DIRECTORY
3562        );
3563        dir.close().await.unwrap();
3564    }
3565
3566    #[cfg(unix)]
3567    #[tokio::test]
3568    async fn a_set_that_keeps_the_read_only_state_leaves_the_mode_alone() {
3569        use std::os::unix::fs::MetadataExt as _;
3570        let td = tempdir().unwrap();
3571        let path = td.path().join("f.txt");
3572        std::fs::write(&path, b"x").unwrap();
3573        let backend = LocalFsBackend::new(td.path()).unwrap();
3574        let h = backend.open(&p("f.txt"), opts_open_ro()).await.unwrap().0;
3575        let changed = || {
3576            let md = std::fs::metadata(&path).unwrap();
3577            (md.ctime(), md.ctime_nsec())
3578        };
3579        let before = changed();
3580        std::thread::sleep(Duration::from_millis(20));
3581        h.set_attributes(crate::backend::FILE_ATTRIBUTE_HIDDEN)
3582            .await
3583            .unwrap();
3584        assert_eq!(changed(), before);
3585        h.close().await.unwrap();
3586    }
3587
3588    #[test]
3589    fn filetimes_before_1970_reach_the_host_clock() {
3590        for ft in [
3591            0,
3592            95_616_288_000_000_000,
3593            FILETIME_OFFSET - 1,
3594            FILETIME_OFFSET,
3595        ] {
3596            let t = filetime_to_system_time(ft).unwrap();
3597            assert_eq!(system_time_to_filetime(t), ft);
3598        }
3599        assert_eq!(
3600            filetime_to_system_time(95_616_288_000_000_000),
3601            UNIX_EPOCH.checked_sub(Duration::from_secs(2_082_844_800))
3602        );
3603    }
3604
3605    #[test]
3606    fn filetime_round_trip() {
3607        let now = SystemTime::now();
3608        let ft = system_time_to_filetime(now);
3609        let back = filetime_to_system_time(ft).unwrap();
3610        let delta = now
3611            .duration_since(back)
3612            .or_else(|e| Ok::<_, std::time::SystemTimeError>(e.duration()))
3613            .unwrap();
3614        // 100ns granularity: round-trip should be sub-microsecond.
3615        assert!(delta < Duration::from_micros(1), "delta = {delta:?}");
3616    }
3617
3618    #[test]
3619    fn full_disk_and_quota_map_to_their_statuses() {
3620        let full = io_to_smb(io::ErrorKind::StorageFull.into());
3621        assert_eq!(full.to_nt_status(), crate::ntstatus::STATUS_DISK_FULL);
3622        let quota = io_to_smb(io::ErrorKind::QuotaExceeded.into());
3623        assert_eq!(
3624            quota.to_nt_status(),
3625            crate::ntstatus::STATUS_DISK_QUOTA_EXCEEDED
3626        );
3627    }
3628
3629    #[cfg(unix)]
3630    #[tokio::test]
3631    async fn volume_info_reports_the_host_volume() {
3632        let td = tempdir().unwrap();
3633        let backend = LocalFsBackend::new(td.path()).unwrap();
3634        let info = backend.volume_info().await.unwrap();
3635        let st = rustix::fs::statvfs(td.path()).unwrap();
3636        assert_eq!(info.total_allocation_units, st.f_blocks);
3637        let unit = info.allocation_unit();
3638        assert_eq!(unit, st.f_frsize);
3639        // Free space moves with other activity on the volume.
3640        let free_bytes = info.actual_available_allocation_units * unit;
3641        let host_free = st.f_bfree * st.f_frsize;
3642        assert!(
3643            free_bytes.abs_diff(host_free) <= 64 << 20,
3644            "{free_bytes} vs {host_free}"
3645        );
3646        assert!(info.caller_available_allocation_units <= info.actual_available_allocation_units);
3647        assert_ne!(info, VolumeInfo::default());
3648    }
3649
3650    #[cfg(target_os = "linux")]
3651    #[tokio::test]
3652    async fn listing_leaves_out_names_clients_cannot_open() {
3653        use std::ffi::OsStr;
3654        use std::os::unix::ffi::OsStrExt as _;
3655
3656        let td = tempdir().unwrap();
3657        for name in [
3658            OsStr::new("ok.txt"),
3659            OsStr::new("a:b"),
3660            OsStr::new("star*"),
3661            OsStr::from_bytes(b"bad\xffutf8"),
3662        ] {
3663            std::fs::write(td.path().join(name), b"x").unwrap();
3664        }
3665        let long = "x".repeat(200) + "\u{e9}"; // 202 bytes, 201 UTF-16 units
3666        std::fs::write(td.path().join(&long), b"x").unwrap();
3667
3668        let backend = LocalFsBackend::new(td.path()).unwrap();
3669        let dir = backend
3670            .open(&SmbPath::root(), opts_open_dir())
3671            .await
3672            .unwrap()
3673            .0;
3674        let mut names: Vec<String> = dir
3675            .list_dir(None)
3676            .await
3677            .unwrap()
3678            .into_iter()
3679            .map(|e| e.info.name)
3680            .collect();
3681        names.sort();
3682        let mut expected = vec!["ok.txt".to_string(), long];
3683        expected.sort();
3684        assert_eq!(names, expected);
3685        // Every listed name opens again.
3686        for name in &names {
3687            backend
3688                .open(&p(name), opts_open_ro())
3689                .await
3690                .unwrap()
3691                .0
3692                .close()
3693                .await
3694                .unwrap();
3695        }
3696        dir.close().await.unwrap();
3697    }
3698
3699    #[cfg(target_os = "linux")]
3700    #[tokio::test]
3701    async fn dir_is_empty_counts_unlisted_names() {
3702        let td = tempdir().unwrap();
3703        std::fs::create_dir(td.path().join("d")).unwrap();
3704        let backend = LocalFsBackend::new(td.path()).unwrap();
3705        let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
3706        assert!(dir.dir_is_empty().await.unwrap());
3707        std::fs::write(td.path().join("d").join("a:b"), b"x").unwrap();
3708        assert!(dir.list_dir(None).await.unwrap().is_empty());
3709        assert!(!dir.dir_is_empty().await.unwrap());
3710        dir.close().await.unwrap();
3711    }
3712
3713    #[cfg(unix)]
3714    #[tokio::test]
3715    async fn link_count_reports_hard_links() {
3716        let td = tempdir().unwrap();
3717        std::fs::write(td.path().join("a"), b"x").unwrap();
3718        std::fs::hard_link(td.path().join("a"), td.path().join("b")).unwrap();
3719        std::fs::create_dir_all(td.path().join("d").join("sub")).unwrap();
3720        let backend = LocalFsBackend::new(td.path()).unwrap();
3721
3722        let file = backend.open(&p("a"), opts_open_ro()).await.unwrap().0;
3723        assert_eq!(file.link_count().await.unwrap(), 2);
3724        std::fs::remove_file(td.path().join("a")).unwrap();
3725        std::fs::remove_file(td.path().join("b")).unwrap();
3726        assert_eq!(file.link_count().await.unwrap(), 0);
3727        file.close().await.unwrap();
3728
3729        let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
3730        assert_eq!(dir.link_count().await.unwrap(), 1);
3731        dir.close().await.unwrap();
3732    }
3733
3734    #[cfg(unix)]
3735    #[tokio::test]
3736    async fn listing_reports_symlinks_as_their_targets() {
3737        let td = tempdir().unwrap();
3738        std::fs::create_dir(td.path().join("real")).unwrap();
3739        std::os::unix::fs::symlink("real", td.path().join("link")).unwrap();
3740        std::os::unix::fs::symlink("missing", td.path().join("dangling")).unwrap();
3741        let backend = LocalFsBackend::new(td.path()).unwrap();
3742
3743        let root = backend
3744            .open(&SmbPath::root(), opts_open_dir())
3745            .await
3746            .unwrap()
3747            .0;
3748        let entries = root.list_dir(None).await.unwrap();
3749        let get = |name: &str| {
3750            entries
3751                .iter()
3752                .find(|e| e.info.name == name)
3753                .unwrap_or_else(|| panic!("{name} listed"))
3754                .info
3755                .clone()
3756        };
3757        let link = get("link");
3758        let opened = backend.open(&p("link"), opts_open_ro()).await.unwrap().0;
3759        let stat = opened.stat().await.unwrap();
3760        assert!(link.is_directory);
3761        assert_eq!(link.is_directory, stat.is_directory);
3762        assert_eq!(link.file_index, stat.file_index);
3763        assert!(!get("dangling").is_directory);
3764        opened.close().await.unwrap();
3765        root.close().await.unwrap();
3766    }
3767
3768    /// Makes a FIFO at `path`.
3769    #[cfg(unix)]
3770    pub(in crate::fs) fn mkfifo(path: &Path) {
3771        let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
3772        // SAFETY: `path` is a NUL-terminated path.
3773        assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o644) }, 0);
3774    }
3775
3776    /// Opens the FIFO at `path` for reading and for writing without
3777    /// blocking, and writes to it, so a thread stuck opening, reading or
3778    /// writing it returns.
3779    #[cfg(unix)]
3780    pub(in crate::fs) fn release(path: &Path) {
3781        use std::io::{Read as _, Write as _};
3782        use std::os::unix::fs::OpenOptionsExt as _;
3783        let reader = std::fs::OpenOptions::new()
3784            .read(true)
3785            .custom_flags(libc::O_NONBLOCK)
3786            .open(path);
3787        if let Ok(mut fifo) = std::fs::OpenOptions::new()
3788            .write(true)
3789            .custom_flags(libc::O_NONBLOCK)
3790            .open(path)
3791        {
3792            let _ = fifo.write_all(b"x");
3793        }
3794        if let Ok(mut reader) = reader {
3795            let _ = reader.read(&mut [0; 64]);
3796        }
3797    }
3798
3799    #[cfg(unix)]
3800    #[tokio::test]
3801    async fn a_fifo_or_socket_in_place_of_a_checked_file_fails_as_changed_at_once() {
3802        let td = tempdir().unwrap();
3803        let fifo = td.path().join("fifo");
3804        mkfifo(&fifo);
3805        // A socket fails to open at all; a FIFO opens and is no file.
3806        let _socket = std::os::unix::net::UnixListener::bind(td.path().join("sock")).unwrap();
3807        let root = Arc::new(Dir::open_ambient_dir(td.path(), ambient_authority()).unwrap());
3808        for (name, opts) in [
3809            ("fifo", opts_open_ro()),
3810            ("fifo", opts_open_rw()),
3811            ("sock", opts_open_ro()),
3812        ] {
3813            let dir = Arc::clone(&root);
3814            let opened = spawn_blocking(move || {
3815                let name = Path::new(name);
3816                #[cfg_attr(not(target_os = "linux"), expect(unused_mut))]
3817                let mut results = vec![open_file(&dir, name, opts).map(|_| ())];
3818                #[cfg(target_os = "linux")]
3819                results.push(open_file_nofollow(&dir, name, opts).map(|_| ()));
3820                results
3821            });
3822            let Ok(opened) = tokio::time::timeout(Duration::from_secs(10), opened).await else {
3823                release(&fifo);
3824                panic!("the open of a FIFO blocked");
3825            };
3826            for result in opened.unwrap() {
3827                assert!(result.is_err_and(|e| is_changed(&e)), "{name}");
3828            }
3829        }
3830    }
3831
3832    #[cfg(unix)]
3833    #[tokio::test]
3834    async fn an_opened_file_is_left_in_blocking_mode() {
3835        let td = tempdir().unwrap();
3836        std::fs::write(td.path().join("f"), b"x").unwrap();
3837        let root = Dir::open_ambient_dir(td.path(), ambient_authority()).unwrap();
3838        let (file, _) = open_file(&root, Path::new("f"), opts_open_rw()).unwrap();
3839        let flags = rustix::fs::fcntl_getfl(&file).unwrap();
3840        assert!(!flags.contains(rustix::fs::OFlags::NONBLOCK));
3841        #[cfg(target_os = "linux")]
3842        {
3843            let (file, _) = open_file_nofollow(&root, Path::new("f"), opts_open_rw()).unwrap();
3844            let flags = rustix::fs::fcntl_getfl(&file).unwrap();
3845            assert!(!flags.contains(rustix::fs::OFlags::NONBLOCK));
3846        }
3847    }
3848
3849    #[cfg(unix)]
3850    #[tokio::test]
3851    async fn fifos_and_sockets_are_refused_for_every_intent() {
3852        let td = tempdir().unwrap();
3853        let fifo = td.path().join("fifo");
3854        mkfifo(&fifo);
3855        let _socket = std::os::unix::net::UnixListener::bind(td.path().join("sock")).unwrap();
3856        let backend = LocalFsBackend::new(td.path()).unwrap();
3857        for name in ["fifo", "sock"] {
3858            for intent in [
3859                OpenIntent::Open,
3860                OpenIntent::OpenOrCreate,
3861                OpenIntent::Truncate,
3862                OpenIntent::OverwriteOrCreate,
3863            ] {
3864                for opts in [opts_open_ro(), opts_open_rw()] {
3865                    let (path, opts) = (p(name), OpenOptions { intent, ..opts });
3866                    let open = backend.open(&path, opts);
3867                    let Ok(opened) = tokio::time::timeout(Duration::from_secs(10), open).await
3868                    else {
3869                        release(&fifo);
3870                        panic!("the open of {name} blocked");
3871                    };
3872                    assert!(
3873                        matches!(opened, Err(SmbError::SpecialFile)),
3874                        "{name} {intent:?}"
3875                    );
3876                }
3877            }
3878        }
3879    }
3880
3881    #[cfg(target_os = "linux")]
3882    #[tokio::test]
3883    async fn an_open_against_a_file_lease_fails_as_shared_and_breaks_the_lease() {
3884        use libc::{F_GETLEASE, F_SETLEASE};
3885        let td = tempdir().unwrap();
3886        std::fs::write(td.path().join("f"), b"x").unwrap();
3887        let backend = LocalFsBackend::new(td.path()).unwrap();
3888        for (lease, opts, breaks_to) in [
3889            (libc::F_WRLCK, opts_open_ro(), libc::F_RDLCK),
3890            (libc::F_RDLCK, opts_open_rw(), libc::F_UNLCK),
3891            (
3892                libc::F_RDLCK,
3893                OpenOptions {
3894                    intent: OpenIntent::Truncate,
3895                    ..opts_open_rw()
3896                },
3897                libc::F_UNLCK,
3898            ),
3899        ] {
3900            let holder = std::fs::File::open(td.path().join("f")).unwrap();
3901            let fd = std::os::fd::AsRawFd::as_raw_fd(&holder);
3902            // SAFETY: `fd` is open for the whole block; F_SETOWN 0 sends the
3903            // break signal to no process.
3904            unsafe {
3905                if libc::fcntl(fd, F_SETLEASE, lease) != 0 {
3906                    eprintln!("skipping: no file lease: {}", io::Error::last_os_error());
3907                    return;
3908                }
3909                assert_eq!(libc::fcntl(fd, libc::F_SETOWN, 0), 0);
3910            }
3911            let opened = backend.open(&p("f"), opts).await;
3912            assert!(matches!(opened, Err(SmbError::Sharing)), "{lease}");
3913            // SAFETY: as above.
3914            assert_eq!(
3915                unsafe { libc::fcntl(fd, F_GETLEASE) },
3916                breaks_to,
3917                "breaking"
3918            );
3919            // SAFETY: as above.
3920            assert_eq!(unsafe { libc::fcntl(fd, F_SETLEASE, libc::F_UNLCK) }, 0);
3921            let (file, _) = backend.open(&p("f"), opts).await.unwrap();
3922            file.close().await.unwrap();
3923            drop(holder);
3924        }
3925    }
3926
3927    #[cfg(target_os = "linux")]
3928    mod copy_range {
3929        use super::*;
3930        use crate::tests::data::pattern;
3931        use rustix::io::Errno;
3932
3933        #[tokio::test]
3934        async fn copies_a_range_between_files() {
3935            let td = tempdir().unwrap();
3936            let bytes = pattern(300_000, 0);
3937            std::fs::write(td.path().join("s"), &bytes).unwrap();
3938            std::fs::write(td.path().join("t"), [7u8; 10]).unwrap();
3939            let backend = LocalFsBackend::new(td.path()).unwrap();
3940            let (s, t) = (open(&backend, "s").await, open(&backend, "t").await);
3941            let copied = backend.copy_range(&*s, 1000, &*t, 4, 250_000).await;
3942            assert_eq!(copied.unwrap(), 250_000);
3943            let mut expected = vec![7u8; 4];
3944            expected.extend_from_slice(&bytes[1000..251_000]);
3945            assert_eq!(std::fs::read(td.path().join("t")).unwrap(), expected);
3946        }
3947
3948        #[tokio::test]
3949        async fn stops_at_the_end_of_the_source() {
3950            let td = tempdir().unwrap();
3951            let bytes = pattern(5000, 0);
3952            std::fs::write(td.path().join("s"), &bytes).unwrap();
3953            std::fs::write(td.path().join("t"), []).unwrap();
3954            let backend = LocalFsBackend::new(td.path()).unwrap();
3955            let (s, t) = (open(&backend, "s").await, open(&backend, "t").await);
3956            let copied = backend.copy_range(&*s, 1000, &*t, 0, 10_000).await;
3957            assert_eq!(copied.unwrap(), 4000);
3958            assert_eq!(std::fs::read(td.path().join("t")).unwrap(), bytes[1000..]);
3959            assert_eq!(backend.copy_range(&*s, 6000, &*t, 0, 10).await.unwrap(), 0);
3960        }
3961
3962        #[tokio::test]
3963        async fn a_target_past_its_end_gets_a_gap_of_zeros() {
3964            let td = tempdir().unwrap();
3965            let bytes = pattern(1000, 0);
3966            std::fs::write(td.path().join("s"), &bytes).unwrap();
3967            std::fs::write(td.path().join("t"), [7u8; 10]).unwrap();
3968            let backend = LocalFsBackend::new(td.path()).unwrap();
3969            let (s, t) = (open(&backend, "s").await, open(&backend, "t").await);
3970            assert_eq!(
3971                backend.copy_range(&*s, 0, &*t, 5000, 1000).await.unwrap(),
3972                1000
3973            );
3974            let mut expected = vec![7u8; 10];
3975            expected.resize(5000, 0);
3976            expected.extend_from_slice(&bytes);
3977            assert_eq!(std::fs::read(td.path().join("t")).unwrap(), expected);
3978        }
3979
3980        #[tokio::test]
3981        async fn overlapping_ranges_of_one_file_are_left_to_the_server() {
3982            let td = tempdir().unwrap();
3983            let bytes = pattern(10_000, 0);
3984            std::fs::write(td.path().join("f"), &bytes).unwrap();
3985            let short = pattern(3000, 0);
3986            std::fs::write(td.path().join("short"), &short).unwrap();
3987            let (a, b) = (
3988                LocalFsBackend::new(td.path()).unwrap(),
3989                LocalFsBackend::new(td.path()).unwrap(),
3990            );
3991            let (f, g) = (open(&a, "f").await, open(&b, "f").await);
3992            for (from, to) in [(0, 2048), (2048, 0), (0, 0)] {
3993                let copied = a.copy_range(&*f, from, &*g, to, 8192).await;
3994                assert!(matches!(copied, Err(SmbError::NotSupported)), "{from} {to}");
3995                assert_eq!(std::fs::read(td.path().join("f")).unwrap(), bytes);
3996            }
3997
3998            // The kernel cuts this range at the end of the file, and the
3999            // part left does not overlap.
4000            let (s, r) = (open(&a, "short").await, open(&b, "short").await);
4001            let copied = a.copy_range(&*s, 0, &*r, 3500, 4096).await;
4002            assert!(matches!(copied, Err(SmbError::NotSupported)));
4003            assert_eq!(std::fs::read(td.path().join("short")).unwrap(), short);
4004        }
4005
4006        #[tokio::test]
4007        async fn a_range_of_one_file_that_does_not_overlap_its_target_is_copied() {
4008            let td = tempdir().unwrap();
4009            let bytes = pattern(10_000, 0);
4010            std::fs::write(td.path().join("f"), &bytes).unwrap();
4011            let (a, b) = (
4012                LocalFsBackend::new(td.path()).unwrap(),
4013                LocalFsBackend::new(td.path()).unwrap(),
4014            );
4015            let (f, g) = (open(&a, "f").await, open(&b, "f").await);
4016            assert_eq!(a.copy_range(&*f, 0, &*g, 20_000, 1000).await.unwrap(), 1000);
4017            let mut expected = bytes.clone();
4018            expected.resize(20_000, 0);
4019            expected.extend_from_slice(&bytes[..1000]);
4020            assert_eq!(std::fs::read(td.path().join("f")).unwrap(), expected);
4021        }
4022
4023        /// Some kernels copy across filesystems; others refuse.
4024        #[tokio::test]
4025        async fn a_copy_across_filesystems_is_made_whole_or_left_to_the_server() {
4026            let Some((build, shm)) = crate::tests::filesystems::pair() else {
4027                return;
4028            };
4029            let bytes = pattern(100_000, 0);
4030            std::fs::write(build.path().join("s"), &bytes).unwrap();
4031            std::fs::write(shm.path().join("t"), []).unwrap();
4032            let (from, to) = (
4033                LocalFsBackend::new(build.path()).unwrap(),
4034                LocalFsBackend::new(shm.path()).unwrap(),
4035            );
4036            let (s, t) = (open(&from, "s").await, open(&to, "t").await);
4037            match to.copy_range(&*s, 0, &*t, 0, 100_000).await {
4038                Err(SmbError::NotSupported) => {
4039                    assert!(std::fs::read(shm.path().join("t")).unwrap().is_empty());
4040                }
4041                Ok(copied) => {
4042                    assert_eq!(copied, 100_000);
4043                    assert_eq!(std::fs::read(shm.path().join("t")).unwrap(), bytes);
4044                }
4045                other => panic!("{other:?}"),
4046            }
4047        }
4048
4049        #[tokio::test]
4050        async fn a_handle_of_a_read_only_backend_is_not_copied_to() {
4051            let td = tempdir().unwrap();
4052            std::fs::write(td.path().join("s"), pattern(100, 0)).unwrap();
4053            std::fs::write(td.path().join("t"), []).unwrap();
4054            let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
4055            let (s, t) = (open_ro(&backend, "s").await, open_ro(&backend, "t").await);
4056            let copied = backend.copy_range(&*s, 0, &*t, 0, 100).await;
4057            assert!(matches!(copied, Err(SmbError::AccessDenied)));
4058            assert!(std::fs::read(td.path().join("t")).unwrap().is_empty());
4059        }
4060
4061        #[tokio::test]
4062        async fn handles_that_are_not_files_of_this_backend_are_left_to_the_server() {
4063            let td = tempdir().unwrap();
4064            std::fs::write(td.path().join("f"), pattern(100, 0)).unwrap();
4065            let backend = LocalFsBackend::new(td.path()).unwrap();
4066            let file = open(&backend, "f").await;
4067            let (dir, foreign) = dir_and_foreign(&backend).await;
4068            let copied = backend.copy_range(&*dir, 0, &*file, 0, 10).await;
4069            assert!(matches!(copied, Err(SmbError::NotSupported)), "{copied:?}");
4070            let copied = backend.copy_range(&*file, 0, &*dir, 0, 10).await;
4071            assert!(matches!(copied, Err(SmbError::NotSupported)), "{copied:?}");
4072            let copied = backend.copy_range(&*foreign, 0, &*file, 0, 10).await;
4073            assert!(matches!(copied, Err(SmbError::NotSameDevice)), "{copied:?}");
4074            let copied = backend.copy_range(&*file, 0, &*foreign, 0, 10).await;
4075            assert!(matches!(copied, Err(SmbError::NotSupported)), "{copied:?}");
4076        }
4077
4078        #[test]
4079        fn copy_errors_without_a_kernel_path_are_not_supported() {
4080            for errno in [
4081                Errno::XDEV,
4082                Errno::OPNOTSUPP,
4083                Errno::NOSYS,
4084                Errno::INVAL,
4085                Errno::PERM,
4086                Errno::BADF,
4087            ] {
4088                assert!(
4089                    matches!(copy_error(errno), SmbError::NotSupported),
4090                    "{errno}"
4091                );
4092            }
4093        }
4094    }
4095
4096    #[cfg(any(target_os = "linux", windows))]
4097    mod clone_range {
4098        use super::*;
4099        use crate::tests::data::{allocation_unit, pattern};
4100
4101        /// Whether the filesystem of `dir` is one that cannot clone.
4102        #[cfg(target_os = "linux")]
4103        fn cannot_clone(dir: &Path) -> bool {
4104            const EXT4_MAGIC: i128 = 0xEF53;
4105            const TMPFS_MAGIC: i128 = 0x0102_1994;
4106
4107            let magic = i128::from(rustix::fs::statfs(dir).unwrap().f_type);
4108            matches!(magic, EXT4_MAGIC | TMPFS_MAGIC)
4109        }
4110
4111        /// The name of the file system of the volume of `dir`.
4112        #[cfg(windows)]
4113        fn file_system(dir: &Path) -> String {
4114            let dir = Dir::open_ambient_dir(dir, ambient_authority()).unwrap();
4115            volume::volume_of(&dir).unwrap().1
4116        }
4117
4118        /// Whether the filesystem of `dir` is one that cannot clone.
4119        #[cfg(windows)]
4120        fn cannot_clone(dir: &Path) -> bool {
4121            file_system(dir).eq_ignore_ascii_case("NTFS")
4122        }
4123
4124        #[tokio::test]
4125        async fn clones_a_range_where_the_filesystem_can_and_says_so_where_it_cannot() {
4126            let td = tempdir().unwrap();
4127            let backend = LocalFsBackend::new(td.path()).unwrap();
4128            let unit = allocation_unit(&backend).await as usize;
4129            let bytes = pattern(4 * unit, 0);
4130            std::fs::write(td.path().join("s"), &bytes).unwrap();
4131            std::fs::write(td.path().join("t"), vec![0; 4 * unit]).unwrap();
4132            let (s, t) = (open(&backend, "s").await, open(&backend, "t").await);
4133            let (unit_len, two) = (unit as u64, 2 * unit as u64);
4134            let cloned = backend.clone_range(&*s, unit_len, &*t, two, two).await;
4135            let target = std::fs::read(td.path().join("t")).unwrap();
4136            if backend.capabilities().block_cloning {
4137                cloned.unwrap();
4138                assert_eq!(target[2 * unit..], bytes[unit..3 * unit]);
4139                assert_eq!(target[..2 * unit], vec![0; 2 * unit]);
4140            } else if cannot_clone(td.path()) {
4141                assert!(matches!(cloned, Err(SmbError::NotSupported)), "{cloned:?}");
4142                assert_eq!(target, vec![0; 4 * unit]);
4143            } else {
4144                eprintln!("skipping: {} may clone", td.path().display());
4145            }
4146        }
4147
4148        #[cfg(target_os = "linux")]
4149        #[tokio::test]
4150        async fn an_unaligned_length_is_cloned_only_when_it_ends_both_files() {
4151            let td = tempdir().unwrap();
4152            let backend = LocalFsBackend::new(td.path()).unwrap();
4153            if !backend.capabilities().block_cloning {
4154                eprintln!("skipping: {} does not clone", td.path().display());
4155                return;
4156            }
4157            let unit = allocation_unit(&backend).await as usize;
4158            let size = 3 * unit + 1000;
4159            std::fs::write(td.path().join("s"), pattern(size, 0)).unwrap();
4160            std::fs::write(td.path().join("same"), vec![0; size]).unwrap();
4161            std::fs::write(td.path().join("longer"), vec![0; 4 * unit]).unwrap();
4162            let s = open(&backend, "s").await;
4163            let longer = open(&backend, "longer").await;
4164            let cloned = backend.clone_range(&*s, 0, &*longer, 0, size as u64).await;
4165            assert!(
4166                matches!(cloned, Err(SmbError::InvalidParameter)),
4167                "{cloned:?}"
4168            );
4169            let same = open(&backend, "same").await;
4170            backend
4171                .clone_range(&*s, 0, &*same, 0, size as u64)
4172                .await
4173                .unwrap();
4174            assert_eq!(
4175                std::fs::read(td.path().join("same")).unwrap(),
4176                pattern(size, 0)
4177            );
4178        }
4179
4180        #[cfg(target_os = "linux")]
4181        #[tokio::test]
4182        async fn a_filesystem_that_cannot_clone_reports_no_block_cloning() {
4183            let Some((build, shm)) = crate::tests::filesystems::pair() else {
4184                return;
4185            };
4186            for dir in [build.path(), shm.path()] {
4187                if cannot_clone(dir) {
4188                    let backend = LocalFsBackend::new(dir).unwrap();
4189                    assert!(!backend.capabilities().block_cloning, "{}", dir.display());
4190                } else {
4191                    eprintln!("skipping: {} may clone", dir.display());
4192                }
4193            }
4194        }
4195
4196        #[tokio::test]
4197        async fn a_clone_of_no_bytes_changes_nothing() {
4198            let td = tempdir().unwrap();
4199            std::fs::write(td.path().join("s"), pattern(8192, 0)).unwrap();
4200            std::fs::write(td.path().join("t"), [0u8; 8192]).unwrap();
4201            let backend = LocalFsBackend::new(td.path()).unwrap();
4202            let (s, t) = (open(&backend, "s").await, open(&backend, "t").await);
4203            backend.clone_range(&*s, 0, &*t, 0, 0).await.unwrap();
4204            assert_eq!(std::fs::read(td.path().join("t")).unwrap(), [0; 8192]);
4205        }
4206
4207        #[cfg(target_os = "linux")]
4208        #[tokio::test]
4209        async fn a_clone_across_filesystems_is_refused_with_nothing_changed() {
4210            let Some((build, shm)) = crate::tests::filesystems::pair() else {
4211                return;
4212            };
4213            std::fs::write(build.path().join("s"), pattern(8192, 0)).unwrap();
4214            std::fs::write(shm.path().join("t"), [0u8; 8192]).unwrap();
4215            let (from, to) = (
4216                LocalFsBackend::new(build.path()).unwrap(),
4217                LocalFsBackend::new(shm.path()).unwrap(),
4218            );
4219            let (s, t) = (open(&from, "s").await, open(&to, "t").await);
4220            let cloned = to.clone_range(&*s, 0, &*t, 0, 4096).await;
4221            assert!(matches!(cloned, Err(SmbError::NotSameDevice)), "{cloned:?}");
4222            assert_eq!(std::fs::read(shm.path().join("t")).unwrap(), [0; 8192]);
4223        }
4224
4225        #[tokio::test]
4226        async fn a_read_only_backend_reports_no_block_cloning_and_does_not_clone() {
4227            let td = tempdir().unwrap();
4228            std::fs::write(td.path().join("s"), pattern(8192, 0)).unwrap();
4229            std::fs::write(td.path().join("t"), [0u8; 8192]).unwrap();
4230            let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
4231            assert!(!backend.capabilities().block_cloning);
4232            let (s, t) = (open_ro(&backend, "s").await, open_ro(&backend, "t").await);
4233            let cloned = backend.clone_range(&*s, 0, &*t, 0, 4096).await;
4234            assert!(matches!(cloned, Err(SmbError::AccessDenied)), "{cloned:?}");
4235        }
4236
4237        #[tokio::test]
4238        async fn handles_that_are_not_files_of_this_backend_are_not_cloned() {
4239            let td = tempdir().unwrap();
4240            std::fs::write(td.path().join("f"), pattern(8192, 0)).unwrap();
4241            let backend = LocalFsBackend::new(td.path()).unwrap();
4242            let file = open(&backend, "f").await;
4243            let (dir, foreign) = dir_and_foreign(&backend).await;
4244            let cloned = backend.clone_range(&*foreign, 0, &*file, 0, 4096).await;
4245            assert!(matches!(cloned, Err(SmbError::NotSameDevice)), "{cloned:?}");
4246            for (src, dst) in [(&file, &foreign), (&file, &dir), (&dir, &file)] {
4247                let cloned = backend.clone_range(&**src, 0, &**dst, 0, 4096).await;
4248                assert!(matches!(cloned, Err(SmbError::NotSupported)), "{cloned:?}");
4249            }
4250        }
4251
4252        #[cfg(windows)]
4253        #[tokio::test]
4254        async fn block_cloning_follows_the_file_system_of_the_share_root() {
4255            let td = tempdir().unwrap();
4256            let backend = LocalFsBackend::new(td.path()).unwrap();
4257            let cloning = backend.capabilities().block_cloning;
4258            match file_system(td.path()).to_ascii_uppercase().as_str() {
4259                "NTFS" => assert!(!cloning),
4260                "REFS" => assert!(cloning),
4261                other => eprintln!("skipping: {} is on {other}", td.path().display()),
4262            }
4263        }
4264
4265        #[cfg(target_os = "linux")]
4266        #[test]
4267        fn clone_errors_are_told_apart() {
4268            use rustix::io::Errno;
4269
4270            assert!(matches!(
4271                clone_error(Errno::INVAL),
4272                SmbError::InvalidParameter
4273            ));
4274            assert!(matches!(
4275                clone_error(Errno::OPNOTSUPP),
4276                SmbError::NotSupported
4277            ));
4278        }
4279    }
4280}