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