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