1use std::io;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use std::time::{Duration, SystemTime, UNIX_EPOCH};
22
23use async_trait::async_trait;
24use bytes::Bytes;
25use cap_std::ambient_authority;
26use cap_std::fs::{Dir, Metadata, OpenOptions as CapOpenOptions};
27use tokio::task::spawn_blocking;
28
29use crate::backend::{
30 BackendCapabilities, DirEntry as SmbDirEntry, FILE_ATTRIBUTE_ARCHIVE, FILE_ATTRIBUTE_READONLY,
31 FileInfo, FileTimes, Handle, OpenIntent, OpenOptions, ShareBackend,
32};
33use crate::error::{SmbError, SmbResult};
34use crate::path::{SmbPath, same_path};
35use crate::utils::{FILETIME_OFFSET, system_time_to_filetime};
36
37pub struct LocalFsBackend {
48 root: Arc<Dir>,
49 root_dev: Option<u64>,
51 read_only: bool,
52}
53
54impl LocalFsBackend {
55 pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
58 let dir = Dir::open_ambient_dir(path, ambient_authority())?;
59 let root_dev = file_key(&dir.dir_metadata()?).map(|(dev, _)| dev);
60 Ok(Self {
61 root: Arc::new(dir),
62 root_dev,
63 read_only: false,
64 })
65 }
66
67 #[must_use]
70 pub fn read_only(mut self) -> Self {
71 self.read_only = true;
72 self
73 }
74}
75
76fn to_rel_path(path: &SmbPath) -> PathBuf {
87 if path.is_root() {
88 return PathBuf::from(".");
89 }
90 let mut out = PathBuf::new();
91 for c in path.components() {
92 out.push(c);
93 }
94 out
95}
96
97fn io_to_smb(err: io::Error) -> SmbError {
102 use io::ErrorKind::*;
103 #[cfg(windows)]
104 {
105 const ERROR_SHARING_VIOLATION: i32 = 32;
106 if err.raw_os_error() == Some(ERROR_SHARING_VIOLATION) {
107 return SmbError::Sharing;
108 }
109 }
110 match err.kind() {
111 NotFound => SmbError::NotFound,
112 PermissionDenied => SmbError::AccessDenied,
113 AlreadyExists => SmbError::Exists,
114 DirectoryNotEmpty => SmbError::NotEmpty,
115 IsADirectory => SmbError::IsDirectory,
116 NotADirectory => SmbError::NotADirectory,
117 InvalidInput | InvalidFilename => SmbError::NameInvalid,
118 CrossesDevices => SmbError::NotSameDevice,
119 _ => SmbError::Io(err),
120 }
121}
122
123fn join_to_io(_e: tokio::task::JoinError) -> io::Error {
126 io::Error::other("blocking task panicked or was cancelled")
127}
128
129fn read_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
136 #[cfg(unix)]
137 {
138 std::os::unix::fs::FileExt::read_at(file, buf, offset)
139 }
140 #[cfg(windows)]
141 {
142 std::os::windows::fs::FileExt::seek_read(file, buf, offset)
143 }
144}
145
146fn write_at(file: &std::fs::File, data: &[u8], offset: u64) -> io::Result<usize> {
147 #[cfg(unix)]
148 {
149 std::os::unix::fs::FileExt::write_at(file, data, offset)
150 }
151 #[cfg(windows)]
152 {
153 std::os::windows::fs::FileExt::seek_write(file, data, offset)
154 }
155}
156
157fn file_key(md: &Metadata) -> Option<(u64, u64)> {
160 #[cfg(unix)]
161 {
162 use cap_std::fs::MetadataExt as _;
163 Some((md.dev(), md.ino()))
164 }
165 #[cfg(windows)]
166 {
167 use cap_primitives::fs::_WindowsByHandle;
169 let volume = _WindowsByHandle::volume_serial_number(md)?;
170 let index = _WindowsByHandle::file_index(md)?;
171 Some((volume.into(), index))
172 }
173}
174
175fn file_index(root_dev: Option<u64>, key: Option<(u64, u64)>) -> u64 {
180 let Some((dev, ino)) = key else {
181 return 0;
182 };
183 if root_dev.is_none_or(|root| root == dev) {
184 return ino;
185 }
186 let mut x = dev;
188 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
189 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
190 ino ^ x ^ (x >> 31)
191}
192
193fn link_count(md: &Metadata) -> Option<u64> {
195 #[cfg(unix)]
196 {
197 use cap_std::fs::MetadataExt as _;
198 Some(md.nlink())
199 }
200 #[cfg(windows)]
201 {
202 cap_primitives::fs::_WindowsByHandle::number_of_links(md).map(u64::from)
203 }
204}
205
206fn is_dir_entry(md: &Metadata) -> bool {
212 #[cfg(unix)]
213 {
214 md.is_dir()
215 }
216 #[cfg(windows)]
217 {
218 const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
219 cap_std::fs::MetadataExt::file_attributes(md) & FILE_ATTRIBUTE_DIRECTORY != 0
220 }
221}
222
223#[cfg_attr(unix, expect(unused_variables, reason = "dir is used on Windows only"))]
228fn entry_metadata(dir: &Dir, entry: &cap_std::fs::DirEntry) -> io::Result<Metadata> {
229 #[cfg(unix)]
230 {
231 entry.metadata()
232 }
233 #[cfg(windows)]
234 {
235 dir.symlink_metadata(entry.file_name())
236 .or_else(|_| entry.metadata())
237 }
238}
239
240#[cfg_attr(
244 unix,
245 expect(unused_variables, reason = "write_attributes is used on Windows only")
246)]
247fn open_dir_handle(root: &Dir, rel: &Path, write_attributes: bool) -> io::Result<Dir> {
248 #[cfg(unix)]
249 {
250 root.open_dir(rel)
251 }
252 #[cfg(windows)]
253 {
254 use cap_primitives::fs::OpenOptionsExt as _;
255 const GENERIC_READ: u32 = 0x8000_0000;
256 const FILE_WRITE_ATTRIBUTES: u32 = 0x0000_0100;
257 const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
258
259 let mut opts = CapOpenOptions::new();
260 opts.read(true).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
261 if write_attributes {
262 opts.access_mode(GENERIC_READ | FILE_WRITE_ATTRIBUTES);
263 }
264 let file = root.open_with(rel, &opts)?;
265 if !file.metadata()?.is_dir() {
266 return Err(io::ErrorKind::NotADirectory.into());
267 }
268 Ok(Dir::from_std_file(file.into_std()))
269 }
270}
271
272fn dir_as_file(dir: &Dir) -> io::Result<std::fs::File> {
276 #[cfg(unix)]
277 {
278 Ok(dir.open(".")?.into_std())
279 }
280 #[cfg(windows)]
281 {
282 use std::os::windows::io::AsHandle as _;
283 Ok(dir.as_handle().try_clone_to_owned()?.into())
284 }
285}
286
287fn set_read_only(file: &std::fs::File, read_only: bool) -> io::Result<()> {
291 let mut perms = file.metadata()?.permissions();
292 #[cfg(unix)]
293 {
294 use std::os::unix::fs::PermissionsExt as _;
295 let mode = perms.mode();
296 perms.set_mode(if read_only {
297 mode & !0o222
298 } else {
299 mode | 0o200
300 });
301 }
302 #[cfg(windows)]
303 {
304 perms.set_readonly(read_only);
305 }
306 file.set_permissions(perms)
307}
308
309fn host_file_times(times: FileTimes) -> SmbResult<std::fs::FileTimes> {
313 let host_time = |ft| filetime_to_system_time(ft).ok_or(SmbError::NotSupported);
314 let mut out = std::fs::FileTimes::new();
315 if let Some(ft) = times.last_write_time {
316 out = out.set_modified(host_time(ft)?);
317 }
318 if let Some(ft) = times.last_access_time {
319 out = out.set_accessed(host_time(ft)?);
320 }
321 #[cfg(any(windows, target_os = "macos"))]
322 if let Some(ft) = times.creation_time {
323 out = set_created(out, host_time(ft)?);
324 }
325 Ok(out)
326}
327
328#[cfg(windows)]
329fn set_created(times: std::fs::FileTimes, t: SystemTime) -> std::fs::FileTimes {
330 use std::os::windows::fs::FileTimesExt as _;
331 times.set_created(t)
332}
333
334#[cfg(target_os = "macos")]
335fn set_created(times: std::fs::FileTimes, t: SystemTime) -> std::fs::FileTimes {
336 use std::os::macos::fs::FileTimesExt as _;
337 times.set_created(t)
338}
339
340fn filetime_to_system_time(ft: u64) -> Option<SystemTime> {
345 if ft < FILETIME_OFFSET {
346 return None;
347 }
348 let unix_100ns = ft - FILETIME_OFFSET;
349 let secs = unix_100ns / 10_000_000;
350 let nanos = ((unix_100ns % 10_000_000) * 100) as u32;
351 UNIX_EPOCH.checked_add(Duration::new(secs, nanos))
352}
353
354fn file_info_from_metadata(name: String, md: &Metadata, root_dev: Option<u64>) -> FileInfo {
359 let len = md.len();
360 let modified = md.modified().ok().map(|t| t.into_std());
361 let accessed = md.accessed().ok().map(|t| t.into_std());
362 let created = md.created().ok().map(|t| t.into_std());
363
364 let modified = modified
367 .or(created)
368 .or(accessed)
369 .unwrap_or(SystemTime::UNIX_EPOCH);
370 let accessed = accessed.unwrap_or(modified);
371 let created = created.unwrap_or(modified);
372
373 FileInfo {
374 name,
375 end_of_file: len,
376 allocation_size: len,
377 creation_time: system_time_to_filetime(created),
378 last_access_time: system_time_to_filetime(accessed),
379 last_write_time: system_time_to_filetime(modified),
380 change_time: system_time_to_filetime(modified),
381 is_directory: md.is_dir(),
382 read_only: !md.is_dir() && md.permissions().readonly(),
383 file_index: file_index(root_dev, file_key(md)),
384 }
385}
386
387fn glob_match(pattern: &str, name: &str) -> bool {
401 let p: Vec<char> = pattern.chars().collect();
402 let n: Vec<char> = name.chars().collect();
403 let last_dot = n.iter().rposition(|&c| c == '.');
404
405 let mut matches = vec![false; n.len() + 1];
408 matches[0] = true;
409 for &pc in &p {
410 let mut next = vec![false; n.len() + 1];
411 for j in 0..=n.len() {
412 let here = j < n.len();
413 next[j] = match pc {
414 '*' => matches[j] || (j > 0 && next[j - 1]),
415 '<' => matches[j] || (j > 0 && next[j - 1] && Some(j - 1) != last_dot),
416 '?' => j > 0 && matches[j - 1],
417 '>' => {
418 (j > 0 && matches[j - 1] && n[j - 1] != '.')
419 || (matches[j] && (!here || n[j] == '.'))
420 }
421 '"' => (j > 0 && matches[j - 1] && n[j - 1] == '.') || (matches[j] && !here),
422 c => j > 0 && matches[j - 1] && c.eq_ignore_ascii_case(&n[j - 1]),
423 };
424 }
425 matches = next;
426 }
427 matches[n.len()]
428}
429
430#[async_trait]
435impl ShareBackend for LocalFsBackend {
436 async fn open(&self, path: &SmbPath, opts: OpenOptions) -> SmbResult<Box<dyn Handle>> {
437 let writes = opts.write
441 || opts.write_attributes
442 || matches!(
443 opts.intent,
444 OpenIntent::Create
445 | OpenIntent::OpenOrCreate
446 | OpenIntent::OverwriteOrCreate
447 | OpenIntent::Truncate
448 );
449 if self.read_only && writes {
450 return Err(SmbError::AccessDenied);
451 }
452
453 let rel = to_rel_path(path);
454 let root = Arc::clone(&self.root);
455 let read_only = self.read_only;
456 let directory = opts.directory;
457 let non_directory = opts.non_directory;
458 let write_attributes = opts.write_attributes;
459
460 if directory {
461 let intent = opts.intent;
464 let dir_handle = spawn_blocking(move || -> io::Result<Dir> {
465 match intent {
466 OpenIntent::Open => open_dir_handle(&root, &rel, write_attributes),
467 OpenIntent::Create => {
468 root.create_dir(&rel)?;
469 open_dir_handle(&root, &rel, write_attributes)
470 }
471 OpenIntent::OpenOrCreate => {
472 if !root.exists(&rel) {
473 root.create_dir(&rel)?;
474 }
475 open_dir_handle(&root, &rel, write_attributes)
476 }
477 OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
478 Err(io::Error::from(io::ErrorKind::InvalidInput))
480 }
481 }
482 })
483 .await
484 .map_err(join_to_io)
485 .map_err(io_to_smb)?
486 .map_err(io_to_smb)?;
487
488 return Ok(Box::new(LocalHandle::Dir {
489 name: file_name_for(path),
490 root_dev: self.root_dev,
491 dir_handle: Arc::new(dir_handle),
492 }));
493 }
494
495 let existing_is_dir = {
496 let root = Arc::clone(&self.root);
497 let rel = rel.clone();
498 spawn_blocking(move || -> io::Result<bool> {
499 match root.metadata(&rel) {
500 Ok(md) => Ok(md.is_dir()),
501 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
502 Err(e) => Err(e),
503 }
504 })
505 .await
506 .map_err(join_to_io)
507 .map_err(io_to_smb)?
508 .map_err(io_to_smb)?
509 };
510 if existing_is_dir {
511 if non_directory {
512 return Err(SmbError::IsDirectory);
513 }
514 match opts.intent {
515 OpenIntent::Open | OpenIntent::OpenOrCreate => {
516 let root = Arc::clone(&self.root);
517 let rel = rel.clone();
518 let dir_handle =
519 spawn_blocking(move || open_dir_handle(&root, &rel, write_attributes))
520 .await
521 .map_err(join_to_io)
522 .map_err(io_to_smb)?
523 .map_err(io_to_smb)?;
524 return Ok(Box::new(LocalHandle::Dir {
525 name: file_name_for(path),
526 root_dev: self.root_dev,
527 dir_handle: Arc::new(dir_handle),
528 }));
529 }
530 OpenIntent::Create => return Err(SmbError::Exists),
531 OpenIntent::Truncate | OpenIntent::OverwriteOrCreate => {
532 return Err(SmbError::IsDirectory);
533 }
534 }
535 }
536
537 let mut cap_opts = CapOpenOptions::new();
539 match opts.intent {
540 OpenIntent::Open => {
541 cap_opts.read(true).write(opts.write);
542 #[cfg(windows)]
546 if opts.write_attributes && !opts.write {
547 use cap_primitives::fs::OpenOptionsExt as _;
548 const GENERIC_READ: u32 = 0x8000_0000;
549 const FILE_WRITE_ATTRIBUTES: u32 = 0x0000_0100;
550 cap_opts.access_mode(GENERIC_READ | FILE_WRITE_ATTRIBUTES);
551 }
552 }
553 OpenIntent::Create => {
554 cap_opts.read(opts.read).write(true).create_new(true);
555 }
556 OpenIntent::Truncate => {
557 cap_opts.read(opts.read).write(true).truncate(true);
558 }
559 OpenIntent::OpenOrCreate => {
560 cap_opts.read(opts.read).write(true).create(true);
561 }
562 OpenIntent::OverwriteOrCreate => {
563 cap_opts
564 .read(opts.read)
565 .write(true)
566 .create(true)
567 .truncate(true);
568 }
569 }
570
571 let cap_file = spawn_blocking(move || root.open_with(&rel, &cap_opts))
572 .await
573 .map_err(join_to_io)
574 .map_err(io_to_smb)?
575 .map_err(io_to_smb)?;
576
577 let std_file: std::fs::File = cap_file.into_std();
581
582 Ok(Box::new(LocalHandle::File {
583 name: file_name_for(path),
584 root_dev: self.root_dev,
585 file: Arc::new(std_file),
586 read_only,
587 }))
588 }
589
590 async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
591 if self.read_only {
592 return Err(SmbError::AccessDenied);
593 }
594 if path.is_root() {
595 return Err(SmbError::AccessDenied);
597 }
598 let rel = to_rel_path(path);
599 let root = Arc::clone(&self.root);
600
601 spawn_blocking(move || -> io::Result<()> {
602 if is_dir_entry(&root.symlink_metadata(&rel)?) {
606 root.remove_dir(&rel)
607 } else {
608 root.remove_file(&rel)
609 }
610 })
611 .await
612 .map_err(join_to_io)
613 .map_err(io_to_smb)?
614 .map_err(io_to_smb)
615 }
616
617 async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()> {
618 if self.read_only {
619 return Err(SmbError::AccessDenied);
620 }
621 if from.is_root() || to.is_root() {
622 return Err(SmbError::NameInvalid);
623 }
624 let same_name = same_path(from, to, self.capabilities().case_sensitive);
625 let from = to_rel_path(from);
626 let to_path = to_rel_path(to);
627 let root = Arc::clone(&self.root);
628
629 spawn_blocking(move || -> io::Result<()> {
630 let from_md = root.symlink_metadata(&from)?;
631 match root.symlink_metadata(&to_path) {
632 Ok(to_md) => {
633 let from_key = file_key(&from_md);
634 let same_file = from_key.is_some() && from_key == file_key(&to_md);
635 if !(same_file && same_name) {
639 if !replace_if_exists {
640 return Err(io::ErrorKind::AlreadyExists.into());
641 }
642 if is_dir_entry(&to_md) {
643 return Err(io::ErrorKind::PermissionDenied.into());
644 }
645 }
646 if same_file && !same_name && link_count(&from_md) > Some(1) {
651 return root.remove_file(&from);
652 }
653 }
654 Err(e) if e.kind() == io::ErrorKind::NotFound => {}
655 Err(e) => return Err(e),
656 }
657 root.rename(&from, &root, &to_path)
658 })
659 .await
660 .map_err(join_to_io)
661 .map_err(io_to_smb)?
662 .map_err(io_to_smb)
663 }
664
665 fn capabilities(&self) -> BackendCapabilities {
666 BackendCapabilities {
667 is_read_only: self.read_only,
668 case_sensitive: cfg!(any(target_os = "linux", target_os = "freebsd")),
670 }
671 }
672}
673
674enum LocalHandle {
682 File {
683 name: String,
684 root_dev: Option<u64>,
685 file: Arc<std::fs::File>,
686 read_only: bool,
687 },
688 Dir {
689 name: String,
690 root_dev: Option<u64>,
691 dir_handle: Arc<Dir>,
692 },
693}
694
695fn file_name_for(path: &SmbPath) -> String {
696 path.file_name().unwrap_or("").to_string()
697}
698
699#[async_trait]
700impl Handle for LocalHandle {
701 async fn read(&self, offset: u64, len: u32) -> SmbResult<Bytes> {
702 match self {
703 LocalHandle::File { file, .. } => {
704 let file = Arc::clone(file);
705 let n = len as usize;
706 let bytes = spawn_blocking(move || -> io::Result<Bytes> {
707 let mut buf = vec![0u8; n];
708 let read = read_at(&file, &mut buf, offset)?;
709 buf.truncate(read);
710 Ok(Bytes::from(buf))
711 })
712 .await
713 .map_err(join_to_io)
714 .map_err(io_to_smb)?
715 .map_err(io_to_smb)?;
716 Ok(bytes)
717 }
718 LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
719 }
720 }
721
722 async fn write(&self, offset: u64, data: &[u8]) -> SmbResult<u32> {
723 self.write_owned(offset, data.to_vec()).await
724 }
725
726 async fn write_owned(&self, offset: u64, data: Vec<u8>) -> SmbResult<u32> {
727 match self {
728 LocalHandle::File {
729 file, read_only, ..
730 } => {
731 if *read_only {
732 return Err(SmbError::AccessDenied);
733 }
734 let file = Arc::clone(file);
735 let written = spawn_blocking(move || write_at(&file, &data, offset))
736 .await
737 .map_err(join_to_io)
738 .map_err(io_to_smb)?
739 .map_err(io_to_smb)?;
740 Ok(u32::try_from(written).unwrap_or(u32::MAX))
741 }
742 LocalHandle::Dir { .. } => Err(SmbError::IsDirectory),
743 }
744 }
745
746 async fn flush(&self) -> SmbResult<()> {
747 match self {
748 LocalHandle::File { file, .. } => {
749 let file = Arc::clone(file);
750 spawn_blocking(move || file.sync_data())
751 .await
752 .map_err(join_to_io)
753 .map_err(io_to_smb)?
754 .map_err(io_to_smb)
755 }
756 LocalHandle::Dir { .. } => Ok(()),
758 }
759 }
760
761 async fn stat(&self) -> SmbResult<FileInfo> {
762 match self {
763 LocalHandle::File {
764 file,
765 name,
766 root_dev,
767 ..
768 } => {
769 let file = Arc::clone(file);
770 let name = name.clone();
771 let root_dev = *root_dev;
772 spawn_blocking(move || -> io::Result<FileInfo> {
773 let md = Metadata::from_file(&file)?;
774 Ok(file_info_from_metadata(name, &md, root_dev))
775 })
776 .await
777 .map_err(join_to_io)
778 .map_err(io_to_smb)?
779 .map_err(io_to_smb)
780 }
781 LocalHandle::Dir {
782 dir_handle,
783 name,
784 root_dev,
785 } => {
786 let dir_handle = Arc::clone(dir_handle);
787 let name = name.clone();
788 let root_dev = *root_dev;
789 spawn_blocking(move || -> io::Result<FileInfo> {
790 let md = dir_handle.dir_metadata()?;
791 Ok(file_info_from_metadata(name, &md, root_dev))
792 })
793 .await
794 .map_err(join_to_io)
795 .map_err(io_to_smb)?
796 .map_err(io_to_smb)
797 }
798 }
799 }
800
801 async fn set_times(&self, times: FileTimes) -> SmbResult<()> {
802 let host_times = host_file_times(times)?;
803 match self {
804 LocalHandle::File {
805 file, read_only, ..
806 } => {
807 if *read_only {
808 return Err(SmbError::AccessDenied);
809 }
810 let file = Arc::clone(file);
811 spawn_blocking(move || file.set_times(host_times))
812 .await
813 .map_err(join_to_io)
814 .map_err(io_to_smb)?
815 .map_err(io_to_smb)
816 }
817 LocalHandle::Dir { dir_handle, .. } => {
818 let dir_handle = Arc::clone(dir_handle);
819 spawn_blocking(move || dir_as_file(&dir_handle)?.set_times(host_times))
820 .await
821 .map_err(join_to_io)
822 .map_err(io_to_smb)?
823 .map_err(io_to_smb)
824 }
825 }
826 }
827
828 async fn set_attributes(&self, attributes: u32) -> SmbResult<()> {
829 if attributes & !(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_ARCHIVE) != 0 {
830 return Err(SmbError::NotSupported);
831 }
832 let read_only = attributes & FILE_ATTRIBUTE_READONLY != 0;
833 match self {
834 LocalHandle::File {
835 file,
836 read_only: backend_read_only,
837 ..
838 } => {
839 if *backend_read_only {
840 return Err(SmbError::AccessDenied);
841 }
842 let file = Arc::clone(file);
843 spawn_blocking(move || set_read_only(&file, read_only))
844 .await
845 .map_err(join_to_io)
846 .map_err(io_to_smb)?
847 .map_err(io_to_smb)
848 }
849 LocalHandle::Dir { .. } if read_only => Err(SmbError::NotSupported),
850 LocalHandle::Dir { .. } => Ok(()),
851 }
852 }
853
854 async fn truncate(&self, len: u64) -> SmbResult<()> {
855 match self {
856 LocalHandle::File {
857 file, read_only, ..
858 } => {
859 if *read_only {
860 return Err(SmbError::AccessDenied);
861 }
862 let file = Arc::clone(file);
863 spawn_blocking(move || file.set_len(len))
864 .await
865 .map_err(join_to_io)
866 .map_err(io_to_smb)?
867 .map_err(io_to_smb)
868 }
869 LocalHandle::Dir { .. } => Err(SmbError::NotSupported),
872 }
873 }
874
875 async fn list_dir(&self, pattern: Option<&str>) -> SmbResult<Vec<SmbDirEntry>> {
876 match self {
877 LocalHandle::File { .. } => Err(SmbError::NotADirectory),
878 LocalHandle::Dir {
879 dir_handle,
880 root_dev,
881 ..
882 } => {
883 let dir_handle = Arc::clone(dir_handle);
884 let root_dev = *root_dev;
885 let pat = pattern.map(|s| s.to_owned());
886 spawn_blocking(move || -> io::Result<Vec<SmbDirEntry>> {
887 let mut out = Vec::new();
888 for entry in dir_handle.entries()? {
889 let entry = entry?;
890 let os_name = entry.file_name();
891 let Some(name) = os_name.to_str().map(str::to_owned) else {
892 continue;
895 };
896 if let Some(p) = pat.as_deref() {
897 if !(p.is_empty() || p == "*" || p == "*.*" || glob_match(p, &name)) {
900 continue;
901 }
902 }
903 let md = entry_metadata(&dir_handle, &entry)?;
904 let info = file_info_from_metadata(name, &md, root_dev);
905 out.push(SmbDirEntry { info });
906 }
907 Ok(out)
908 })
909 .await
910 .map_err(join_to_io)
911 .map_err(io_to_smb)?
912 .map_err(io_to_smb)
913 }
914 }
915 }
916
917 async fn close(self: Box<Self>) -> SmbResult<()> {
918 Ok(())
922 }
923}
924
925#[cfg(test)]
930mod tests {
931 use super::*;
932 use crate::backend::{OpenIntent, OpenOptions};
933 use crate::path::SmbPath;
934 use tempfile::tempdir;
935
936 fn p(s: &str) -> SmbPath {
937 s.parse::<SmbPath>().unwrap()
938 }
939
940 fn opts_create() -> OpenOptions {
941 OpenOptions {
942 read: true,
943 write: true,
944 write_attributes: true,
945 intent: OpenIntent::Create,
946 directory: false,
947 non_directory: false,
948 delete_on_close: false,
949 }
950 }
951
952 fn opts_open_rw() -> OpenOptions {
953 OpenOptions {
954 read: true,
955 write: true,
956 write_attributes: true,
957 intent: OpenIntent::Open,
958 directory: false,
959 non_directory: false,
960 delete_on_close: false,
961 }
962 }
963
964 fn opts_open_ro() -> OpenOptions {
965 OpenOptions {
966 read: true,
967 write: false,
968 write_attributes: false,
969 intent: OpenIntent::Open,
970 directory: false,
971 non_directory: false,
972 delete_on_close: false,
973 }
974 }
975
976 fn opts_open_dir() -> OpenOptions {
977 OpenOptions {
978 read: true,
979 write: false,
980 write_attributes: false,
981 intent: OpenIntent::Open,
982 directory: true,
983 non_directory: false,
984 delete_on_close: false,
985 }
986 }
987
988 #[tokio::test]
989 async fn create_write_read_stat_close() {
990 let td = tempdir().unwrap();
991 let backend = LocalFsBackend::new(td.path()).unwrap();
992
993 let h = backend.open(&p("hello.txt"), opts_create()).await.unwrap();
995 let n = h.write(0, b"hello world").await.unwrap();
996 assert_eq!(n, 11);
997 h.flush().await.unwrap();
998
999 let info = h.stat().await.unwrap();
1001 assert_eq!(info.name, "hello.txt");
1002 assert_eq!(info.end_of_file, 11);
1003 assert!(!info.is_directory);
1004 assert!(info.last_write_time > 0);
1005 h.close().await.unwrap();
1006
1007 let h2 = backend.open(&p("hello.txt"), opts_open_ro()).await.unwrap();
1009 let bytes = h2.read(0, 1024).await.unwrap();
1010 assert_eq!(&bytes[..], b"hello world");
1011
1012 let bytes = h2.read(6, 1024).await.unwrap();
1014 assert_eq!(&bytes[..], b"world");
1015
1016 let bytes = h2.read(100, 1024).await.unwrap();
1018 assert!(bytes.is_empty());
1019 h2.close().await.unwrap();
1020 }
1021
1022 #[tokio::test]
1023 async fn list_dir_finds_created_file() {
1024 let td = tempdir().unwrap();
1025 let backend = LocalFsBackend::new(td.path()).unwrap();
1026 let h = backend.open(&p("a.txt"), opts_create()).await.unwrap();
1027 h.close().await.unwrap();
1028
1029 let dir_h = backend
1030 .open(&SmbPath::root(), opts_open_dir())
1031 .await
1032 .unwrap();
1033 let entries = dir_h.list_dir(None).await.unwrap();
1034 assert!(entries.iter().any(|e| e.info.name == "a.txt"));
1035 dir_h.close().await.unwrap();
1036 }
1037
1038 #[tokio::test]
1039 async fn read_only_rejects_writes() {
1040 let td = tempdir().unwrap();
1041 {
1044 let writable = LocalFsBackend::new(td.path()).unwrap();
1045 let h = writable.open(&p("x.txt"), opts_create()).await.unwrap();
1046 h.close().await.unwrap();
1047 }
1048
1049 let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
1050 assert!(backend.capabilities().is_read_only);
1051
1052 let err = backend
1054 .open(&p("x.txt"), opts_open_rw())
1055 .await
1056 .err()
1057 .unwrap();
1058 assert!(matches!(err, SmbError::AccessDenied));
1059
1060 let err = backend
1062 .open(&p("y.txt"), opts_create())
1063 .await
1064 .err()
1065 .unwrap();
1066 assert!(matches!(err, SmbError::AccessDenied));
1067
1068 let h = backend.open(&p("x.txt"), opts_open_ro()).await.unwrap();
1070 assert!(matches!(
1071 h.write(0, b"x").await,
1072 Err(SmbError::AccessDenied)
1073 ));
1074 h.close().await.unwrap();
1075
1076 let err = backend.unlink(&p("x.txt")).await.err().unwrap();
1078 assert!(matches!(err, SmbError::AccessDenied));
1079 }
1080
1081 #[tokio::test]
1082 async fn unlink_file_then_nonempty_dir_errors() {
1083 let td = tempdir().unwrap();
1084 let backend = LocalFsBackend::new(td.path()).unwrap();
1085
1086 let h = backend.open(&p("doomed.txt"), opts_create()).await.unwrap();
1088 h.close().await.unwrap();
1089 backend.unlink(&p("doomed.txt")).await.unwrap();
1090 assert!(matches!(
1091 backend.unlink(&p("doomed.txt")).await.err().unwrap(),
1092 SmbError::NotFound
1093 ));
1094
1095 std::fs::create_dir(td.path().join("dir1")).unwrap();
1097 std::fs::write(td.path().join("dir1").join("inside"), b"x").unwrap();
1098
1099 let err = backend.unlink(&p("dir1")).await.err().unwrap();
1100 assert!(
1101 matches!(err, SmbError::NotEmpty),
1102 "expected NotEmpty, got {err:?}"
1103 );
1104
1105 std::fs::remove_file(td.path().join("dir1").join("inside")).unwrap();
1107 backend.unlink(&p("dir1")).await.unwrap();
1108 }
1109
1110 #[tokio::test]
1111 async fn rename_within_root() {
1112 let td = tempdir().unwrap();
1113 let backend = LocalFsBackend::new(td.path()).unwrap();
1114
1115 let h = backend.open(&p("old.txt"), opts_create()).await.unwrap();
1116 h.write(0, b"data").await.unwrap();
1117 h.close().await.unwrap();
1118
1119 backend
1120 .rename(&p("old.txt"), &p("new.txt"), false)
1121 .await
1122 .unwrap();
1123 assert!(td.path().join("new.txt").exists());
1124 assert!(!td.path().join("old.txt").exists());
1125
1126 let h = backend.open(&p("other.txt"), opts_create()).await.unwrap();
1128 h.close().await.unwrap();
1129 let err = backend
1130 .rename(&p("other.txt"), &p("new.txt"), false)
1131 .await
1132 .err()
1133 .unwrap();
1134 assert!(matches!(err, SmbError::Exists), "got {err:?}");
1135 }
1136
1137 #[tokio::test]
1138 async fn rename_onto_itself_is_not_a_collision() {
1139 let td = tempdir().unwrap();
1140 std::fs::write(td.path().join("doc.txt"), b"old").unwrap();
1141 let backend = LocalFsBackend::new(td.path()).unwrap();
1142 backend
1143 .rename(&p("doc.txt"), &p("doc.txt"), false)
1144 .await
1145 .unwrap();
1146 assert_eq!(std::fs::read(td.path().join("doc.txt")).unwrap(), b"old");
1147 }
1148
1149 #[cfg(unix)]
1150 #[tokio::test]
1151 async fn rename_between_hard_links_follows_collision_rules() {
1152 let td = tempdir().unwrap();
1153 let root = td.path();
1154 std::fs::write(root.join("a.txt"), b"data").unwrap();
1155 std::fs::hard_link(root.join("a.txt"), root.join("b.txt")).unwrap();
1156 let backend = LocalFsBackend::new(root).unwrap();
1157
1158 let err = backend
1159 .rename(&p("a.txt"), &p("b.txt"), false)
1160 .await
1161 .unwrap_err();
1162 assert!(matches!(err, SmbError::Exists), "got {err:?}");
1163 assert!(root.join("a.txt").exists());
1164
1165 backend
1166 .rename(&p("a.txt"), &p("b.txt"), true)
1167 .await
1168 .unwrap();
1169 assert!(!root.join("a.txt").exists());
1170 assert_eq!(std::fs::read(root.join("b.txt")).unwrap(), b"data");
1171 }
1172
1173 #[tokio::test]
1174 async fn directory_file_index_is_the_same_for_every_open_and_listing() {
1175 let td = tempdir().unwrap();
1176 std::fs::create_dir(td.path().join("d")).unwrap();
1177 let backend = LocalFsBackend::new(td.path()).unwrap();
1178
1179 let root = backend
1180 .open(&SmbPath::root(), opts_open_dir())
1181 .await
1182 .unwrap();
1183 let listed = root.list_dir(None).await.unwrap();
1184 let first = backend.open(&p("d"), opts_open_dir()).await.unwrap();
1185 let second = backend.open(&p("d"), opts_open_dir()).await.unwrap();
1186 let id = first.stat().await.unwrap().file_index;
1187 assert_ne!(id, 0);
1188 assert_eq!(second.stat().await.unwrap().file_index, id);
1189 let entry = listed.iter().find(|e| e.info.name == "d").unwrap();
1190 assert_eq!(entry.info.file_index, id);
1191 }
1192
1193 #[test]
1194 fn file_index_keeps_root_device_inodes_and_separates_other_devices() {
1195 let root = Some(0x803);
1196 assert_eq!(file_index(root, Some((0x803, 42))), 42);
1197 assert_eq!(file_index(None, Some((0x803, 42))), 42);
1198 assert_eq!(file_index(root, None), 0);
1199 assert_ne!(
1200 file_index(root, Some((0x803, 1))),
1201 file_index(root, Some((0x2b, 1)))
1202 );
1203 }
1204
1205 #[cfg(unix)]
1206 #[tokio::test]
1207 async fn file_index_is_the_inode_on_the_root_device() {
1208 use std::os::unix::fs::MetadataExt as _;
1209
1210 let td = tempdir().unwrap();
1211 std::fs::write(td.path().join("f.txt"), b"x").unwrap();
1212 let backend = LocalFsBackend::new(td.path()).unwrap();
1213 let h = backend.open(&p("f.txt"), opts_open_ro()).await.unwrap();
1214 let ino = std::fs::metadata(td.path().join("f.txt")).unwrap().ino();
1215 assert_eq!(h.stat().await.unwrap().file_index, ino);
1216 }
1217
1218 #[cfg(target_os = "linux")]
1221 #[tokio::test]
1222 async fn file_index_differs_across_mounts_with_equal_inodes() {
1223 use std::os::unix::fs::MetadataExt as _;
1224
1225 let mounts: Vec<_> = ["proc", "sys", "dev", "tmp"]
1226 .into_iter()
1227 .filter_map(|name| {
1228 let md = std::fs::metadata(Path::new("/").join(name)).ok()?;
1229 Some((name, md.dev(), md.ino()))
1230 })
1231 .collect();
1232 let pair = mounts.iter().enumerate().find_map(|(i, a)| {
1233 mounts[i + 1..]
1234 .iter()
1235 .find(|b| a.1 != b.1 && a.2 == b.2)
1236 .map(|b| (a.0, b.0))
1237 });
1238 let Some((a, b)) = pair else {
1239 eprintln!("no two mounts below / share an inode number; skipping");
1240 return;
1241 };
1242 let backend = LocalFsBackend::new("/").unwrap();
1243 let root = backend
1244 .open(&SmbPath::root(), opts_open_dir())
1245 .await
1246 .unwrap();
1247 let listed = root.list_dir(None).await.unwrap();
1248 let mut ids = Vec::new();
1249 for name in [a, b] {
1250 let h = backend.open(&p(name), opts_open_dir()).await.unwrap();
1251 let id = h.stat().await.unwrap().file_index;
1252 let entry = listed.iter().find(|e| e.info.name == name).unwrap();
1253 assert_eq!(entry.info.file_index, id, "{name}");
1254 ids.push(id);
1255 }
1256 assert_ne!(ids[0], ids[1], "{a} and {b}");
1257 }
1258
1259 #[cfg(unix)]
1260 #[tokio::test]
1261 async fn unlink_removes_empty_dirs_and_symlinks_as_links() {
1262 use std::os::unix::fs::symlink;
1263
1264 let td = tempdir().unwrap();
1265 let outside = tempdir().unwrap();
1266 std::fs::write(outside.path().join("keep.txt"), b"x").unwrap();
1267 let root = td.path();
1268 std::fs::create_dir(root.join("empty")).unwrap();
1269 std::fs::create_dir(root.join("target")).unwrap();
1270 std::fs::write(root.join("target").join("inside.txt"), b"x").unwrap();
1271 symlink(root.join("target"), root.join("link_in")).unwrap();
1272 symlink(outside.path(), root.join("link_out")).unwrap();
1273 symlink(root.join("missing"), root.join("dangling")).unwrap();
1274 let backend = LocalFsBackend::new(root).unwrap();
1275
1276 backend.unlink(&p("empty")).await.unwrap();
1277 assert!(!root.join("empty").exists());
1278
1279 for link in ["link_in", "link_out", "dangling"] {
1280 backend.unlink(&p(link)).await.unwrap();
1281 assert!(root.join(link).symlink_metadata().is_err(), "{link}");
1282 }
1283 assert!(root.join("target").join("inside.txt").exists());
1284 assert!(outside.path().join("keep.txt").exists());
1285 }
1286
1287 #[test]
1288 fn cross_device_error_maps_to_not_same_device() {
1289 assert!(matches!(
1290 io_to_smb(io::ErrorKind::CrossesDevices.into()),
1291 SmbError::NotSameDevice
1292 ));
1293 }
1294
1295 #[tokio::test]
1296 async fn list_dir_pattern_matching() {
1297 let td = tempdir().unwrap();
1298 let backend = LocalFsBackend::new(td.path()).unwrap();
1299
1300 for name in ["a.txt", "b.txt", "c.log", "README"] {
1301 let h = backend.open(&p(name), opts_create()).await.unwrap();
1302 h.close().await.unwrap();
1303 }
1304
1305 let dir_h = backend
1306 .open(&SmbPath::root(), opts_open_dir())
1307 .await
1308 .unwrap();
1309
1310 let txts = dir_h.list_dir(Some("*.txt")).await.unwrap();
1311 let names: Vec<_> = txts.iter().map(|e| e.info.name.as_str()).collect();
1312 assert_eq!(names.len(), 2, "expected 2 .txt files, got {names:?}");
1313 assert!(names.contains(&"a.txt"));
1314 assert!(names.contains(&"b.txt"));
1315
1316 let one = dir_h.list_dir(Some("?.log")).await.unwrap();
1318 let names: Vec<_> = one.iter().map(|e| e.info.name.as_str()).collect();
1319 assert_eq!(names, vec!["c.log"]);
1320
1321 let any_txt = dir_h.list_dir(Some("*.TXT")).await.unwrap();
1323 assert_eq!(any_txt.len(), 2);
1324
1325 let all = dir_h.list_dir(Some("*")).await.unwrap();
1327 assert_eq!(all.len(), 4);
1328
1329 dir_h.close().await.unwrap();
1330 }
1331
1332 #[test]
1333 fn glob_match_basics() {
1334 assert!(glob_match("*", "anything"));
1335 assert!(glob_match("*.txt", "foo.txt"));
1336 assert!(!glob_match("*.txt", "foo.log"));
1337 assert!(glob_match("a?c", "abc"));
1338 assert!(!glob_match("a?c", "ac"));
1339 assert!(glob_match("a*b*c", "axxxbxxxc"));
1340 assert!(glob_match("FOO", "foo"));
1341 assert!(glob_match("", ""));
1342 assert!(!glob_match("", "a"));
1343 }
1344
1345 #[test]
1346 fn glob_match_dos_wildcards() {
1347 assert!(glob_match("<.txt", "ow.txt"));
1349 assert!(glob_match("<.txt", "a.b.txt"));
1350 assert!(glob_match("<.TXT", "ow.txt"));
1351 assert!(!glob_match("<.txt", "ow.log"));
1352 assert!(!glob_match("<", "a.b"));
1353 assert!(glob_match("<", "noext"));
1354 assert!(glob_match("<.<", "a.b"));
1355 assert!(glob_match(">w.txt", "ow.txt"));
1357 assert!(!glob_match(">w.txt", "w.txt"));
1358 assert!(glob_match(">>>.txt", "ab.txt"));
1359 assert!(glob_match("a>>", "a"));
1360 assert!(!glob_match("a>", "abc"));
1361 assert!(glob_match("a\"txt", "a.txt"));
1363 assert!(glob_match("abc\"", "abc"));
1364 assert!(!glob_match("a\"txt", "aXtxt"));
1365 assert!(glob_match("<\"<", "a.b"));
1366 assert!(glob_match("<\"<", "noext"));
1367 assert!(glob_match("<\"", "noext"));
1368 assert!(!glob_match("<\"", "a.b"));
1369 }
1370
1371 #[cfg(windows)]
1372 #[test]
1373 fn sharing_violation_maps_to_sharing() {
1374 const ERROR_SHARING_VIOLATION: i32 = 32;
1375 assert!(matches!(
1376 io_to_smb(io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)),
1377 SmbError::Sharing
1378 ));
1379 }
1380
1381 #[tokio::test]
1382 async fn directory_unlinks_while_open() {
1383 let td = tempdir().unwrap();
1384 std::fs::create_dir(td.path().join("d")).unwrap();
1385 let backend = LocalFsBackend::new(td.path()).unwrap();
1386 let h = backend.open(&p("d"), opts_open_dir()).await.unwrap();
1387 backend.unlink(&p("d")).await.unwrap();
1388 assert!(!td.path().join("d").exists());
1389 h.close().await.unwrap();
1390 }
1391
1392 fn filetime(secs: u64) -> u64 {
1393 system_time_to_filetime(UNIX_EPOCH + Duration::from_secs(secs))
1394 }
1395
1396 #[tokio::test]
1397 async fn creation_time_is_set_where_the_host_can() {
1398 let td = tempdir().unwrap();
1399 let backend = LocalFsBackend::new(td.path()).unwrap();
1400 let h = backend.open(&p("f.txt"), opts_create()).await.unwrap();
1401 let before = h.stat().await.unwrap();
1402 let t = filetime(1_557_126_489);
1403 h.set_times(FileTimes {
1404 creation_time: Some(t),
1405 ..FileTimes::default()
1406 })
1407 .await
1408 .unwrap();
1409 let after = h.stat().await.unwrap();
1410 if cfg!(any(windows, target_os = "macos")) {
1411 assert_eq!(after.creation_time, t);
1412 } else {
1413 assert_eq!(after.creation_time, before.creation_time);
1414 }
1415 assert_eq!(after.last_write_time, before.last_write_time);
1416 h.close().await.unwrap();
1417 }
1418
1419 #[tokio::test]
1420 async fn creation_time_does_not_block_the_other_times() {
1421 let td = tempdir().unwrap();
1422 let backend = LocalFsBackend::new(td.path()).unwrap();
1423 let h = backend.open(&p("f.txt"), opts_create()).await.unwrap();
1424 let created = filetime(1_557_126_489);
1425 let written = filetime(1_577_934_245);
1426 h.set_times(FileTimes {
1427 creation_time: Some(created),
1428 last_access_time: Some(written),
1429 last_write_time: Some(written),
1430 ..FileTimes::default()
1431 })
1432 .await
1433 .unwrap();
1434 let info = h.stat().await.unwrap();
1435 assert_eq!(info.last_write_time, written);
1436 assert_eq!(info.last_access_time, written);
1437 if cfg!(any(windows, target_os = "macos")) {
1438 assert_eq!(info.creation_time, created);
1439 }
1440 h.close().await.unwrap();
1441 }
1442
1443 #[tokio::test]
1444 async fn unsupported_attributes_are_rejected() {
1445 let td = tempdir().unwrap();
1446 std::fs::create_dir(td.path().join("d")).unwrap();
1447 let backend = LocalFsBackend::new(td.path()).unwrap();
1448 let h = backend.open(&p("f.txt"), opts_create()).await.unwrap();
1449 assert!(matches!(
1450 h.set_attributes(0x2).await,
1451 Err(SmbError::NotSupported)
1452 ));
1453 h.close().await.unwrap();
1454
1455 let dir = backend.open(&p("d"), opts_open_dir()).await.unwrap();
1456 assert!(matches!(
1457 dir.set_attributes(FILE_ATTRIBUTE_READONLY).await,
1458 Err(SmbError::NotSupported)
1459 ));
1460 dir.set_attributes(0).await.unwrap();
1461 dir.close().await.unwrap();
1462 }
1463
1464 #[test]
1465 fn filetime_round_trip() {
1466 let now = SystemTime::now();
1467 let ft = system_time_to_filetime(now);
1468 let back = filetime_to_system_time(ft).unwrap();
1469 let delta = now
1470 .duration_since(back)
1471 .or_else(|e| Ok::<_, std::time::SystemTimeError>(e.duration()))
1472 .unwrap();
1473 assert!(delta < Duration::from_micros(1), "delta = {delta:?}");
1475 }
1476}