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