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//! Per the v1 design (spec §3.4) this backend is intentionally minimal:
10//!
11//! - Sync FS calls are wrapped in `tokio::task::spawn_blocking` so the async
12//!   `ShareBackend`/`Handle` methods integrate cleanly with the dispatcher.
13//! - `read_only()` flips a flag that makes write-class opens reject early
14//!   with `SmbError::AccessDenied`.
15//! - DOS-style glob matching for `list_dir` is handled here (case-insensitive,
16//!   `?` and `*`), since cap-std only provides raw `entries()`.
17
18use std::io;
19use std::os::unix::fs::FileExt as _;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22use std::time::{Duration, SystemTime, UNIX_EPOCH};
23
24use async_trait::async_trait;
25use bytes::Bytes;
26use cap_std::ambient_authority;
27use cap_std::fs::{Dir, OpenOptions as CapOpenOptions};
28use tokio::task::spawn_blocking;
29
30use crate::backend::{
31    BackendCapabilities, DirEntry as SmbDirEntry, FileInfo, FileTimes, Handle, OpenIntent,
32    OpenOptions, ShareBackend,
33};
34use crate::error::{SmbError, SmbResult};
35use crate::path::SmbPath;
36
37// ---------------------------------------------------------------------------
38// Backend
39// ---------------------------------------------------------------------------
40
41/// Local-filesystem backend, sandboxed at a single root directory.
42///
43/// Cheap to clone: internally an `Arc<cap_std::fs::Dir>` plus a flag.
44pub struct LocalFsBackend {
45    root: Arc<Dir>,
46    read_only: bool,
47}
48
49impl LocalFsBackend {
50    /// Open `path` as the share root. Errors if the path does not exist or is
51    /// not a directory.
52    pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
53        let dir = Dir::open_ambient_dir(path, ambient_authority())?;
54        Ok(Self {
55            root: Arc::new(dir),
56            read_only: false,
57        })
58    }
59
60    /// Mark the backend as read-only. All write-class opens and writes return
61    /// an access-denied SMB error.
62    #[must_use]
63    pub fn read_only(mut self) -> Self {
64        self.read_only = true;
65        self
66    }
67}
68
69// ---------------------------------------------------------------------------
70// Path translation
71// ---------------------------------------------------------------------------
72
73/// Convert a validated `SmbPath` into a relative `PathBuf` suitable for
74/// `cap_std::fs::Dir` lookups.
75///
76/// `SmbPath` is already validated (no `..`, no forbidden chars, no doubled
77/// separators), so this is purely a join. The empty `SmbPath` (root) yields
78/// `PathBuf::from(".")` — cap-std accepts this for `metadata` etc.
79fn to_rel_path(path: &SmbPath) -> PathBuf {
80    if path.is_root() {
81        return PathBuf::from(".");
82    }
83    let mut out = PathBuf::new();
84    for c in path.components() {
85        out.push(c);
86    }
87    out
88}
89
90// ---------------------------------------------------------------------------
91// Error mapping
92// ---------------------------------------------------------------------------
93
94fn io_to_smb(err: io::Error) -> SmbError {
95    use io::ErrorKind::*;
96    match err.kind() {
97        NotFound => SmbError::NotFound,
98        PermissionDenied => SmbError::AccessDenied,
99        AlreadyExists => SmbError::Exists,
100        DirectoryNotEmpty => SmbError::NotEmpty,
101        IsADirectory => SmbError::IsDirectory,
102        NotADirectory => SmbError::NotADirectory,
103        InvalidInput | InvalidFilename => SmbError::NameInvalid,
104        _ => SmbError::Io(err),
105    }
106}
107
108/// Convert a panic from `spawn_blocking` into an `io::Error`. Panics in the
109/// blocking pool are exotic; we surface them as a generic `Other` rather than
110/// re-panicking on the async side.
111fn join_to_io(_e: tokio::task::JoinError) -> io::Error {
112    io::Error::other("blocking task panicked or was cancelled")
113}
114
115// ---------------------------------------------------------------------------
116// FILETIME conversion
117// ---------------------------------------------------------------------------
118
119/// Number of 100-nanosecond intervals between 1601-01-01 (Windows FILETIME
120/// epoch) and 1970-01-01 (UNIX epoch).
121const FILETIME_OFFSET: u64 = 116_444_736_000_000_000;
122
123fn system_time_to_filetime(t: SystemTime) -> u64 {
124    match t.duration_since(UNIX_EPOCH) {
125        Ok(d) => FILETIME_OFFSET + (d.as_secs() * 10_000_000) + u64::from(d.subsec_nanos() / 100),
126        Err(_) => 0,
127    }
128}
129
130fn filetime_to_system_time(ft: u64) -> Option<SystemTime> {
131    if ft < FILETIME_OFFSET {
132        return None;
133    }
134    let unix_100ns = ft - FILETIME_OFFSET;
135    let secs = unix_100ns / 10_000_000;
136    let nanos = ((unix_100ns % 10_000_000) * 100) as u32;
137    UNIX_EPOCH.checked_add(Duration::new(secs, nanos))
138}
139
140// ---------------------------------------------------------------------------
141// FileInfo construction
142// ---------------------------------------------------------------------------
143
144fn file_info_from_metadata(name: String, md: &cap_std::fs::Metadata) -> FileInfo {
145    let len = md.len();
146    let modified = md.modified().ok().map(|t| t.into_std());
147    let accessed = md.accessed().ok().map(|t| t.into_std());
148    let created = md.created().ok().map(|t| t.into_std());
149
150    // Fall back: if a particular timestamp isn't available on the platform,
151    // use whichever timestamp is available, then `now()` as last resort. SMB
152    // clients tolerate equal timestamps fine.
153    let modified = modified
154        .or(created)
155        .or(accessed)
156        .unwrap_or(SystemTime::UNIX_EPOCH);
157    let accessed = accessed.unwrap_or(modified);
158    let created = created.unwrap_or(modified);
159
160    FileInfo {
161        name,
162        end_of_file: len,
163        allocation_size: len,
164        creation_time: system_time_to_filetime(created),
165        last_access_time: system_time_to_filetime(accessed),
166        last_write_time: system_time_to_filetime(modified),
167        change_time: system_time_to_filetime(modified),
168        is_directory: md.is_dir(),
169        // `cap-std` does not expose a stable inode-style identifier in its
170        // public API; the dispatcher substitutes the FileId where needed.
171        file_index: 0,
172    }
173}
174
175// ---------------------------------------------------------------------------
176// DOS glob matching
177// ---------------------------------------------------------------------------
178
179/// Match `name` against a DOS-style pattern. `?` matches any single char,
180/// `*` matches any sequence (possibly empty). Comparison is case-insensitive
181/// (ASCII fold) — sufficient for the v1 use-case where names are validated to
182/// be free of weird Unicode tricks.
183fn glob_match(pattern: &str, name: &str) -> bool {
184    // Walk both strings as char vectors so `?` matches a char rather than a
185    // byte, without going through grapheme territory.
186    let p: Vec<char> = pattern.chars().collect();
187    let n: Vec<char> = name.chars().collect();
188    glob_match_inner(&p, &n)
189}
190
191fn glob_match_inner(p: &[char], n: &[char]) -> bool {
192    let mut pi = 0usize;
193    let mut ni = 0usize;
194    let mut star: Option<(usize, usize)> = None; // (pi after '*', ni at the time)
195
196    while ni < n.len() {
197        if pi < p.len() && (p[pi] == '?' || ascii_eq_ci(p[pi], n[ni])) {
198            pi += 1;
199            ni += 1;
200        } else if pi < p.len() && p[pi] == '*' {
201            star = Some((pi + 1, ni));
202            pi += 1;
203        } else if let Some((sp, sn)) = star {
204            pi = sp;
205            ni = sn + 1;
206            star = Some((sp, sn + 1));
207        } else {
208            return false;
209        }
210    }
211    while pi < p.len() && p[pi] == '*' {
212        pi += 1;
213    }
214    pi == p.len()
215}
216
217fn ascii_eq_ci(a: char, b: char) -> bool {
218    a.eq_ignore_ascii_case(&b)
219}
220
221// ---------------------------------------------------------------------------
222// ShareBackend impl
223// ---------------------------------------------------------------------------
224
225#[async_trait]
226impl ShareBackend for LocalFsBackend {
227    async fn open(&self, path: &SmbPath, opts: OpenOptions) -> SmbResult<Box<dyn Handle>> {
228        // 1. Read-only check: any open that requests creation, write access,
229        //    truncation, or overwrite is rejected up front. Pure read opens
230        //    pass through.
231        let writes = opts.write
232            || matches!(
233                opts.intent,
234                OpenIntent::Create
235                    | OpenIntent::OpenOrCreate
236                    | OpenIntent::OverwriteOrCreate
237                    | OpenIntent::Truncate
238            );
239        if self.read_only && writes {
240            return Err(SmbError::AccessDenied);
241        }
242
243        let rel = to_rel_path(path);
244        let root = Arc::clone(&self.root);
245        let read_only = self.read_only;
246        let directory = opts.directory;
247        let non_directory = opts.non_directory;
248
249        // For directories, cap-std exposes `open_dir` separately; we don't
250        // need an OpenOptions translation in that case.
251        if directory {
252            // Directory CREATE intents: Create / OpenOrCreate / OverwriteOrCreate
253            // imply mkdir; Open / Truncate require existing.
254            let intent = opts.intent;
255            let dir_handle = spawn_blocking(move || -> io::Result<Dir> {
256                match intent {
257                    OpenIntent::Open => root.open_dir(&rel),
258                    OpenIntent::Create => {
259                        root.create_dir(&rel)?;
260                        root.open_dir(&rel)
261                    }
262                    OpenIntent::OpenOrCreate => {
263                        if !root.exists(&rel) {
264                            root.create_dir(&rel)?;
265                        }
266                        root.open_dir(&rel)
267                    }
268                    OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
269                        // Truncating a directory has no meaning; reject.
270                        Err(io::Error::from(io::ErrorKind::InvalidInput))
271                    }
272                }
273            })
274            .await
275            .map_err(join_to_io)
276            .map_err(io_to_smb)?
277            .map_err(io_to_smb)?;
278
279            return Ok(Box::new(LocalHandle::Dir {
280                name: file_name_for(path),
281                dir_handle: Arc::new(dir_handle),
282            }));
283        }
284
285        let existing_is_dir = {
286            let root = Arc::clone(&self.root);
287            let rel = rel.clone();
288            spawn_blocking(move || -> io::Result<bool> {
289                match root.metadata(&rel) {
290                    Ok(md) => Ok(md.is_dir()),
291                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
292                    Err(e) => Err(e),
293                }
294            })
295            .await
296            .map_err(join_to_io)
297            .map_err(io_to_smb)?
298            .map_err(io_to_smb)?
299        };
300        if existing_is_dir {
301            if non_directory {
302                return Err(SmbError::IsDirectory);
303            }
304            match opts.intent {
305                OpenIntent::Open | OpenIntent::OpenOrCreate => {
306                    let root = Arc::clone(&self.root);
307                    let rel = rel.clone();
308                    let dir_handle = spawn_blocking(move || root.open_dir(&rel))
309                        .await
310                        .map_err(join_to_io)
311                        .map_err(io_to_smb)?
312                        .map_err(io_to_smb)?;
313                    return Ok(Box::new(LocalHandle::Dir {
314                        name: file_name_for(path),
315                        dir_handle: Arc::new(dir_handle),
316                    }));
317                }
318                OpenIntent::Create => return Err(SmbError::Exists),
319                OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
320                    return Err(SmbError::IsDirectory);
321                }
322            }
323        }
324
325        // 2. Translate OpenIntent → cap-std OpenOptions.
326        let mut cap_opts = CapOpenOptions::new();
327        match opts.intent {
328            OpenIntent::Open => {
329                cap_opts.read(true).write(opts.write);
330            }
331            OpenIntent::Create => {
332                cap_opts.read(opts.read).write(true).create_new(true);
333            }
334            OpenIntent::Truncate => {
335                cap_opts.read(opts.read).write(true).truncate(true);
336            }
337            OpenIntent::OpenOrCreate => {
338                cap_opts.read(opts.read).write(true).create(true);
339            }
340            OpenIntent::OverwriteOrCreate => {
341                cap_opts
342                    .read(opts.read)
343                    .write(true)
344                    .create(true)
345                    .truncate(true);
346            }
347        }
348
349        let cap_file = spawn_blocking(move || root.open_with(&rel, &cap_opts))
350            .await
351            .map_err(join_to_io)
352            .map_err(io_to_smb)?
353            .map_err(io_to_smb)?;
354
355        // Convert to a `std::fs::File`. We only need cap-std for the safe
356        // *open*; once we hold a verified file handle, std's API gives us
357        // `set_times`, `set_len`, `sync_data`, and `FileExt::{read,write}_at`
358        // without pulling in extra crates.
359        let std_file: std::fs::File = cap_file.into_std();
360
361        Ok(Box::new(LocalHandle::File {
362            name: file_name_for(path),
363            file: Arc::new(std_file),
364            read_only,
365        }))
366    }
367
368    async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
369        if self.read_only {
370            return Err(SmbError::AccessDenied);
371        }
372        if path.is_root() {
373            // Refusing to delete the share root itself.
374            return Err(SmbError::AccessDenied);
375        }
376        let rel = to_rel_path(path);
377        let root = Arc::clone(&self.root);
378
379        spawn_blocking(move || -> io::Result<()> {
380            match root.remove_file(&rel) {
381                Ok(()) => Ok(()),
382                Err(e) if e.kind() == io::ErrorKind::IsADirectory => {
383                    // Caller's intent was "delete this name"; if it turned
384                    // out to be a directory, fall back to remove_dir which
385                    // refuses non-empty dirs (mapped to NotEmpty above).
386                    root.remove_dir(&rel)
387                }
388                Err(e) => Err(e),
389            }
390        })
391        .await
392        .map_err(join_to_io)
393        .map_err(io_to_smb)?
394        .map_err(io_to_smb)
395    }
396
397    async fn rename(&self, from: &SmbPath, to: &SmbPath) -> SmbResult<()> {
398        if self.read_only {
399            return Err(SmbError::AccessDenied);
400        }
401        if from.is_root() || to.is_root() {
402            return Err(SmbError::NameInvalid);
403        }
404        let from = to_rel_path(from);
405        let to_path = to_rel_path(to);
406        let root = Arc::clone(&self.root);
407        let root2 = Arc::clone(&self.root);
408
409        spawn_blocking(move || -> io::Result<()> {
410            // Reject overwrite — SMB rename semantics require explicit
411            // replace-if-exists which we do not implement in v1.
412            if root2.exists(&to_path) {
413                return Err(io::Error::from(io::ErrorKind::AlreadyExists));
414            }
415            root.rename(&from, &root2, &to_path)
416        })
417        .await
418        .map_err(join_to_io)
419        .map_err(io_to_smb)?
420        .map_err(io_to_smb)
421    }
422
423    fn capabilities(&self) -> BackendCapabilities {
424        BackendCapabilities {
425            is_read_only: self.read_only,
426            // POSIX filesystems are typically case-sensitive. We don't try to
427            // emulate case-insensitive lookup in v1 (see spec §3.4).
428            case_sensitive: cfg!(any(target_os = "linux", target_os = "freebsd")),
429        }
430    }
431}
432
433// ---------------------------------------------------------------------------
434// Handle
435// ---------------------------------------------------------------------------
436
437/// Internal handle variant. `File` carries a `std::fs::File` (after cap-std
438/// has done the safe open); `Dir` keeps the `cap_std::fs::Dir` so we can
439/// re-list entries.
440enum LocalHandle {
441    File {
442        name: String,
443        file: Arc<std::fs::File>,
444        read_only: bool,
445    },
446    Dir {
447        name: String,
448        dir_handle: Arc<Dir>,
449    },
450}
451
452fn file_name_for(path: &SmbPath) -> String {
453    path.file_name().unwrap_or("").to_string()
454}
455
456#[async_trait]
457impl Handle for LocalHandle {
458    async fn read(&self, offset: u64, len: u32) -> SmbResult<Bytes> {
459        match self {
460            LocalHandle::File { file, .. } => {
461                let file = Arc::clone(file);
462                let n = len as usize;
463                let bytes = spawn_blocking(move || -> io::Result<Bytes> {
464                    let mut buf = vec![0u8; n];
465                    let read = file.read_at(&mut buf, offset)?;
466                    buf.truncate(read);
467                    Ok(Bytes::from(buf))
468                })
469                .await
470                .map_err(join_to_io)
471                .map_err(io_to_smb)?
472                .map_err(io_to_smb)?;
473                Ok(bytes)
474            }
475            LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
476        }
477    }
478
479    async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32> {
480        self.write_owned(offset, data.to_vec()).await
481    }
482
483    async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
484        match self {
485            LocalHandle::File {
486                file, read_only, ..
487            } => {
488                if *read_only {
489                    return Err(SmbError::AccessDenied);
490                }
491                let file = Arc::clone(file);
492                let written = spawn_blocking(move || file.write_at(&data, offset))
493                    .await
494                    .map_err(join_to_io)
495                    .map_err(io_to_smb)?
496                    .map_err(io_to_smb)?;
497                Ok(u32::try_from(written).unwrap_or(u32::MAX))
498            }
499            LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
500        }
501    }
502
503    async fn flush(&self) -> SmbResult<()> {
504        match self {
505            LocalHandle::File { file, .. } => {
506                let file = Arc::clone(file);
507                spawn_blocking(move || file.sync_data())
508                    .await
509                    .map_err(join_to_io)
510                    .map_err(io_to_smb)?
511                    .map_err(io_to_smb)
512            }
513            // Flushing a directory is a no-op in SMB semantics.
514            LocalHandle::Dir { .. } => Ok(()),
515        }
516    }
517
518    async fn stat(&self) -> SmbResult<FileInfo> {
519        match self {
520            LocalHandle::File { file, name, .. } => {
521                let file = Arc::clone(file);
522                let name = name.clone();
523                spawn_blocking(move || -> io::Result<FileInfo> {
524                    let std_md = file.metadata()?;
525                    // Synthesize a cap-std Metadata from the std one so we
526                    // can reuse `file_info_from_metadata`. cap-primitives
527                    // exposes `Metadata::from_just_metadata` for this.
528                    let md = cap_std::fs::Metadata::from_just_metadata(std_md);
529                    Ok(file_info_from_metadata(name, &md))
530                })
531                .await
532                .map_err(join_to_io)
533                .map_err(io_to_smb)?
534                .map_err(io_to_smb)
535            }
536            LocalHandle::Dir {
537                dir_handle, name, ..
538            } => {
539                let dir_handle = Arc::clone(dir_handle);
540                let name = name.clone();
541                spawn_blocking(move || -> io::Result<FileInfo> {
542                    let md = dir_handle.dir_metadata()?;
543                    Ok(file_info_from_metadata(name, &md))
544                })
545                .await
546                .map_err(join_to_io)
547                .map_err(io_to_smb)?
548                .map_err(io_to_smb)
549            }
550        }
551    }
552
553    async fn set_times(&self, times: FileTimes) -> SmbResult<()> {
554        match self {
555            LocalHandle::File {
556                file, read_only, ..
557            } => {
558                if *read_only {
559                    return Err(SmbError::AccessDenied);
560                }
561                let file = Arc::clone(file);
562                spawn_blocking(move || -> io::Result<()> {
563                    let mut std_times = std::fs::FileTimes::new();
564                    if let Some(ft) = times.last_write_time
565                        && let Some(t) = filetime_to_system_time(ft)
566                    {
567                        std_times = std_times.set_modified(t);
568                    }
569                    if let Some(ft) = times.last_access_time
570                        && let Some(t) = filetime_to_system_time(ft)
571                    {
572                        std_times = std_times.set_accessed(t);
573                    }
574                    // creation_time / change_time: stable std::fs::FileTimes
575                    // does not expose setters for these; silently ignored.
576                    file.set_times(std_times)
577                })
578                .await
579                .map_err(join_to_io)
580                .map_err(io_to_smb)?
581                .map_err(io_to_smb)
582            }
583            // cap-std's directory handle does not expose set_times in its
584            // stable API; mark as unsupported on directories.
585            LocalHandle::Dir { .. } => Err(SmbError::NotSupported),
586        }
587    }
588
589    async fn truncate(&self, len: u64) -> SmbResult<()> {
590        match self {
591            LocalHandle::File {
592                file, read_only, ..
593            } => {
594                if *read_only {
595                    return Err(SmbError::AccessDenied);
596                }
597                let file = Arc::clone(file);
598                spawn_blocking(move || file.set_len(len))
599                    .await
600                    .map_err(join_to_io)
601                    .map_err(io_to_smb)?
602                    .map_err(io_to_smb)
603            }
604            // Protocol layer rejects truncate on dir handles before this; if
605            // it ever reaches us, surface as NotSupported.
606            LocalHandle::Dir { .. } => Err(SmbError::NotSupported),
607        }
608    }
609
610    async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<SmbDirEntry>> {
611        match self {
612            LocalHandle::File { .. } => Err(SmbError::NotADirectory),
613            LocalHandle::Dir { dir_handle, .. } => {
614                let dir_handle = Arc::clone(dir_handle);
615                let pat = pattern.map(|s| s.to_owned());
616                spawn_blocking(move || -> io::Result<Vec<SmbDirEntry>> {
617                    let mut out = Vec::new();
618                    for entry in dir_handle.entries()? {
619                        let entry = entry?;
620                        let os_name = entry.file_name();
621                        let Some(name) = os_name.to_str().map(str::to_owned) else {
622                            // Skip non-UTF-8 names; SMB wire format is UTF-16
623                            // and we never want to emit invalid Unicode here.
624                            continue;
625                        };
626                        if let Some(p) = pat.as_deref() {
627                            // Empty / "*" / "*.*" all mean "match everything"
628                            // in DOS-speak.
629                            if !(p.is_empty() || p == "*" || p == "*.*" || glob_match(p, &name)) {
630                                continue;
631                            }
632                        }
633                        let md = entry.metadata()?;
634                        let info = file_info_from_metadata(name, &md);
635                        out.push(SmbDirEntry { info });
636                    }
637                    Ok(out)
638                })
639                .await
640                .map_err(join_to_io)
641                .map_err(io_to_smb)?
642                .map_err(io_to_smb)
643            }
644        }
645    }
646
647    async fn close(self: Box<Self>) -> SmbResult<()> {
648        // Drop is sufficient — closing the underlying handle is what the OS
649        // does when the last `Arc` ref goes away. No flush here: SMB CLOSE
650        // does not imply fsync.
651        Ok(())
652    }
653}
654
655// ---------------------------------------------------------------------------
656// Tests
657// ---------------------------------------------------------------------------
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662    use crate::backend::{OpenIntent, OpenOptions};
663    use crate::path::SmbPath;
664    use tempfile::tempdir;
665
666    fn p(s: &str) -> SmbPath {
667        s.parse::<SmbPath>().unwrap()
668    }
669
670    fn opts_create() -> OpenOptions {
671        OpenOptions {
672            read: true,
673            write: true,
674            intent: OpenIntent::Create,
675            directory: false,
676            non_directory: false,
677            delete_on_close: false,
678        }
679    }
680
681    fn opts_open_rw() -> OpenOptions {
682        OpenOptions {
683            read: true,
684            write: true,
685            intent: OpenIntent::Open,
686            directory: false,
687            non_directory: false,
688            delete_on_close: false,
689        }
690    }
691
692    fn opts_open_ro() -> OpenOptions {
693        OpenOptions {
694            read: true,
695            write: false,
696            intent: OpenIntent::Open,
697            directory: false,
698            non_directory: false,
699            delete_on_close: false,
700        }
701    }
702
703    fn opts_open_dir() -> OpenOptions {
704        OpenOptions {
705            read: true,
706            write: false,
707            intent: OpenIntent::Open,
708            directory: true,
709            non_directory: false,
710            delete_on_close: false,
711        }
712    }
713
714    #[tokio::test]
715    async fn create_write_read_stat_close() {
716        let td = tempdir().unwrap();
717        let backend = LocalFsBackend::new(td.path()).unwrap();
718
719        // Create
720        let h = backend.open(&p("hello.txt"), opts_create()).await.unwrap();
721        let n = h.write(0, b"hello world").await.unwrap();
722        assert_eq!(n, 11);
723        h.flush().await.unwrap();
724
725        // Stat
726        let info = h.stat().await.unwrap();
727        assert_eq!(info.name, "hello.txt");
728        assert_eq!(info.end_of_file, 11);
729        assert!(!info.is_directory);
730        assert!(info.last_write_time > 0);
731        h.close().await.unwrap();
732
733        // Reopen for read
734        let h2 = backend.open(&p("hello.txt"), opts_open_ro()).await.unwrap();
735        let bytes = h2.read(0, 1024).await.unwrap();
736        assert_eq!(&bytes[..], b"hello world");
737
738        // Short-read past EOF returns truncated
739        let bytes = h2.read(6, 1024).await.unwrap();
740        assert_eq!(&bytes[..], b"world");
741
742        // Read past EOF returns empty
743        let bytes = h2.read(100, 1024).await.unwrap();
744        assert!(bytes.is_empty());
745        h2.close().await.unwrap();
746    }
747
748    #[tokio::test]
749    async fn list_dir_finds_created_file() {
750        let td = tempdir().unwrap();
751        let backend = LocalFsBackend::new(td.path()).unwrap();
752        let h = backend.open(&p("a.txt"), opts_create()).await.unwrap();
753        h.close().await.unwrap();
754
755        let dir_h = backend
756            .open(&SmbPath::root(), opts_open_dir())
757            .await
758            .unwrap();
759        let entries = dir_h.list_dir(None).await.unwrap();
760        assert!(entries.iter().any(|e| e.info.name == "a.txt"));
761        dir_h.close().await.unwrap();
762    }
763
764    #[tokio::test]
765    async fn read_only_rejects_writes() {
766        let td = tempdir().unwrap();
767        // Pre-create a file via a writable backend so we have something to
768        // attempt to open RW.
769        {
770            let writable = LocalFsBackend::new(td.path()).unwrap();
771            let h = writable.open(&p("x.txt"), opts_create()).await.unwrap();
772            h.close().await.unwrap();
773        }
774
775        let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
776        assert!(backend.capabilities().is_read_only);
777
778        // RW open should be rejected.
779        let err = backend
780            .open(&p("x.txt"), opts_open_rw())
781            .await
782            .err()
783            .unwrap();
784        assert!(matches!(err, SmbError::AccessDenied));
785
786        // Create should be rejected.
787        let err = backend
788            .open(&p("y.txt"), opts_create())
789            .await
790            .err()
791            .unwrap();
792        assert!(matches!(err, SmbError::AccessDenied));
793
794        // Pure read open is fine.
795        let h = backend.open(&p("x.txt"), opts_open_ro()).await.unwrap();
796        // Writing through a handle obtained from a read-only backend would
797        // already be impossible — but if a backend ever yields one, the
798        // check still bites.
799        h.close().await.unwrap();
800
801        // unlink rejected.
802        let err = backend.unlink(&p("x.txt")).await.err().unwrap();
803        assert!(matches!(err, SmbError::AccessDenied));
804    }
805
806    #[tokio::test]
807    async fn unlink_file_then_nonempty_dir_errors() {
808        let td = tempdir().unwrap();
809        let backend = LocalFsBackend::new(td.path()).unwrap();
810
811        // Create & remove a file.
812        let h = backend.open(&p("doomed.txt"), opts_create()).await.unwrap();
813        h.close().await.unwrap();
814        backend.unlink(&p("doomed.txt")).await.unwrap();
815        assert!(matches!(
816            backend.unlink(&p("doomed.txt")).await.err().unwrap(),
817            SmbError::NotFound
818        ));
819
820        // Create a non-empty directory; unlink should fail with NotEmpty.
821        std::fs::create_dir(td.path().join("dir1")).unwrap();
822        std::fs::write(td.path().join("dir1").join("inside"), b"x").unwrap();
823
824        let err = backend.unlink(&p("dir1")).await.err().unwrap();
825        assert!(
826            matches!(err, SmbError::NotEmpty),
827            "expected NotEmpty, got {err:?}"
828        );
829
830        // Empty it and retry.
831        std::fs::remove_file(td.path().join("dir1").join("inside")).unwrap();
832        backend.unlink(&p("dir1")).await.unwrap();
833    }
834
835    #[tokio::test]
836    async fn rename_within_root() {
837        let td = tempdir().unwrap();
838        let backend = LocalFsBackend::new(td.path()).unwrap();
839
840        let h = backend.open(&p("old.txt"), opts_create()).await.unwrap();
841        h.write(0, b"data").await.unwrap();
842        h.close().await.unwrap();
843
844        backend.rename(&p("old.txt"), &p("new.txt")).await.unwrap();
845        assert!(td.path().join("new.txt").exists());
846        assert!(!td.path().join("old.txt").exists());
847
848        // Renaming over an existing target should fail.
849        let h = backend.open(&p("other.txt"), opts_create()).await.unwrap();
850        h.close().await.unwrap();
851        let err = backend
852            .rename(&p("other.txt"), &p("new.txt"))
853            .await
854            .err()
855            .unwrap();
856        assert!(matches!(err, SmbError::Exists), "got {err:?}");
857    }
858
859    #[tokio::test]
860    async fn list_dir_pattern_matching() {
861        let td = tempdir().unwrap();
862        let backend = LocalFsBackend::new(td.path()).unwrap();
863
864        for name in ["a.txt", "b.txt", "c.log", "README"] {
865            let h = backend.open(&p(name), opts_create()).await.unwrap();
866            h.close().await.unwrap();
867        }
868
869        let dir_h = backend
870            .open(&SmbPath::root(), opts_open_dir())
871            .await
872            .unwrap();
873
874        let txts = dir_h.list_dir(Some("*.txt")).await.unwrap();
875        let names: Vec<_> = txts.iter().map(|e| e.info.name.as_str()).collect();
876        assert_eq!(names.len(), 2, "expected 2 .txt files, got {names:?}");
877        assert!(names.contains(&"a.txt"));
878        assert!(names.contains(&"b.txt"));
879
880        // Single-char wildcard.
881        let one = dir_h.list_dir(Some("?.log")).await.unwrap();
882        let names: Vec<_> = one.iter().map(|e| e.info.name.as_str()).collect();
883        assert_eq!(names, vec!["c.log"]);
884
885        // Case-insensitive.
886        let any_txt = dir_h.list_dir(Some("*.TXT")).await.unwrap();
887        assert_eq!(any_txt.len(), 2);
888
889        // "*" matches everything.
890        let all = dir_h.list_dir(Some("*")).await.unwrap();
891        assert_eq!(all.len(), 4);
892
893        dir_h.close().await.unwrap();
894    }
895
896    #[test]
897    fn glob_match_basics() {
898        assert!(glob_match("*", "anything"));
899        assert!(glob_match("*.txt", "foo.txt"));
900        assert!(!glob_match("*.txt", "foo.log"));
901        assert!(glob_match("a?c", "abc"));
902        assert!(!glob_match("a?c", "ac"));
903        assert!(glob_match("a*b*c", "axxxbxxxc"));
904        assert!(glob_match("FOO", "foo"));
905        assert!(glob_match("", ""));
906        assert!(!glob_match("", "a"));
907    }
908
909    #[test]
910    fn filetime_round_trip() {
911        let now = SystemTime::now();
912        let ft = system_time_to_filetime(now);
913        let back = filetime_to_system_time(ft).unwrap();
914        let delta = now
915            .duration_since(back)
916            .or_else(|e| Ok::<_, std::time::SystemTimeError>(e.duration()))
917            .unwrap();
918        // 100ns granularity — round-trip should be sub-microsecond.
919        assert!(delta < Duration::from_micros(1), "delta = {delta:?}");
920    }
921}