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, FILE_ATTRIBUTE_ARCHIVE, FILE_ATTRIBUTE_READONLY,
37    FileInfo, FileTimes, Handle, OpenAction, OpenIntent, OpenOptions, ShareBackend,
38};
39use crate::error::{SmbError, SmbResult};
40use crate::path::{SmbPath, same_path};
41use crate::utils::{FILETIME_OFFSET, system_time_to_filetime};
42
43use super::volume;
44use crate::backend::VolumeInfo;
45use crate::path::is_valid_component;
46use crate::wildcard::Pattern;
47
48// ---------------------------------------------------------------------------
49// Backend
50// ---------------------------------------------------------------------------
51
52/// Local-filesystem backend, sandboxed at a single root directory.
53///
54/// Handles set access and write times on every host. The creation time is
55/// set on Windows and macOS; other hosts have no call that sets it, so a
56/// requested creation time is ignored there and the other times still apply.
57/// The host keeps the change time.
58pub struct LocalFsBackend {
59    root: Arc<Dir>,
60    /// Device of the share root; see `file_index`.
61    root_dev: Option<u64>,
62    read_only: bool,
63    /// Case rule of name lookups in the share root.
64    case_sensitive: bool,
65}
66
67impl LocalFsBackend {
68    /// Open `path` as the share root. Errors if the path does not exist or is
69    /// not a directory.
70    pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
71        let dir = Dir::open_ambient_dir(path, ambient_authority())?;
72        let root_dev = file_key(&dir.dir_metadata()?).map(|(dev, _)| dev);
73        let case_sensitive = volume::is_case_sensitive(&dir);
74        Ok(Self {
75            root: Arc::new(dir),
76            root_dev,
77            read_only: false,
78            case_sensitive,
79        })
80    }
81
82    /// Mark the backend as read-only. All write-class opens and writes return
83    /// an access-denied SMB error.
84    #[must_use]
85    pub fn read_only(mut self) -> Self {
86        self.read_only = true;
87        self
88    }
89}
90
91// ---------------------------------------------------------------------------
92// Path translation
93// ---------------------------------------------------------------------------
94
95/// Convert a validated `SmbPath` into a relative `PathBuf` suitable for
96/// `cap_std::fs::Dir` lookups.
97///
98/// `SmbPath` is already validated (no `..`, no forbidden chars, no doubled
99/// separators), so this is purely a join. The empty `SmbPath` (root) yields
100/// `PathBuf::from(".")`, which cap-std accepts for `metadata` etc.
101fn to_rel_path(path: &SmbPath) -> PathBuf {
102    if path.is_root() {
103        return PathBuf::from(".");
104    }
105    let mut out = PathBuf::new();
106    for c in path.components() {
107        out.push(c);
108    }
109    out
110}
111
112// ---------------------------------------------------------------------------
113// Error mapping
114// ---------------------------------------------------------------------------
115
116fn io_to_smb(err: io::Error) -> SmbError {
117    use io::ErrorKind::*;
118    #[cfg(windows)]
119    {
120        const ERROR_SHARING_VIOLATION: i32 = 32;
121        if err.raw_os_error() == Some(ERROR_SHARING_VIOLATION) {
122            return SmbError::Sharing;
123        }
124    }
125    match err.kind() {
126        NotFound => SmbError::NotFound,
127        PermissionDenied => SmbError::AccessDenied,
128        AlreadyExists => SmbError::Exists,
129        DirectoryNotEmpty => SmbError::NotEmpty,
130        IsADirectory => SmbError::IsDirectory,
131        NotADirectory => SmbError::NotADirectory,
132        InvalidInput | InvalidFilename => SmbError::NameInvalid,
133        CrossesDevices => SmbError::NotSameDevice,
134        StorageFull => SmbError::DiskFull,
135        QuotaExceeded => SmbError::QuotaExceeded,
136        _ => SmbError::Io(err),
137    }
138}
139
140/// Convert a `spawn_blocking` join error (panic or cancellation) into
141/// `io::ErrorKind::Other`.
142fn join_to_io(_e: tokio::task::JoinError) -> io::Error {
143    io::Error::other("blocking task panicked or was cancelled")
144}
145
146// ---------------------------------------------------------------------------
147// Host-specific file access
148// ---------------------------------------------------------------------------
149
150// On Windows these also move the file cursor, which nothing here reads.
151
152fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
153    #[cfg(unix)]
154    {
155        std::os::unix::fs::FileExt::read_at(file, buf, offset)
156    }
157    #[cfg(windows)]
158    {
159        std::os::windows::fs::FileExt::seek_read(file, buf, offset)
160    }
161}
162
163fn write_at(file: &std::fs::File, data: &[u8], offset: u64) -> io::Result<usize> {
164    #[cfg(unix)]
165    {
166        std::os::unix::fs::FileExt::write_at(file, data, offset)
167    }
168    #[cfg(windows)]
169    {
170        std::os::windows::fs::FileExt::seek_write(file, data, offset)
171    }
172}
173
174/// Host identity of a file: device and inode number on Unix, volume serial
175/// number and file index on Windows. `None` if `md` does not carry it.
176fn file_key(md: &Metadata) -> Option<(u64, u64)> {
177    #[cfg(unix)]
178    {
179        use cap_std::fs::MetadataExt as _;
180        Some((md.dev(), md.ino()))
181    }
182    #[cfg(windows)]
183    {
184        // The hidden trait returns `None` where `cap_fs_ext::MetadataExt` panics on scan metadata.
185        use cap_primitives::fs::_WindowsByHandle;
186        let volume = _WindowsByHandle::volume_serial_number(md)?;
187        let index = _WindowsByHandle::file_index(md)?;
188        Some((volume.into(), index))
189    }
190}
191
192/// File id for a file with host identity `key`. Files on the share root's
193/// device report the inode (file index on Windows). Files on other mounts
194/// below the root have their device mixed into the id, so equal inodes on
195/// different devices give different ids.
196fn file_index(root_dev: Option<u64>, key: Option<(u64, u64)>) -> u64 {
197    let Some((dev, ino)) = key else {
198        return 0;
199    };
200    if root_dev.is_none_or(|root| root == dev) {
201        return ino;
202    }
203    // splitmix64 finalizer: spreads the device over all 64 bits.
204    let mut x = dev;
205    x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
206    x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
207    ino ^ x ^ (x >> 31)
208}
209
210/// Number of hard links to a file. `None` if `md` does not carry it.
211fn link_count(md: &Metadata) -> Option<u64> {
212    #[cfg(unix)]
213    {
214        use cap_std::fs::MetadataExt as _;
215        Some(md.nlink())
216    }
217    #[cfg(windows)]
218    {
219        cap_primitives::fs::_WindowsByHandle::number_of_links(md).map(u64::from)
220    }
221}
222
223/// Whether an entry, given its metadata read without following a final
224/// symlink, is a directory to the host and is deleted with `remove_dir`. On
225/// Unix that holds for directories only; a symlink to a directory is a plain
226/// link. On Windows it holds for anything with the directory attribute,
227/// which includes directory symlinks and junctions.
228fn is_dir_entry(md: &Metadata) -> bool {
229    #[cfg(unix)]
230    {
231        md.is_dir()
232    }
233    #[cfg(windows)]
234    {
235        const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
236        cap_std::fs::MetadataExt::file_attributes(md) & FILE_ATTRIBUTE_DIRECTORY != 0
237    }
238}
239
240/// Metadata for a directory listing entry, carrying the host file id. On
241/// Windows, `DirEntry::metadata` comes from the directory scan and has no
242/// file index, so the entry is opened for it, falling back to the scan data
243/// when the open fails.
244#[cfg_attr(unix, expect(unused_variables, reason = "dir is used on Windows only"))]
245fn entry_metadata(dir: &Dir, entry: &cap_std::fs::DirEntry) -> io::Result<Metadata> {
246    #[cfg(unix)]
247    {
248        entry.metadata()
249    }
250    #[cfg(windows)]
251    {
252        dir.symlink_metadata(entry.file_name())
253            .or_else(|_| entry.metadata())
254    }
255}
256
257/// Opens the directory `rel` below `root`. On Windows the handle shares
258/// delete access, which `Dir::open_dir` leaves out, and has
259/// `FILE_WRITE_ATTRIBUTES` when `write_attributes` is set.
260#[cfg_attr(
261    unix,
262    expect(unused_variables, reason = "write_attributes is used on Windows only")
263)]
264fn open_dir_handle(root: &Dir, rel: &Path, write_attributes: bool) -> io::Result<Dir> {
265    #[cfg(unix)]
266    {
267        root.open_dir(rel)
268    }
269    #[cfg(windows)]
270    {
271        use cap_primitives::fs::OpenOptionsExt as _;
272        const GENERIC_READ: u32 = 0x8000_0000;
273        const FILE_WRITE_ATTRIBUTES: u32 = 0x0000_0100;
274        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
275
276        let mut opts = CapOpenOptions::new();
277        opts.read(true).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
278        if write_attributes {
279            opts.access_mode(GENERIC_READ | FILE_WRITE_ATTRIBUTES);
280        }
281        let file = root.open_with(rel, &opts)?;
282        if !file.metadata()?.is_dir() {
283            return Err(io::ErrorKind::NotADirectory.into());
284        }
285        Ok(Dir::from_std_file(file.into_std()))
286    }
287}
288
289/// A `File` on the same open directory, for setting its times. On Linux a
290/// `Dir` holds an `O_PATH` descriptor, which cannot change times, so the
291/// directory is opened again through it.
292fn dir_as_file(dir: &Dir) -> io::Result<std::fs::File> {
293    #[cfg(unix)]
294    {
295        Ok(dir.open(".")?.into_std())
296    }
297    #[cfg(windows)]
298    {
299        use std::os::windows::io::AsHandle as _;
300        Ok(dir.as_handle().try_clone_to_owned()?.into())
301    }
302}
303
304/// Sets or clears the read-only state of an open file. On Unix a read-only
305/// file has no write permission bits, and clearing it gives the owner write
306/// permission back.
307fn set_read_only(file: &std::fs::File, read_only: bool) -> io::Result<()> {
308    let mut perms = file.metadata()?.permissions();
309    #[cfg(unix)]
310    {
311        use std::os::unix::fs::PermissionsExt as _;
312        let mode = perms.mode();
313        perms.set_mode(if read_only {
314            mode & !0o222
315        } else {
316            mode | 0o200
317        });
318    }
319    #[cfg(windows)]
320    {
321        perms.set_readonly(read_only);
322    }
323    file.set_permissions(perms)
324}
325
326/// Host times for `times`. The change time is left to the host. Hosts other
327/// than Windows and macOS have no call that sets the creation time, so it is
328/// ignored there.
329fn host_file_times(times: FileTimes) -> SmbResult<std::fs::FileTimes> {
330    let host_time = |ft| filetime_to_system_time(ft).ok_or(SmbError::NotSupported);
331    let mut out = std::fs::FileTimes::new();
332    if let Some(ft) = times.last_write_time {
333        out = out.set_modified(host_time(ft)?);
334    }
335    if let Some(ft) = times.last_access_time {
336        out = out.set_accessed(host_time(ft)?);
337    }
338    #[cfg(any(windows, target_os = "macos"))]
339    if let Some(ft) = times.creation_time {
340        out = set_created(out, host_time(ft)?);
341    }
342    Ok(out)
343}
344
345#[cfg(windows)]
346fn set_created(times: std::fs::FileTimes, t: SystemTime) -> std::fs::FileTimes {
347    use std::os::windows::fs::FileTimesExt as _;
348    times.set_created(t)
349}
350
351#[cfg(target_os = "macos")]
352fn set_created(times: std::fs::FileTimes, t: SystemTime) -> std::fs::FileTimes {
353    use std::os::macos::fs::FileTimesExt as _;
354    times.set_created(t)
355}
356
357// ---------------------------------------------------------------------------
358// FILETIME conversion
359// ---------------------------------------------------------------------------
360
361fn filetime_to_system_time(ft: u64) -> Option<SystemTime> {
362    if ft < FILETIME_OFFSET {
363        return None;
364    }
365    let unix_100ns = ft - FILETIME_OFFSET;
366    let secs = unix_100ns / 10_000_000;
367    let nanos = ((unix_100ns % 10_000_000) * 100) as u32;
368    UNIX_EPOCH.checked_add(Duration::new(secs, nanos))
369}
370
371// ---------------------------------------------------------------------------
372// FileInfo construction
373// ---------------------------------------------------------------------------
374
375fn file_info_from_metadata(name: String, md: &Metadata, root_dev: Option<u64>) -> FileInfo {
376    let len = md.len();
377    let modified = md.modified().ok().map(|t| t.into_std());
378    let accessed = md.accessed().ok().map(|t| t.into_std());
379    let created = md.created().ok().map(|t| t.into_std());
380
381    // A missing timestamp falls back to another available one, then to the
382    // UNIX epoch.
383    let modified = modified
384        .or(created)
385        .or(accessed)
386        .unwrap_or(SystemTime::UNIX_EPOCH);
387    let accessed = accessed.unwrap_or(modified);
388    let created = created.unwrap_or(modified);
389
390    FileInfo {
391        name,
392        end_of_file: len,
393        allocation_size: len,
394        creation_time: system_time_to_filetime(created),
395        last_access_time: system_time_to_filetime(accessed),
396        last_write_time: system_time_to_filetime(modified),
397        change_time: system_time_to_filetime(modified),
398        is_directory: md.is_dir(),
399        read_only: !md.is_dir() && md.permissions().readonly(),
400        file_index: file_index(root_dev, file_key(md)),
401    }
402}
403
404// ---------------------------------------------------------------------------
405// Directory listing
406// ---------------------------------------------------------------------------
407
408/// Entries of `dir` whose names match `pattern`, every entry for `None`.
409/// Names a client could not open again are left out.
410fn list_entries(
411    dir: &Dir,
412    pattern: Option<&str>,
413    root_dev: Option<u64>,
414) -> io::Result<Vec<SmbDirEntry>> {
415    let pattern = pattern
416        .filter(|p| !matches!(*p, "" | "*" | "*.*"))
417        .map(|p| Pattern::new(p, !volume::is_case_sensitive(dir)));
418    let mut out = Vec::new();
419    for entry in dir.entries()? {
420        let entry = entry?;
421        let os_name = entry.file_name();
422        if os_name == "." || os_name == ".." {
423            continue;
424        }
425        let Some(name) = os_name.to_str().filter(|n| is_valid_component(n)) else {
426            debug!(name = ?os_name, "listing leaves out a name clients cannot open");
427            continue;
428        };
429        if pattern.as_ref().is_some_and(|p| !p.matches(name)) {
430            continue;
431        }
432        let md = match listed_metadata(dir, &entry) {
433            Ok(md) => md,
434            // Removed since the directory was read.
435            Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
436            Err(e) => return Err(e),
437        };
438        let info = file_info_from_metadata(name.to_owned(), &md, root_dev);
439        out.push(SmbDirEntry { info });
440    }
441    Ok(out)
442}
443
444/// Metadata of a listed entry as an open of its name sees it: a symlink
445/// reports its target, or itself when the target cannot be reached inside
446/// the share.
447fn listed_metadata(dir: &Dir, entry: &cap_std::fs::DirEntry) -> io::Result<Metadata> {
448    if entry.file_type()?.is_symlink()
449        && let Ok(md) = dir.metadata(entry.file_name())
450    {
451        return Ok(md);
452    }
453    entry_metadata(dir, entry)
454}
455
456/// True if `dir` has no entries besides `.` and `..`.
457fn dir_is_empty(dir: &Dir) -> io::Result<bool> {
458    for entry in dir.entries()? {
459        let name = entry?.file_name();
460        if name != "." && name != ".." {
461            return Ok(false);
462        }
463    }
464    Ok(true)
465}
466
467// ---------------------------------------------------------------------------
468// ShareBackend impl
469// ---------------------------------------------------------------------------
470
471impl LocalFsBackend {
472    /// True if a directory on the way to `path` is missing or is not a
473    /// directory.
474    async fn parent_missing(&self, path: &SmbPath) -> bool {
475        let Some(parent) = path.parent().filter(|p| !p.is_root()) else {
476            return false;
477        };
478        let rel = to_rel_path(&parent);
479        let root = Arc::clone(&self.root);
480        spawn_blocking(move || !root.metadata(&rel).is_ok_and(|md| md.is_dir()))
481            .await
482            .unwrap_or(false)
483    }
484
485    async fn open_entry(
486        &self,
487        path: &SmbPath,
488        opts: OpenOptions,
489    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
490        // 1. Read-only check: any open that requests creation, write access,
491        //    truncation, or overwrite is rejected up front. Pure read opens
492        //    pass through.
493        let writes = opts.write
494            || opts.write_attributes
495            || matches!(
496                opts.intent,
497                OpenIntent::Create
498                    | OpenIntent::OpenOrCreate
499                    | OpenIntent::OverwriteOrCreate
500                    | OpenIntent::Truncate
501            );
502        if self.read_only && writes {
503            return Err(SmbError::AccessDenied);
504        }
505
506        let rel = to_rel_path(path);
507        let root = Arc::clone(&self.root);
508        let read_only = self.read_only;
509        let directory = opts.directory;
510        let non_directory = opts.non_directory;
511        let write_attributes = opts.write_attributes;
512
513        if directory {
514            // Directory CREATE intents: Create / OpenOrCreate / OverwriteOrCreate
515            // imply mkdir; Open / Truncate require existing.
516            let intent = opts.intent;
517            let (dir_handle, action) = spawn_blocking(move || -> io::Result<(Dir, OpenAction)> {
518                let action = match intent {
519                    OpenIntent::Open => OpenAction::Opened,
520                    OpenIntent::Create => {
521                        root.create_dir(&rel)?;
522                        OpenAction::Created
523                    }
524                    OpenIntent::OpenOrCreate => match root.create_dir(&rel) {
525                        Ok(()) => OpenAction::Created,
526                        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => OpenAction::Opened,
527                        Err(e) => return Err(e),
528                    },
529                    OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
530                        // Truncating a directory has no meaning; reject.
531                        return Err(io::Error::from(io::ErrorKind::InvalidInput));
532                    }
533                };
534                Ok((open_dir_handle(&root, &rel, write_attributes)?, action))
535            })
536            .await
537            .map_err(join_to_io)
538            .map_err(io_to_smb)?
539            .map_err(io_to_smb)?;
540
541            let handle: Box<dyn Handle> = Box::new(LocalHandle::Dir {
542                name: file_name_for(path),
543                root_dev: self.root_dev,
544                dir_handle: Arc::new(dir_handle),
545            });
546            return Ok((handle, action));
547        }
548
549        let existing_is_dir = {
550            let root = Arc::clone(&self.root);
551            let rel = rel.clone();
552            spawn_blocking(move || -> io::Result<bool> {
553                match root.metadata(&rel) {
554                    Ok(md) => Ok(md.is_dir()),
555                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
556                    Err(e) => Err(e),
557                }
558            })
559            .await
560            .map_err(join_to_io)
561            .map_err(io_to_smb)?
562            .map_err(io_to_smb)?
563        };
564        if existing_is_dir {
565            if non_directory {
566                return Err(SmbError::IsDirectory);
567            }
568            match opts.intent {
569                OpenIntent::Open | OpenIntent::OpenOrCreate => {
570                    let root = Arc::clone(&self.root);
571                    let rel = rel.clone();
572                    let dir_handle =
573                        spawn_blocking(move || open_dir_handle(&root, &rel, write_attributes))
574                            .await
575                            .map_err(join_to_io)
576                            .map_err(io_to_smb)?
577                            .map_err(io_to_smb)?;
578                    let handle: Box<dyn Handle> = Box::new(LocalHandle::Dir {
579                        name: file_name_for(path),
580                        root_dev: self.root_dev,
581                        dir_handle: Arc::new(dir_handle),
582                    });
583                    return Ok((handle, OpenAction::Opened));
584                }
585                OpenIntent::Create => return Err(SmbError::Exists),
586                OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
587                    return Err(SmbError::IsDirectory);
588                }
589            }
590        }
591
592        // 2. Open the file for the intent.
593        let (cap_file, action) = spawn_blocking(move || open_file(&root, &rel, opts))
594            .await
595            .map_err(join_to_io)
596            .map_err(io_to_smb)?
597            .map_err(io_to_smb)?;
598
599        // Convert to a `std::fs::File`. We only need cap-std for the safe
600        // *open*; once we hold a verified file handle, std's API gives us
601        // `set_times`, `set_len`, `sync_data`, and `FileExt::{read,write}_at`.
602        let std_file: std::fs::File = cap_file.into_std();
603
604        let handle: Box<dyn Handle> = Box::new(LocalHandle::File {
605            name: file_name_for(path),
606            root_dev: self.root_dev,
607            file: Arc::new(std_file),
608            read_only,
609        });
610        Ok((handle, action))
611    }
612}
613
614/// Opens the file `rel` below `root` for `opts.intent`. OPEN_IF opens an
615/// existing file with the access `opts` asks for, so a read-only file opens
616/// for reading.
617fn open_file(
618    root: &Dir,
619    rel: &Path,
620    opts: OpenOptions,
621) -> io::Result<(cap_std::fs::File, OpenAction)> {
622    let existing = existing_file_options(&opts);
623    let mut created = CapOpenOptions::new();
624    created.read(opts.read).write(true).create_new(true);
625    let mut truncated = CapOpenOptions::new();
626    truncated.read(opts.read).write(true).truncate(true);
627    let not_found = |e: &io::Error| e.kind() == io::ErrorKind::NotFound;
628    let exists = |e: &io::Error| e.kind() == io::ErrorKind::AlreadyExists;
629    match opts.intent {
630        OpenIntent::Open => Ok((root.open_with(rel, &existing)?, OpenAction::Opened)),
631        OpenIntent::Create => Ok((root.open_with(rel, &created)?, OpenAction::Created)),
632        OpenIntent::Truncate => Ok((root.open_with(rel, &truncated)?, OpenAction::Overwritten)),
633        // The file can appear or vanish between the two calls, so each pair
634        // is tried a second time.
635        OpenIntent::OpenOrCreate => {
636            let mut attempt = 0;
637            loop {
638                attempt += 1;
639                match root.open_with(rel, &existing) {
640                    Ok(f) => return Ok((f, OpenAction::Opened)),
641                    Err(e) if not_found(&e) => {}
642                    Err(e) => return Err(e),
643                }
644                match root.open_with(rel, &created) {
645                    Ok(f) => return Ok((f, OpenAction::Created)),
646                    Err(e) if exists(&e) && attempt < 2 => {}
647                    Err(e) => return Err(e),
648                }
649            }
650        }
651        OpenIntent::OverwriteOrCreate => {
652            let mut attempt = 0;
653            loop {
654                attempt += 1;
655                match root.open_with(rel, &created) {
656                    Ok(f) => return Ok((f, OpenAction::Created)),
657                    Err(e) if exists(&e) => {}
658                    Err(e) => return Err(e),
659                }
660                match root.open_with(rel, &truncated) {
661                    Ok(f) => return Ok((f, OpenAction::Overwritten)),
662                    Err(e) if not_found(&e) && attempt < 2 => {}
663                    Err(e) => return Err(e),
664                }
665            }
666        }
667    }
668}
669
670/// cap-std options that open an existing file with the access `opts` asks
671/// for.
672fn existing_file_options(opts: &OpenOptions) -> CapOpenOptions {
673    let mut cap_opts = CapOpenOptions::new();
674    cap_opts.read(true).write(opts.write);
675    // Unix sets times and permissions through a read-only descriptor.
676    // Windows needs the access right, which a read-only file grants without
677    // write access.
678    #[cfg(windows)]
679    if opts.write_attributes && !opts.write {
680        use cap_primitives::fs::OpenOptionsExt as _;
681        const GENERIC_READ: u32 = 0x8000_0000;
682        const FILE_WRITE_ATTRIBUTES: u32 = 0x0000_0100;
683        cap_opts.access_mode(GENERIC_READ | FILE_WRITE_ATTRIBUTES);
684    }
685    cap_opts
686}
687
688#[async_trait]
689impl ShareBackend for LocalFsBackend {
690    async fn open(
691        &self,
692        path: &SmbPath,
693        opts: OpenOptions,
694    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
695        let result = self.open_entry(path, opts).await;
696        if matches!(result, Err(SmbError::NotFound | SmbError::NotADirectory))
697            && self.parent_missing(path).await
698        {
699            return Err(SmbError::PathNotFound);
700        }
701        result
702    }
703
704    async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
705        if self.read_only {
706            return Err(SmbError::AccessDenied);
707        }
708        if path.is_root() {
709            // Refusing to delete the share root itself.
710            return Err(SmbError::AccessDenied);
711        }
712        let rel = to_rel_path(path);
713        let root = Arc::clone(&self.root);
714
715        spawn_blocking(move || -> io::Result<()> {
716            // Pick the call from the entry itself: the error `remove_file`
717            // returns for a directory differs between hosts. Neither call
718            // follows a final symlink, so a link is removed as a link.
719            if is_dir_entry(&root.symlink_metadata(&rel)?) {
720                root.remove_dir(&rel)
721            } else {
722                root.remove_file(&rel)
723            }
724        })
725        .await
726        .map_err(join_to_io)
727        .map_err(io_to_smb)?
728        .map_err(io_to_smb)
729    }
730
731    async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()> {
732        if self.read_only {
733            return Err(SmbError::AccessDenied);
734        }
735        if from.is_root() || to.is_root() {
736            return Err(SmbError::NameInvalid);
737        }
738        let same_name = same_path(from, to, self.capabilities().case_sensitive);
739        let from = to_rel_path(from);
740        let to_path = to_rel_path(to);
741        let root = Arc::clone(&self.root);
742
743        let result = spawn_blocking(move || -> io::Result<()> {
744            let from_md = root.symlink_metadata(&from)?;
745            match root.symlink_metadata(&to_path) {
746                Ok(to_md) => {
747                    let from_key = file_key(&from_md);
748                    let same_file = from_key.is_some() && from_key == file_key(&to_md);
749                    // A target that is the source under the same name, such
750                    // as a case-only rename on a case-insensitive host, is
751                    // not a collision.
752                    if !(same_file && same_name) {
753                        if !replace_if_exists {
754                            return Err(io::ErrorKind::AlreadyExists.into());
755                        }
756                        if is_dir_entry(&to_md) {
757                            return Err(io::ErrorKind::PermissionDenied.into());
758                        }
759                    }
760                    // The host leaves both names in place when renaming one
761                    // hard link over another, so the source link is removed.
762                    // A file with one link reached under two spellings is a
763                    // single entry and goes through the rename.
764                    if same_file && !same_name && link_count(&from_md) > Some(1) {
765                        return root.remove_file(&from);
766                    }
767                }
768                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
769                Err(e) => return Err(e),
770            }
771            root.rename(&from, &root, &to_path)
772        })
773        .await
774        .map_err(join_to_io)
775        .map_err(io_to_smb)?
776        .map_err(io_to_smb);
777        if matches!(result, Err(SmbError::NotFound | SmbError::NotADirectory))
778            && self.parent_missing(to).await
779        {
780            return Err(SmbError::PathNotFound);
781        }
782        result
783    }
784
785    fn capabilities(&self) -> BackendCapabilities {
786        BackendCapabilities {
787            is_read_only: self.read_only,
788            case_sensitive: self.case_sensitive,
789        }
790    }
791
792    async fn volume_info(&self) -> SmbResult<VolumeInfo> {
793        let root = Arc::clone(&self.root);
794        let root_dev = self.root_dev;
795        spawn_blocking(move || volume::volume_info(&root, root_dev))
796            .await
797            .map_err(join_to_io)
798            .map_err(io_to_smb)?
799            .map_err(io_to_smb)
800    }
801}
802
803// ---------------------------------------------------------------------------
804// Handle
805// ---------------------------------------------------------------------------
806
807/// Internal handle variant. `File` carries a `std::fs::File` (after cap-std
808/// has done the safe open); `Dir` keeps the `cap_std::fs::Dir` for listing
809/// and setting times.
810enum LocalHandle {
811    File {
812        name: String,
813        root_dev: Option<u64>,
814        file: Arc<std::fs::File>,
815        read_only: bool,
816    },
817    Dir {
818        name: String,
819        root_dev: Option<u64>,
820        dir_handle: Arc<Dir>,
821    },
822}
823
824fn file_name_for(path: &SmbPath) -> String {
825    path.file_name().unwrap_or("").to_string()
826}
827
828#[async_trait]
829impl Handle for LocalHandle {
830    async fn read(&self, offset: u64, len: u32) -> SmbResult<Bytes> {
831        match self {
832            LocalHandle::File { file, .. } => {
833                let file = Arc::clone(file);
834                let n = len as usize;
835                let bytes = spawn_blocking(move || -> io::Result<Bytes> {
836                    let mut buf = vec![0u8; n];
837                    let read = read_at(&file, &mut buf, offset)?;
838                    buf.truncate(read);
839                    Ok(Bytes::from(buf))
840                })
841                .await
842                .map_err(join_to_io)
843                .map_err(io_to_smb)?
844                .map_err(io_to_smb)?;
845                Ok(bytes)
846            }
847            LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
848        }
849    }
850
851    async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32> {
852        self.write_owned(offset, data.to_vec()).await
853    }
854
855    async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
856        match self {
857            LocalHandle::File {
858                file, read_only, ..
859            } => {
860                if *read_only {
861                    return Err(SmbError::AccessDenied);
862                }
863                let file = Arc::clone(file);
864                let written = spawn_blocking(move || write_at(&file, &data, offset))
865                    .await
866                    .map_err(join_to_io)
867                    .map_err(io_to_smb)?
868                    .map_err(io_to_smb)?;
869                Ok(u32::try_from(written).unwrap_or(u32::MAX))
870            }
871            LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
872        }
873    }
874
875    async fn flush(&self) -> SmbResult<()> {
876        match self {
877            LocalHandle::File { file, .. } => {
878                let file = Arc::clone(file);
879                spawn_blocking(move || file.sync_data())
880                    .await
881                    .map_err(join_to_io)
882                    .map_err(io_to_smb)?
883                    .map_err(io_to_smb)
884            }
885            // Flushing a directory is a no-op in SMB semantics.
886            LocalHandle::Dir { .. } => Ok(()),
887        }
888    }
889
890    async fn stat(&self) -> SmbResult<FileInfo> {
891        match self {
892            LocalHandle::File {
893                file,
894                name,
895                root_dev,
896                ..
897            } => {
898                let file = Arc::clone(file);
899                let name = name.clone();
900                let root_dev = *root_dev;
901                spawn_blocking(move || -> io::Result<FileInfo> {
902                    let md = Metadata::from_file(&file)?;
903                    Ok(file_info_from_metadata(name, &md, root_dev))
904                })
905                .await
906                .map_err(join_to_io)
907                .map_err(io_to_smb)?
908                .map_err(io_to_smb)
909            }
910            LocalHandle::Dir {
911                dir_handle,
912                name,
913                root_dev,
914            } => {
915                let dir_handle = Arc::clone(dir_handle);
916                let name = name.clone();
917                let root_dev = *root_dev;
918                spawn_blocking(move || -> io::Result<FileInfo> {
919                    let md = dir_handle.dir_metadata()?;
920                    Ok(file_info_from_metadata(name, &md, root_dev))
921                })
922                .await
923                .map_err(join_to_io)
924                .map_err(io_to_smb)?
925                .map_err(io_to_smb)
926            }
927        }
928    }
929
930    async fn set_times(&self, times: FileTimes) -> SmbResult<()> {
931        let host_times = host_file_times(times)?;
932        match self {
933            LocalHandle::File {
934                file, read_only, ..
935            } => {
936                if *read_only {
937                    return Err(SmbError::AccessDenied);
938                }
939                let file = Arc::clone(file);
940                spawn_blocking(move || file.set_times(host_times))
941                    .await
942                    .map_err(join_to_io)
943                    .map_err(io_to_smb)?
944                    .map_err(io_to_smb)
945            }
946            LocalHandle::Dir { dir_handle, .. } => {
947                let dir_handle = Arc::clone(dir_handle);
948                spawn_blocking(move || dir_as_file(&dir_handle)?.set_times(host_times))
949                    .await
950                    .map_err(join_to_io)
951                    .map_err(io_to_smb)?
952                    .map_err(io_to_smb)
953            }
954        }
955    }
956
957    async fn set_attributes(&self, attributes: u32) -> SmbResult<()> {
958        if attributes & !(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_ARCHIVE) != 0 {
959            return Err(SmbError::NotSupported);
960        }
961        let read_only = attributes & FILE_ATTRIBUTE_READONLY != 0;
962        match self {
963            LocalHandle::File {
964                file,
965                read_only: backend_read_only,
966                ..
967            } => {
968                if *backend_read_only {
969                    return Err(SmbError::AccessDenied);
970                }
971                let file = Arc::clone(file);
972                spawn_blocking(move || set_read_only(&file, read_only))
973                    .await
974                    .map_err(join_to_io)
975                    .map_err(io_to_smb)?
976                    .map_err(io_to_smb)
977            }
978            LocalHandle::Dir { .. } if read_only => Err(SmbError::NotSupported),
979            LocalHandle::Dir { .. } => Ok(()),
980        }
981    }
982
983    async fn truncate(&self, len: u64) -> SmbResult<()> {
984        match self {
985            LocalHandle::File {
986                file, read_only, ..
987            } => {
988                if *read_only {
989                    return Err(SmbError::AccessDenied);
990                }
991                let file = Arc::clone(file);
992                spawn_blocking(move || file.set_len(len))
993                    .await
994                    .map_err(join_to_io)
995                    .map_err(io_to_smb)?
996                    .map_err(io_to_smb)
997            }
998            // Protocol layer rejects truncate on dir handles before this; if
999            // it ever reaches us, surface as NotSupported.
1000            LocalHandle::Dir { .. } => Err(SmbError::NotSupported),
1001        }
1002    }
1003
1004    async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<SmbDirEntry>> {
1005        match self {
1006            LocalHandle::File { .. } => Err(SmbError::NotADirectory),
1007            LocalHandle::Dir {
1008                dir_handle,
1009                root_dev,
1010                ..
1011            } => {
1012                let dir_handle = Arc::clone(dir_handle);
1013                let root_dev = *root_dev;
1014                let pat = pattern.map(|s| s.to_owned());
1015                spawn_blocking(move || list_entries(&dir_handle, pat.as_deref(), root_dev))
1016                    .await
1017                    .map_err(join_to_io)
1018                    .map_err(io_to_smb)?
1019                    .map_err(io_to_smb)
1020            }
1021        }
1022    }
1023
1024    async fn close(self: Box<Self>) -> SmbResult<()> {
1025        // Drop is sufficient: closing the underlying handle is what the OS
1026        // does when the last `Arc` ref goes away. No flush here: SMB CLOSE
1027        // does not imply fsync.
1028        Ok(())
1029    }
1030
1031    /// The host link count of a file. A directory reports one link, as it
1032    /// has one name, or none once it has been removed.
1033    async fn link_count(&self) -> SmbResult<u32> {
1034        let md = match self {
1035            LocalHandle::File { file, .. } => {
1036                let file = Arc::clone(file);
1037                spawn_blocking(move || Metadata::from_file(&file)).await
1038            }
1039            LocalHandle::Dir { dir_handle, .. } => {
1040                let dir_handle = Arc::clone(dir_handle);
1041                spawn_blocking(move || dir_handle.dir_metadata()).await
1042            }
1043        }
1044        .map_err(join_to_io)
1045        .map_err(io_to_smb)?
1046        .map_err(io_to_smb)?;
1047        let links = link_count(&md).map_or(1, |n| u32::try_from(n).unwrap_or(u32::MAX));
1048        Ok(if md.is_dir() { links.min(1) } else { links })
1049    }
1050
1051    async fn dir_is_empty(&self) -> SmbResult<bool> {
1052        match self {
1053            LocalHandle::File { .. } => Err(SmbError::NotADirectory),
1054            LocalHandle::Dir { dir_handle, .. } => {
1055                let dir_handle = Arc::clone(dir_handle);
1056                spawn_blocking(move || dir_is_empty(&dir_handle))
1057                    .await
1058                    .map_err(join_to_io)
1059                    .map_err(io_to_smb)?
1060                    .map_err(io_to_smb)
1061            }
1062        }
1063    }
1064}
1065
1066// ---------------------------------------------------------------------------
1067// Tests
1068// ---------------------------------------------------------------------------
1069
1070#[cfg(test)]
1071mod tests {
1072    use super::*;
1073    use crate::backend::{OpenIntent, OpenOptions};
1074    use crate::path::SmbPath;
1075    use tempfile::tempdir;
1076
1077    fn p(s: &str) -> SmbPath {
1078        s.parse::<SmbPath>().unwrap()
1079    }
1080
1081    fn opts_create() -> OpenOptions {
1082        OpenOptions {
1083            read: true,
1084            write: true,
1085            write_attributes: true,
1086            intent: OpenIntent::Create,
1087            directory: false,
1088            non_directory: false,
1089            delete_on_close: false,
1090        }
1091    }
1092
1093    fn opts_open_rw() -> OpenOptions {
1094        OpenOptions {
1095            read: true,
1096            write: true,
1097            write_attributes: true,
1098            intent: OpenIntent::Open,
1099            directory: false,
1100            non_directory: false,
1101            delete_on_close: false,
1102        }
1103    }
1104
1105    fn opts_open_ro() -> OpenOptions {
1106        OpenOptions {
1107            read: true,
1108            write: false,
1109            write_attributes: false,
1110            intent: OpenIntent::Open,
1111            directory: false,
1112            non_directory: false,
1113            delete_on_close: false,
1114        }
1115    }
1116
1117    fn opts_open_dir() -> OpenOptions {
1118        OpenOptions {
1119            read: true,
1120            write: false,
1121            write_attributes: false,
1122            intent: OpenIntent::Open,
1123            directory: true,
1124            non_directory: false,
1125            delete_on_close: false,
1126        }
1127    }
1128
1129    #[tokio::test]
1130    async fn create_write_read_stat_close() {
1131        let td = tempdir().unwrap();
1132        let backend = LocalFsBackend::new(td.path()).unwrap();
1133
1134        // Create
1135        let h = backend
1136            .open(&p("hello.txt"), opts_create())
1137            .await
1138            .unwrap()
1139            .0;
1140        let n = h.write(0, b"hello world").await.unwrap();
1141        assert_eq!(n, 11);
1142        h.flush().await.unwrap();
1143
1144        // Stat
1145        let info = h.stat().await.unwrap();
1146        assert_eq!(info.name, "hello.txt");
1147        assert_eq!(info.end_of_file, 11);
1148        assert!(!info.is_directory);
1149        assert!(info.last_write_time > 0);
1150        h.close().await.unwrap();
1151
1152        // Reopen for read
1153        let h2 = backend
1154            .open(&p("hello.txt"), opts_open_ro())
1155            .await
1156            .unwrap()
1157            .0;
1158        let bytes = h2.read(0, 1024).await.unwrap();
1159        assert_eq!(&bytes[..], b"hello world");
1160
1161        // Short-read past EOF returns truncated
1162        let bytes = h2.read(6, 1024).await.unwrap();
1163        assert_eq!(&bytes[..], b"world");
1164
1165        // Read past EOF returns empty
1166        let bytes = h2.read(100, 1024).await.unwrap();
1167        assert!(bytes.is_empty());
1168        h2.close().await.unwrap();
1169    }
1170
1171    #[tokio::test]
1172    async fn list_dir_finds_created_file() {
1173        let td = tempdir().unwrap();
1174        let backend = LocalFsBackend::new(td.path()).unwrap();
1175        let h = backend.open(&p("a.txt"), opts_create()).await.unwrap().0;
1176        h.close().await.unwrap();
1177
1178        let dir_h = backend
1179            .open(&SmbPath::root(), opts_open_dir())
1180            .await
1181            .unwrap()
1182            .0;
1183        let entries = dir_h.list_dir(None).await.unwrap();
1184        assert!(entries.iter().any(|e| e.info.name == "a.txt"));
1185        dir_h.close().await.unwrap();
1186    }
1187
1188    #[tokio::test]
1189    async fn read_only_rejects_writes() {
1190        let td = tempdir().unwrap();
1191        // Pre-create a file via a writable backend so we have something to
1192        // attempt to open RW.
1193        {
1194            let writable = LocalFsBackend::new(td.path()).unwrap();
1195            let h = writable.open(&p("x.txt"), opts_create()).await.unwrap().0;
1196            h.close().await.unwrap();
1197        }
1198
1199        let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
1200        assert!(backend.capabilities().is_read_only);
1201
1202        // RW open should be rejected.
1203        let err = backend
1204            .open(&p("x.txt"), opts_open_rw())
1205            .await
1206            .err()
1207            .unwrap();
1208        assert!(matches!(err, SmbError::AccessDenied));
1209
1210        // Create should be rejected.
1211        let err = backend
1212            .open(&p("y.txt"), opts_create())
1213            .await
1214            .err()
1215            .unwrap();
1216        assert!(matches!(err, SmbError::AccessDenied));
1217
1218        // Pure read open is fine; writes through it are rejected.
1219        let h = backend.open(&p("x.txt"), opts_open_ro()).await.unwrap().0;
1220        assert!(matches!(
1221            h.write(0, b"x").await,
1222            Err(SmbError::AccessDenied)
1223        ));
1224        h.close().await.unwrap();
1225
1226        // unlink rejected.
1227        let err = backend.unlink(&p("x.txt")).await.err().unwrap();
1228        assert!(matches!(err, SmbError::AccessDenied));
1229    }
1230
1231    #[tokio::test]
1232    async fn unlink_file_then_nonempty_dir_errors() {
1233        let td = tempdir().unwrap();
1234        let backend = LocalFsBackend::new(td.path()).unwrap();
1235
1236        // Create & remove a file.
1237        let h = backend
1238            .open(&p("doomed.txt"), opts_create())
1239            .await
1240            .unwrap()
1241            .0;
1242        h.close().await.unwrap();
1243        backend.unlink(&p("doomed.txt")).await.unwrap();
1244        assert!(matches!(
1245            backend.unlink(&p("doomed.txt")).await.err().unwrap(),
1246            SmbError::NotFound
1247        ));
1248
1249        // Create a non-empty directory; unlink should fail with NotEmpty.
1250        std::fs::create_dir(td.path().join("dir1")).unwrap();
1251        std::fs::write(td.path().join("dir1").join("inside"), b"x").unwrap();
1252
1253        let err = backend.unlink(&p("dir1")).await.err().unwrap();
1254        assert!(
1255            matches!(err, SmbError::NotEmpty),
1256            "expected NotEmpty, got {err:?}"
1257        );
1258
1259        // Empty it and retry.
1260        std::fs::remove_file(td.path().join("dir1").join("inside")).unwrap();
1261        backend.unlink(&p("dir1")).await.unwrap();
1262    }
1263
1264    #[tokio::test]
1265    async fn rename_within_root() {
1266        let td = tempdir().unwrap();
1267        let backend = LocalFsBackend::new(td.path()).unwrap();
1268
1269        let h = backend.open(&p("old.txt"), opts_create()).await.unwrap().0;
1270        h.write(0, b"data").await.unwrap();
1271        h.close().await.unwrap();
1272
1273        backend
1274            .rename(&p("old.txt"), &p("new.txt"), false)
1275            .await
1276            .unwrap();
1277        assert!(td.path().join("new.txt").exists());
1278        assert!(!td.path().join("old.txt").exists());
1279
1280        // Renaming over an existing target should fail.
1281        let h = backend
1282            .open(&p("other.txt"), opts_create())
1283            .await
1284            .unwrap()
1285            .0;
1286        h.close().await.unwrap();
1287        let err = backend
1288            .rename(&p("other.txt"), &p("new.txt"), false)
1289            .await
1290            .err()
1291            .unwrap();
1292        assert!(matches!(err, SmbError::Exists), "got {err:?}");
1293    }
1294
1295    #[tokio::test]
1296    async fn rename_onto_itself_is_not_a_collision() {
1297        let td = tempdir().unwrap();
1298        std::fs::write(td.path().join("doc.txt"), b"old").unwrap();
1299        let backend = LocalFsBackend::new(td.path()).unwrap();
1300        backend
1301            .rename(&p("doc.txt"), &p("doc.txt"), false)
1302            .await
1303            .unwrap();
1304        assert_eq!(std::fs::read(td.path().join("doc.txt")).unwrap(), b"old");
1305    }
1306
1307    #[cfg(unix)]
1308    #[tokio::test]
1309    async fn rename_between_hard_links_follows_collision_rules() {
1310        let td = tempdir().unwrap();
1311        let root = td.path();
1312        std::fs::write(root.join("a.txt"), b"data").unwrap();
1313        std::fs::hard_link(root.join("a.txt"), root.join("b.txt")).unwrap();
1314        let backend = LocalFsBackend::new(root).unwrap();
1315
1316        let err = backend
1317            .rename(&p("a.txt"), &p("b.txt"), false)
1318            .await
1319            .unwrap_err();
1320        assert!(matches!(err, SmbError::Exists), "got {err:?}");
1321        assert!(root.join("a.txt").exists());
1322
1323        backend
1324            .rename(&p("a.txt"), &p("b.txt"), true)
1325            .await
1326            .unwrap();
1327        assert!(!root.join("a.txt").exists());
1328        assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"data");
1329    }
1330
1331    #[tokio::test]
1332    async fn directory_file_index_is_the_same_for_every_open_and_listing() {
1333        let td = tempdir().unwrap();
1334        std::fs::create_dir(td.path().join("d")).unwrap();
1335        let backend = LocalFsBackend::new(td.path()).unwrap();
1336
1337        let root = backend
1338            .open(&SmbPath::root(), opts_open_dir())
1339            .await
1340            .unwrap()
1341            .0;
1342        let listed = root.list_dir(None).await.unwrap();
1343        let first = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
1344        let second = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
1345        let id = first.stat().await.unwrap().file_index;
1346        assert_ne!(id, 0);
1347        assert_eq!(second.stat().await.unwrap().file_index, id);
1348        let entry = listed.iter().find(|e| e.info.name == "d").unwrap();
1349        assert_eq!(entry.info.file_index, id);
1350    }
1351
1352    #[test]
1353    fn file_index_keeps_root_device_inodes_and_separates_other_devices() {
1354        let root = Some(0x803);
1355        assert_eq!(file_index(root, Some((0x803, 42))), 42);
1356        assert_eq!(file_index(None, Some((0x803, 42))), 42);
1357        assert_eq!(file_index(root, None), 0);
1358        assert_ne!(
1359            file_index(root, Some((0x803, 1))),
1360            file_index(root, Some((0x2b, 1)))
1361        );
1362    }
1363
1364    #[cfg(unix)]
1365    #[tokio::test]
1366    async fn file_index_is_the_inode_on_the_root_device() {
1367        use std::os::unix::fs::MetadataExt as _;
1368
1369        let td = tempdir().unwrap();
1370        std::fs::write(td.path().join("f.txt"), b"x").unwrap();
1371        let backend = LocalFsBackend::new(td.path()).unwrap();
1372        let h = backend.open(&p("f.txt"), opts_open_ro()).await.unwrap().0;
1373        let ino = std::fs::metadata(td.path().join("f.txt")).unwrap().ino();
1374        assert_eq!(h.stat().await.unwrap().file_index, ino);
1375    }
1376
1377    /// Needs mounts below `/` whose roots share an inode number, as procfs,
1378    /// sysfs and tmpfs roots do on Linux.
1379    #[cfg(target_os = "linux")]
1380    #[tokio::test]
1381    async fn file_index_differs_across_mounts_with_equal_inodes() {
1382        use std::os::unix::fs::MetadataExt as _;
1383
1384        let mounts: Vec<_> = ["proc", "sys", "dev", "tmp"]
1385            .into_iter()
1386            .filter_map(|name| {
1387                let md = std::fs::metadata(Path::new("/").join(name)).ok()?;
1388                Some((name, md.dev(), md.ino()))
1389            })
1390            .collect();
1391        let pair = mounts.iter().enumerate().find_map(|(i, a)| {
1392            mounts[i + 1..]
1393                .iter()
1394                .find(|b| a.1 != b.1 && a.2 == b.2)
1395                .map(|b| (a.0, b.0))
1396        });
1397        let Some((a, b)) = pair else {
1398            eprintln!("no two mounts below / share an inode number; skipping");
1399            return;
1400        };
1401        let backend = LocalFsBackend::new("/").unwrap();
1402        let root = backend
1403            .open(&SmbPath::root(), opts_open_dir())
1404            .await
1405            .unwrap()
1406            .0;
1407        let listed = root.list_dir(None).await.unwrap();
1408        let mut ids = Vec::new();
1409        for name in [a, b] {
1410            let h = backend.open(&p(name), opts_open_dir()).await.unwrap().0;
1411            let id = h.stat().await.unwrap().file_index;
1412            let entry = listed.iter().find(|e| e.info.name == name).unwrap();
1413            assert_eq!(entry.info.file_index, id, "{name}");
1414            ids.push(id);
1415        }
1416        assert_ne!(ids[0], ids[1], "{a} and {b}");
1417    }
1418
1419    #[cfg(unix)]
1420    #[tokio::test]
1421    async fn unlink_removes_empty_dirs_and_symlinks_as_links() {
1422        use std::os::unix::fs::symlink;
1423
1424        let td = tempdir().unwrap();
1425        let outside = tempdir().unwrap();
1426        std::fs::write(outside.path().join("keep.txt"), b"x").unwrap();
1427        let root = td.path();
1428        std::fs::create_dir(root.join("empty")).unwrap();
1429        std::fs::create_dir(root.join("target")).unwrap();
1430        std::fs::write(root.join("target").join("inside.txt"), b"x").unwrap();
1431        symlink(root.join("target"), root.join("link_in")).unwrap();
1432        symlink(outside.path(), root.join("link_out")).unwrap();
1433        symlink(root.join("missing"), root.join("dangling")).unwrap();
1434        let backend = LocalFsBackend::new(root).unwrap();
1435
1436        backend.unlink(&p("empty")).await.unwrap();
1437        assert!(!root.join("empty").exists());
1438
1439        for link in ["link_in", "link_out", "dangling"] {
1440            backend.unlink(&p(link)).await.unwrap();
1441            assert!(root.join(link).symlink_metadata().is_err(), "{link}");
1442        }
1443        assert!(root.join("target").join("inside.txt").exists());
1444        assert!(outside.path().join("keep.txt").exists());
1445    }
1446
1447    #[test]
1448    fn cross_device_error_maps_to_not_same_device() {
1449        assert!(matches!(
1450            io_to_smb(io::ErrorKind::CrossesDevices.into()),
1451            SmbError::NotSameDevice
1452        ));
1453    }
1454
1455    #[tokio::test]
1456    async fn list_dir_pattern_matching() {
1457        let td = tempdir().unwrap();
1458        let backend = LocalFsBackend::new(td.path()).unwrap();
1459
1460        for name in ["a.txt", "b.txt", "c.log", "README"] {
1461            let h = backend.open(&p(name), opts_create()).await.unwrap().0;
1462            h.close().await.unwrap();
1463        }
1464
1465        let dir_h = backend
1466            .open(&SmbPath::root(), opts_open_dir())
1467            .await
1468            .unwrap()
1469            .0;
1470
1471        let txts = dir_h.list_dir(Some("*.txt")).await.unwrap();
1472        let names: Vec<_> = txts.iter().map(|e| e.info.name.as_str()).collect();
1473        assert_eq!(names.len(), 2, "expected 2 .txt files, got {names:?}");
1474        assert!(names.contains(&"a.txt"));
1475        assert!(names.contains(&"b.txt"));
1476
1477        // Single-char wildcard.
1478        let one = dir_h.list_dir(Some("?.log")).await.unwrap();
1479        let names: Vec<_> = one.iter().map(|e| e.info.name.as_str()).collect();
1480        assert_eq!(names, vec!["c.log"]);
1481
1482        // Case follows the host's lookup rule.
1483        let any_txt = dir_h.list_dir(Some("*.TXT")).await.unwrap();
1484        let expected = if backend.capabilities().case_sensitive {
1485            0
1486        } else {
1487            2
1488        };
1489        assert_eq!(any_txt.len(), expected);
1490
1491        // "*" matches everything.
1492        let all = dir_h.list_dir(Some("*")).await.unwrap();
1493        assert_eq!(all.len(), 4);
1494
1495        dir_h.close().await.unwrap();
1496    }
1497
1498    #[cfg(windows)]
1499    #[test]
1500    fn sharing_violation_maps_to_sharing() {
1501        const ERROR_SHARING_VIOLATION: i32 = 32;
1502        assert!(matches!(
1503            io_to_smb(io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)),
1504            SmbError::Sharing
1505        ));
1506    }
1507
1508    #[tokio::test]
1509    async fn directory_unlinks_while_open() {
1510        let td = tempdir().unwrap();
1511        std::fs::create_dir(td.path().join("d")).unwrap();
1512        let backend = LocalFsBackend::new(td.path()).unwrap();
1513        let h = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
1514        backend.unlink(&p("d")).await.unwrap();
1515        assert!(!td.path().join("d").exists());
1516        h.close().await.unwrap();
1517    }
1518
1519    fn filetime(secs: u64) -> u64 {
1520        system_time_to_filetime(UNIX_EPOCH + Duration::from_secs(secs))
1521    }
1522
1523    #[tokio::test]
1524    async fn creation_time_is_set_where_the_host_can() {
1525        let td = tempdir().unwrap();
1526        let backend = LocalFsBackend::new(td.path()).unwrap();
1527        let h = backend.open(&p("f.txt"), opts_create()).await.unwrap().0;
1528        let before = h.stat().await.unwrap();
1529        let t = filetime(1_557_126_489);
1530        h.set_times(FileTimes {
1531            creation_time: Some(t),
1532            ..FileTimes::default()
1533        })
1534        .await
1535        .unwrap();
1536        let after = h.stat().await.unwrap();
1537        if cfg!(any(windows, target_os = "macos")) {
1538            assert_eq!(after.creation_time, t);
1539        } else {
1540            assert_eq!(after.creation_time, before.creation_time);
1541        }
1542        assert_eq!(after.last_write_time, before.last_write_time);
1543        h.close().await.unwrap();
1544    }
1545
1546    #[tokio::test]
1547    async fn creation_time_does_not_block_the_other_times() {
1548        let td = tempdir().unwrap();
1549        let backend = LocalFsBackend::new(td.path()).unwrap();
1550        let h = backend.open(&p("f.txt"), opts_create()).await.unwrap().0;
1551        let created = filetime(1_557_126_489);
1552        let written = filetime(1_577_934_245);
1553        h.set_times(FileTimes {
1554            creation_time: Some(created),
1555            last_access_time: Some(written),
1556            last_write_time: Some(written),
1557            ..FileTimes::default()
1558        })
1559        .await
1560        .unwrap();
1561        let info = h.stat().await.unwrap();
1562        assert_eq!(info.last_write_time, written);
1563        assert_eq!(info.last_access_time, written);
1564        if cfg!(any(windows, target_os = "macos")) {
1565            assert_eq!(info.creation_time, created);
1566        }
1567        h.close().await.unwrap();
1568    }
1569
1570    #[tokio::test]
1571    async fn unsupported_attributes_are_rejected() {
1572        let td = tempdir().unwrap();
1573        std::fs::create_dir(td.path().join("d")).unwrap();
1574        let backend = LocalFsBackend::new(td.path()).unwrap();
1575        let h = backend.open(&p("f.txt"), opts_create()).await.unwrap().0;
1576        assert!(matches!(
1577            h.set_attributes(0x2).await,
1578            Err(SmbError::NotSupported)
1579        ));
1580        h.close().await.unwrap();
1581
1582        let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
1583        assert!(matches!(
1584            dir.set_attributes(FILE_ATTRIBUTE_READONLY).await,
1585            Err(SmbError::NotSupported)
1586        ));
1587        dir.set_attributes(0).await.unwrap();
1588        dir.close().await.unwrap();
1589    }
1590
1591    #[test]
1592    fn filetime_round_trip() {
1593        let now = SystemTime::now();
1594        let ft = system_time_to_filetime(now);
1595        let back = filetime_to_system_time(ft).unwrap();
1596        let delta = now
1597            .duration_since(back)
1598            .or_else(|e| Ok::<_, std::time::SystemTimeError>(e.duration()))
1599            .unwrap();
1600        // 100ns granularity: round-trip should be sub-microsecond.
1601        assert!(delta < Duration::from_micros(1), "delta = {delta:?}");
1602    }
1603
1604    #[test]
1605    fn full_disk_and_quota_map_to_their_statuses() {
1606        let full = io_to_smb(io::ErrorKind::StorageFull.into());
1607        assert_eq!(full.to_nt_status(), crate::ntstatus::STATUS_DISK_FULL);
1608        let quota = io_to_smb(io::ErrorKind::QuotaExceeded.into());
1609        assert_eq!(
1610            quota.to_nt_status(),
1611            crate::ntstatus::STATUS_DISK_QUOTA_EXCEEDED
1612        );
1613    }
1614
1615    #[cfg(unix)]
1616    #[tokio::test]
1617    async fn volume_info_reports_the_host_volume() {
1618        let td = tempdir().unwrap();
1619        let backend = LocalFsBackend::new(td.path()).unwrap();
1620        let info = backend.volume_info().await.unwrap();
1621        let st = rustix::fs::statvfs(td.path()).unwrap();
1622        assert_eq!(info.total_allocation_units, st.f_blocks);
1623        let unit = u64::from(info.sectors_per_allocation_unit) * u64::from(info.bytes_per_sector);
1624        assert_eq!(unit, st.f_frsize);
1625        // Free space moves with other activity on the volume.
1626        let free_bytes = info.actual_available_allocation_units * unit;
1627        let host_free = st.f_bfree * st.f_frsize;
1628        assert!(
1629            free_bytes.abs_diff(host_free) <= 64 << 20,
1630            "{free_bytes} vs {host_free}"
1631        );
1632        assert!(info.caller_available_allocation_units <= info.actual_available_allocation_units);
1633        assert_ne!(info, VolumeInfo::default());
1634    }
1635
1636    #[cfg(target_os = "linux")]
1637    #[tokio::test]
1638    async fn listing_leaves_out_names_clients_cannot_open() {
1639        use std::ffi::OsStr;
1640        use std::os::unix::ffi::OsStrExt as _;
1641
1642        let td = tempdir().unwrap();
1643        for name in [
1644            OsStr::new("ok.txt"),
1645            OsStr::new("a:b"),
1646            OsStr::new("star*"),
1647            OsStr::from_bytes(b"bad\xffutf8"),
1648        ] {
1649            std::fs::write(td.path().join(name), b"x").unwrap();
1650        }
1651        let long = "x".repeat(200) + "\u{e9}"; // 202 bytes, 201 UTF-16 units
1652        std::fs::write(td.path().join(&long), b"x").unwrap();
1653
1654        let backend = LocalFsBackend::new(td.path()).unwrap();
1655        let dir = backend
1656            .open(&SmbPath::root(), opts_open_dir())
1657            .await
1658            .unwrap()
1659            .0;
1660        let mut names: Vec<String> = dir
1661            .list_dir(None)
1662            .await
1663            .unwrap()
1664            .into_iter()
1665            .map(|e| e.info.name)
1666            .collect();
1667        names.sort();
1668        let mut expected = vec!["ok.txt".to_string(), long];
1669        expected.sort();
1670        assert_eq!(names, expected);
1671        // Every listed name opens again.
1672        for name in &names {
1673            backend
1674                .open(&p(name), opts_open_ro())
1675                .await
1676                .unwrap()
1677                .0
1678                .close()
1679                .await
1680                .unwrap();
1681        }
1682        dir.close().await.unwrap();
1683    }
1684
1685    #[cfg(target_os = "linux")]
1686    #[tokio::test]
1687    async fn dir_is_empty_counts_unlisted_names() {
1688        let td = tempdir().unwrap();
1689        std::fs::create_dir(td.path().join("d")).unwrap();
1690        let backend = LocalFsBackend::new(td.path()).unwrap();
1691        let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
1692        assert!(dir.dir_is_empty().await.unwrap());
1693        std::fs::write(td.path().join("d").join("a:b"), b"x").unwrap();
1694        assert!(dir.list_dir(None).await.unwrap().is_empty());
1695        assert!(!dir.dir_is_empty().await.unwrap());
1696        dir.close().await.unwrap();
1697    }
1698
1699    #[cfg(unix)]
1700    #[tokio::test]
1701    async fn link_count_reports_hard_links() {
1702        let td = tempdir().unwrap();
1703        std::fs::write(td.path().join("a"), b"x").unwrap();
1704        std::fs::hard_link(td.path().join("a"), td.path().join("b")).unwrap();
1705        std::fs::create_dir_all(td.path().join("d").join("sub")).unwrap();
1706        let backend = LocalFsBackend::new(td.path()).unwrap();
1707
1708        let file = backend.open(&p("a"), opts_open_ro()).await.unwrap().0;
1709        assert_eq!(file.link_count().await.unwrap(), 2);
1710        std::fs::remove_file(td.path().join("a")).unwrap();
1711        std::fs::remove_file(td.path().join("b")).unwrap();
1712        assert_eq!(file.link_count().await.unwrap(), 0);
1713        file.close().await.unwrap();
1714
1715        let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap().0;
1716        assert_eq!(dir.link_count().await.unwrap(), 1);
1717        dir.close().await.unwrap();
1718    }
1719
1720    #[cfg(unix)]
1721    #[tokio::test]
1722    async fn listing_reports_symlinks_as_their_targets() {
1723        let td = tempdir().unwrap();
1724        std::fs::create_dir(td.path().join("real")).unwrap();
1725        std::os::unix::fs::symlink("real", td.path().join("link")).unwrap();
1726        std::os::unix::fs::symlink("missing", td.path().join("dangling")).unwrap();
1727        let backend = LocalFsBackend::new(td.path()).unwrap();
1728
1729        let root = backend
1730            .open(&SmbPath::root(), opts_open_dir())
1731            .await
1732            .unwrap()
1733            .0;
1734        let entries = root.list_dir(None).await.unwrap();
1735        let get = |name: &str| {
1736            entries
1737                .iter()
1738                .find(|e| e.info.name == name)
1739                .unwrap_or_else(|| panic!("{name} listed"))
1740                .info
1741                .clone()
1742        };
1743        let link = get("link");
1744        let opened = backend.open(&p("link"), opts_open_ro()).await.unwrap().0;
1745        let stat = opened.stat().await.unwrap();
1746        assert!(link.is_directory);
1747        assert_eq!(link.is_directory, stat.is_directory);
1748        assert_eq!(link.file_index, stat.file_index);
1749        assert!(!get("dangling").is_directory);
1750        opened.close().await.unwrap();
1751        root.close().await.unwrap();
1752    }
1753}