This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new a3088455df fix(core,services/fs): fix std::io directory error mapping
and fs copy, read, list, and config bugs (#8984)
a3088455df is described below
commit a3088455dfd2ee1b3c237d17ea4b88daed002632
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 13:27:52 2026 +0800
fix(core,services/fs): fix std::io directory error mapping and fs copy,
read, list, and config bugs (#8984)
---
core/core/src/raw/std_io_util.rs | 20 ++-
core/services/fs/src/backend.rs | 125 +++++++++++++++---
core/services/fs/src/core.rs | 204 +++++++++++++++++++++++++++--
core/services/fs/src/direct_io.rs | 11 ++
core/services/fs/src/lister.rs | 83 ++++++++----
core/services/fs/src/reader.rs | 76 ++++++++++-
core/services/fs/tests/direct_io.rs | 26 ++++
core/services/fs/tests/list_start_after.rs | 113 ++++++++++++++++
8 files changed, 593 insertions(+), 65 deletions(-)
diff --git a/core/core/src/raw/std_io_util.rs b/core/core/src/raw/std_io_util.rs
index 3fa9f0487e..a0ceee67b2 100644
--- a/core/core/src/raw/std_io_util.rs
+++ b/core/core/src/raw/std_io_util.rs
@@ -20,12 +20,6 @@ use std::io;
use crate::*;
/// Parse std io error into opendal::Error.
-///
-/// # TODO
-///
-/// Add `NotADirectory` and `IsADirectory` once they are stable.
-///
-/// ref: <https://github.com/rust-lang/rust/issues/86442>
pub fn new_std_io_error(err: io::Error) -> Error {
use std::io::ErrorKind::*;
@@ -33,6 +27,8 @@ pub fn new_std_io_error(err: io::Error) -> Error {
NotFound => (ErrorKind::NotFound, false),
PermissionDenied => (ErrorKind::PermissionDenied, false),
AlreadyExists => (ErrorKind::AlreadyExists, false),
+ IsADirectory => (ErrorKind::IsADirectory, false),
+ NotADirectory => (ErrorKind::NotADirectory, false),
Unsupported => (ErrorKind::Unsupported, false),
Interrupted | UnexpectedEof | TimedOut | WouldBlock =>
(ErrorKind::Unexpected, true),
@@ -68,6 +64,18 @@ pub(crate) fn format_std_io_error(err: Error) -> io::Error {
mod tests {
use super::*;
+ #[test]
+ fn test_new_std_io_error_directory_kinds_are_permanent() {
+ for (io_kind, expected_kind) in [
+ (io::ErrorKind::IsADirectory, ErrorKind::IsADirectory),
+ (io::ErrorKind::NotADirectory, ErrorKind::NotADirectory),
+ ] {
+ let err = new_std_io_error(io::Error::from(io_kind));
+ assert_eq!(err.kind(), expected_kind);
+ assert!(!err.is_temporary(), "{err:?}");
+ }
+ }
+
#[test]
fn test_read_to_end_stops_on_persistent_error() {
struct ErrorThenEof {
diff --git a/core/services/fs/src/backend.rs b/core/services/fs/src/backend.rs
index ac18c98f54..3ebc5095da 100644
--- a/core/services/fs/src/backend.rs
+++ b/core/services/fs/src/backend.rs
@@ -61,9 +61,11 @@ impl FsBuilder {
/// a hard link elsewhere. Both need the staging directory and the
/// destination on the same filesystem.
pub fn atomic_write_dir(mut self, dir: &str) -> Self {
- if !dir.is_empty() {
- self.config.atomic_write_dir = Some(dir.to_string());
- }
+ self.config.atomic_write_dir = if dir.is_empty() {
+ None
+ } else {
+ Some(dir.to_string())
+ };
self
}
@@ -89,7 +91,12 @@ impl Builder for FsBuilder {
));
}
- let root = match self.config.root.map(PathBuf::from) {
+ let root = match self
+ .config
+ .root
+ .filter(|s| !s.is_empty())
+ .map(PathBuf::from)
+ {
Some(root) => Ok(root),
None => Err(Error::new(
ErrorKind::ConfigInvalid,
@@ -98,10 +105,44 @@ impl Builder for FsBuilder {
}?;
debug!("backend use root {}", root.to_string_lossy());
- // If root dir is not exist, we must create it.
- if let Err(e) = std::fs::metadata(&root)
- && e.kind() == std::io::ErrorKind::NotFound
- {
+ let atomic_write_dir = self
+ .config
+ .atomic_write_dir
+ .filter(|s| !s.is_empty())
+ .map(PathBuf::from);
+
+ let root_exists = match std::fs::metadata(&root) {
+ Ok(meta) if !meta.is_dir() => {
+ return Err(
+ Error::new(ErrorKind::ConfigInvalid, "root is not a
directory")
+ .with_operation("Builder::build")
+ .with_context("root", root.to_string_lossy()),
+ );
+ }
+ Ok(_) => true,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
+ Err(_) => true,
+ };
+
+ let atomic_write_dir_exists = match &atomic_write_dir {
+ Some(d) => match std::fs::metadata(d) {
+ Ok(meta) if !meta.is_dir() => {
+ return Err(Error::new(
+ ErrorKind::ConfigInvalid,
+ "atomic_write_dir is not a directory",
+ )
+ .with_operation("Builder::build")
+ .with_context("atomic_write_dir", d.to_string_lossy()));
+ }
+ Ok(_) => true,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
+ Err(_) => true,
+ },
+ None => true,
+ };
+
+ // If root dir does not exist, we must create it.
+ if !root_exists {
std::fs::create_dir_all(&root).map_err(|e| {
Error::new(ErrorKind::Unexpected, "create root dir failed")
.with_operation("Builder::build")
@@ -110,13 +151,8 @@ impl Builder for FsBuilder {
})?;
}
- let atomic_write_dir = self.config.atomic_write_dir.map(PathBuf::from);
-
- // If atomic write dir is not exist, we must create it.
- if let Some(d) = &atomic_write_dir
- && let Err(e) = std::fs::metadata(d)
- && e.kind() == std::io::ErrorKind::NotFound
- {
+ // If atomic write dir does not exist, we must create it.
+ if !atomic_write_dir_exists && let Some(d) = &atomic_write_dir {
std::fs::create_dir_all(d).map_err(|e| {
Error::new(ErrorKind::Unexpected, "create atomic write dir
failed")
.with_operation("Builder::build")
@@ -316,3 +352,62 @@ pub(crate) fn read_at(f: &File, buf: &mut [u8], offset:
u64) -> Result<usize> {
use std::os::unix::fs::FileExt;
f.read_at(buf, offset).map_err(new_std_io_error)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_builder_config_validation() {
+ let temp = tempfile::tempdir().unwrap();
+ let file_path = temp.path().join("not_a_dir");
+ std::fs::write(&file_path, b"data").unwrap();
+ let valid_root = temp.path().join("valid_root");
+ std::fs::create_dir(&valid_root).unwrap();
+
+ // Empty root is rejected with ConfigInvalid both via builder and
from_iter.
+ let err = FsBuilder::default().root("").build().err().unwrap();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid, "{err:?}");
+
+ let cfg = FsConfig::from_iter([("root".to_string(),
String::new())]).unwrap();
+ let err = cfg.into_builder().build().err().unwrap();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid, "{err:?}");
+
+ // Empty atomic_write_dir via from_iter is treated as unset.
+ let cfg = FsConfig::from_iter([
+ ("root".to_string(), valid_root.to_str().unwrap().to_string()),
+ ("atomic_write_dir".to_string(), String::new()),
+ ])
+ .unwrap();
+ let backend = cfg.into_builder().build().unwrap();
+ assert!(backend.info().scheme() == FS_SCHEME);
+
+ // Passing an empty string to atomic_write_dir() clears a previously
set path.
+ let backend = FsBuilder::default()
+ .root(valid_root.to_str().unwrap())
+ .atomic_write_dir(file_path.to_str().unwrap())
+ .atomic_write_dir("")
+ .build()
+ .unwrap();
+ assert!(backend.info().scheme() == FS_SCHEME);
+
+ // Existing regular file as root is rejected with ConfigInvalid.
+ let err = FsBuilder::default()
+ .root(file_path.to_str().unwrap())
+ .build()
+ .err()
+ .unwrap();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid, "{err:?}");
+
+ // Existing regular file as atomic_write_dir is rejected before
creating root.
+ let new_root = temp.path().join("should_not_be_created");
+ let err = FsBuilder::default()
+ .root(new_root.to_str().unwrap())
+ .atomic_write_dir(file_path.to_str().unwrap())
+ .build()
+ .err()
+ .unwrap();
+ assert_eq!(err.kind(), ErrorKind::ConfigInvalid, "{err:?}");
+ assert!(!new_root.exists());
+ }
+}
diff --git a/core/services/fs/src/core.rs b/core/services/fs/src/core.rs
index 869fe55a29..014745d761 100644
--- a/core/services/fs/src/core.rs
+++ b/core/services/fs/src/core.rs
@@ -140,19 +140,44 @@ impl FsCore {
pub async fn fs_copy(&self, from: &str, to: &str) -> Result<u64> {
let from = self.root_join(from)?;
- // try to get the metadata of the source file to ensure it exists
- tokio::fs::metadata(&from).await.map_err(new_std_io_error)?;
+ // Fetch source metadata first so missing or directory sources fail
+ // before creating destination parent directories.
+ let from_meta =
tokio::fs::metadata(&from).await.map_err(new_std_io_error)?;
+ if from_meta.is_dir() {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "copy source is a directory",
+ ));
+ }
- // Read source user metadata before copying: copying onto the same path
- // would otherwise read the replaced destination. A source whose user
+ let to_trimmed = to.trim_end_matches('/');
+ let to_path = self.root_join(to_trimmed)?;
+ match tokio::fs::metadata(&to_path).await {
+ Ok(to_meta) => {
+ if to_meta.is_dir() {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "copy target is a directory",
+ ));
+ }
+ if is_same_file(&from, &from_meta, &to_path, &to_meta).await {
+ return Err(Error::new(
+ ErrorKind::IsSameFile,
+ "copy source and destination refer to the same file",
+ ));
+ }
+ }
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
+ Err(err) => return Err(new_std_io_error(err)),
+ }
+
+ // Read source user metadata before copying. A source whose user
// metadata cannot be read keeps the previous copy behavior of not
// failing the content copy.
#[cfg(unix)]
let user_metadata = Self::get_user_metadata(&from).ok();
- let to = self
- .ensure_write_abs_path(&self.root, to.trim_end_matches('/'))
- .await?;
+ let to = self.ensure_write_abs_path(&self.root, to_trimmed).await?;
let size = tokio::fs::copy(&from, &to)
.await
@@ -201,7 +226,7 @@ impl FsCore {
tokio::fs::rename(from, to)
.await
- .map_err(new_std_io_error)?;
+ .map_err(parse_rename_error)?;
Ok(())
}
@@ -463,6 +488,31 @@ pub(crate) fn parse_error(ctx: ErrorContext, err:
std::io::Error) -> Error {
parse_io_error(err, true).with_context("service_operation",
ctx.service_operation.0)
}
+async fn is_same_file(
+ from: &Path,
+ from_meta: &std::fs::Metadata,
+ to: &Path,
+ to_meta: &std::fs::Metadata,
+) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ let _ = (from, to);
+ from_meta.dev() == to_meta.dev() && from_meta.ino() == to_meta.ino()
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = (from_meta, to_meta);
+ matches!(
+ (
+ tokio::fs::canonicalize(from).await,
+ tokio::fs::canonicalize(to).await,
+ ),
+ (Ok(from_canon), Ok(to_canon)) if from_canon == to_canon
+ )
+ }
+}
+
fn parse_io_error(err: std::io::Error, already_exists_as_condition: bool) ->
Error {
match err.kind() {
std::io::ErrorKind::AlreadyExists if already_exists_as_condition =>
Error::new(
@@ -470,12 +520,6 @@ fn parse_io_error(err: std::io::Error,
already_exists_as_condition: bool) -> Err
"The file already exists in the filesystem",
)
.set_source(err),
- std::io::ErrorKind::IsADirectory => {
- Error::new(ErrorKind::IsADirectory,
err.kind().to_string()).set_source(err)
- }
- std::io::ErrorKind::NotADirectory => {
- Error::new(ErrorKind::NotADirectory,
err.kind().to_string()).set_source(err)
- }
_ => {
#[cfg(unix)]
if err.raw_os_error() == Some(libc::EXDEV) {
@@ -863,4 +907,136 @@ mod tests {
assert_eq!(err.kind(), ErrorKind::NotFound);
assert_eq!(std::fs::read(&outside).unwrap(), b"content");
}
+
+ #[tokio::test]
+ async fn test_directory_errors_are_permanent() {
+ let temp_dir = tempfile::TempDir::new().unwrap();
+ let root = temp_dir.path();
+ std::fs::write(root.join("src"), b"data").unwrap();
+ std::fs::write(root.join("file"), b"data").unwrap();
+ std::fs::create_dir(root.join("existing_dir")).unwrap();
+
+ let op =
Operator::new(crate::Fs::default().root(root.to_str().unwrap())).unwrap();
+
+ let err = op.rename("src", "existing_dir").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ for (from, to) in [("file/child", "dst"), ("src", "file/dir/dst")] {
+ let err = op.rename(from, to).await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::NotADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ }
+
+ let err = op.copy("src", "existing_dir").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let err = op.copy("src", "file/dir/dst").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::NotADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let err = op.write("existing_dir", "x").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ }
+
+ #[tokio::test]
+ async fn test_copy_directory_source_rejects_before_creating_parents() {
+ let temp_dir = tempfile::TempDir::new().unwrap();
+ let root = temp_dir.path();
+ std::fs::create_dir(root.join("dir")).unwrap();
+ std::fs::write(root.join("existing.txt"), b"keep").unwrap();
+
+ let op =
Operator::new(crate::Fs::default().root(root.to_str().unwrap())).unwrap();
+
+ let err = op.copy("dir", "existing.txt").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ assert_eq!(std::fs::read(root.join("existing.txt")).unwrap(), b"keep");
+
+ let err = op.copy("dir", "new_parent/missing").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ assert!(!root.join("new_parent").exists());
+
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink("dir", root.join("dir_link")).unwrap();
+ let err = op
+ .copy("dir_link", "new_parent_link/missing")
+ .await
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ assert!(!root.join("new_parent_link").exists());
+ }
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn test_copy_same_file_via_symlink_and_hardlink_preserves_content() {
+ let temp_dir = tempfile::TempDir::new().unwrap();
+ let root = temp_dir.path();
+ let has_xattrs = xattrs_supported(root);
+
+ let op =
Operator::new(crate::Fs::default().root(root.to_str().unwrap())).unwrap();
+ if has_xattrs {
+ op.write_with("real.txt", "important")
+ .user_metadata([("k".to_string(), "v".to_string())])
+ .await
+ .unwrap();
+ } else {
+ op.write("real.txt", "important").await.unwrap();
+ }
+
+ std::os::unix::fs::symlink("real.txt", root.join("link.txt")).unwrap();
+ std::fs::hard_link(root.join("real.txt"),
root.join("hard.txt")).unwrap();
+
+ for (from, to) in [
+ ("real.txt", "link.txt"),
+ ("link.txt", "real.txt"),
+ ("real.txt", "hard.txt"),
+ ("hard.txt", "real.txt"),
+ ("link.txt", "hard.txt"),
+ ] {
+ let err = op.copy(from, to).await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsSameFile, "{from} -> {to}:
{err:?}");
+ assert_eq!(
+ std::fs::read(root.join("real.txt")).unwrap(),
+ b"important",
+ "{from} -> {to} must not truncate source"
+ );
+ if has_xattrs {
+ let meta = op.stat("real.txt").await.unwrap();
+ assert_eq!(meta.user_metadata().and_then(|m| m.get("k")),
Some("v"));
+ }
+ }
+
+ // Copying from a dangling symlink still fails with NotFound.
+ std::os::unix::fs::symlink("missing.txt",
root.join("broken_src.txt")).unwrap();
+ let err = op.copy("broken_src.txt", "dst.txt").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::NotFound, "{err:?}");
+
+ // Copying to a non-existent destination and to a different
file/dangling symlink
+ // still succeeds normally.
+ op.copy("real.txt", "nested/copied.txt").await.unwrap();
+ assert_eq!(
+ std::fs::read(root.join("nested/copied.txt")).unwrap(),
+ b"important"
+ );
+
+ op.write("plain.txt", "payload").await.unwrap();
+ std::fs::write(root.join("other.txt"), b"old").unwrap();
+ std::os::unix::fs::symlink("other.txt",
root.join("other_link.txt")).unwrap();
+ op.copy("plain.txt", "other_link.txt").await.unwrap();
+ assert_eq!(std::fs::read(root.join("other.txt")).unwrap(), b"payload");
+
+ std::os::unix::fs::symlink("created_via_link.txt",
root.join("dangle_dst.txt")).unwrap();
+ op.copy("plain.txt", "dangle_dst.txt").await.unwrap();
+ assert_eq!(
+ std::fs::read(root.join("created_via_link.txt")).unwrap(),
+ b"payload"
+ );
+ }
}
diff --git a/core/services/fs/src/direct_io.rs
b/core/services/fs/src/direct_io.rs
index d81230b871..6ccc75e22f 100644
--- a/core/services/fs/src/direct_io.rs
+++ b/core/services/fs/src/direct_io.rs
@@ -45,6 +45,12 @@ impl DirectIoAlignment {
operation: ServiceOperation,
) -> Result<(File, Self)> {
let file = Self::open_raw(path, options, operation)?;
+ if file.metadata().map_err(new_std_io_error)?.is_dir() {
+ return Err(
+ Error::new(OpendalErrorKind::IsADirectory, "read path is a
directory")
+ .with_context("service_operation", operation.0),
+ );
+ }
Self::discover_or_cleanup(path, file, operation, false)
}
@@ -116,6 +122,11 @@ impl DirectIoAlignment {
if code == Errno::INVAL.raw_os_error()
|| code == Errno::OPNOTSUPP.raw_os_error() =>
{
+ if std::fs::metadata(path).is_ok_and(|meta| meta.is_dir())
{
+ return Error::new(OpendalErrorKind::IsADirectory,
"path is a directory")
+ .with_context("service_operation", operation.0)
+ .set_source(err);
+ }
Error::new(OpendalErrorKind::Unsupported, "O_DIRECT open
failed")
.with_context("service_operation", operation.0)
.set_source(err)
diff --git a/core/services/fs/src/lister.rs b/core/services/fs/src/lister.rs
index 6c1df2457c..09ad5f302e 100644
--- a/core/services/fs/src/lister.rs
+++ b/core/services/fs/src/lister.rs
@@ -63,12 +63,19 @@ impl PendingDir {
}
}
+struct ListedEntry {
+ entry: oio::Entry,
+ /// Only descend into real directories during recursive listing so
+ /// directory symlinks do not trigger duplicate traversal or cycles.
+ descend: bool,
+}
+
enum DirectoryEntries {
Streaming {
- reader: ReadDir,
+ reader: Box<ReadDir>,
after_children: Option<oio::Entry>,
},
- Sorted(IntoIter<oio::Entry>),
+ Sorted(IntoIter<ListedEntry>),
}
impl FsLister {
@@ -149,9 +156,12 @@ impl oio::List for FsLister {
// Unlike other directory paths, "/" is not a prefix of its
// children. It can sort between entries in the root.
if dir.as_ref().is_some_and(|dir| dir.path() == "/") {
- entries.extend(dir.take().map(PendingDir::into_entry));
+ entries.extend(dir.take().map(|dir| ListedEntry {
+ entry: dir.into_entry(),
+ descend: false,
+ }));
}
- entries.sort_unstable_by(|a, b| a.path().cmp(b.path()));
+ entries.sort_unstable_by(|a, b|
a.entry.path().cmp(b.entry.path()));
self.active
.push(DirectoryEntries::Sorted(entries.into_iter()));
// A non-root directory sorts before all its descendants.
@@ -167,7 +177,7 @@ impl oio::List for FsLister {
None
};
self.active.push(DirectoryEntries::Streaming {
- reader,
+ reader: Box::new(reader),
after_children,
});
if let Some(dir) = dir {
@@ -185,7 +195,7 @@ impl oio::List for FsLister {
}
DirectoryEntries::Sorted(entries) => entries.next(),
};
- let Some(entry) = entry else {
+ let Some(listed) = entry else {
if let Some(DirectoryEntries::Streaming {
after_children: Some(dir),
..
@@ -195,10 +205,10 @@ impl oio::List for FsLister {
}
continue;
};
- if self.recursive && entry.mode().is_dir() && entry.path() != "/" {
- self.next_dir = Some(PendingDir::Discovered(entry));
+ if self.recursive && listed.descend && listed.entry.path() != "/" {
+ self.next_dir = Some(PendingDir::Discovered(listed.entry));
} else {
- return Ok(Some(entry));
+ return Ok(Some(listed.entry));
}
}
}
@@ -210,7 +220,7 @@ async fn next_entry(
prefix: &str,
start_after: Option<&str>,
recursive: bool,
-) -> Result<Option<oio::Entry>> {
+) -> Result<Option<ListedEntry>> {
loop {
let de = match reader.next_entry().await {
Ok(Some(de)) => de,
@@ -239,33 +249,55 @@ async fn next_entry(
}
Err(e) => return Err(new_std_io_error(e)),
};
- let (path, mode) = if ft.is_dir() {
+ let (path, mode, descend, target_metadata) = if ft.is_dir() {
// Make sure we are returning the correct path.
- (&format!("{rel_path}/"), EntryMode::DIR)
+ (format!("{rel_path}/"), EntryMode::DIR, true, None)
} else if ft.is_file() {
- (&rel_path, EntryMode::FILE)
+ (rel_path, EntryMode::FILE, false, None)
+ } else if ft.is_symlink() && start_after.is_some() {
+ // Resolve symlinks before start_after filtering and sorting so
+ // directory symlinks carry their trailing '/' and sort in their
+ // final path order. Keep streaming listings (start_after == None)
+ // returning EntryMode::Unknown so GlobLayer does not descend into
+ // discovered symlinks before CompleteLayer refines them.
+ match tokio::fs::metadata(&entry_path).await {
+ Ok(meta) if meta.is_dir() => {
+ (format!("{rel_path}/"), EntryMode::DIR, false, Some(meta))
+ }
+ Ok(meta) if meta.is_file() => (rel_path, EntryMode::FILE,
false, Some(meta)),
+ Ok(meta) => (rel_path, EntryMode::Unknown, false, Some(meta)),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ // Dangling symlink (or removed concurrently; de.metadata()
+ // below distinguishes the two).
+ (rel_path, EntryMode::Unknown, false, None)
+ }
+ Err(e) => return Err(new_std_io_error(e)),
+ }
} else {
- (&rel_path, EntryMode::Unknown)
+ (rel_path, EntryMode::Unknown, false, None)
};
if !path.starts_with(prefix) {
continue;
}
- // A directory containing the marker can still have later children.
+ // A directory we will descend into can still have later children.
if let Some(marker) = start_after
&& path.as_str() <= marker
- && !(recursive && mode.is_dir() && marker.starts_with(path))
+ && !(recursive && descend && marker.starts_with(path.as_str()))
{
continue;
}
- let de_metadata = match de.metadata().await {
- Ok(de_metadata) => de_metadata,
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
- // Entry can be deleted between readdir and metadata calls.
- continue;
- }
- Err(e) => return Err(new_std_io_error(e)),
+ let de_metadata = match target_metadata {
+ Some(meta) => meta,
+ None => match de.metadata().await {
+ Ok(de_metadata) => de_metadata,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ // Entry can be deleted between readdir and metadata calls.
+ continue;
+ }
+ Err(e) => return Err(new_std_io_error(e)),
+ },
};
let last_modified = match de_metadata.modified() {
Ok(v) => v,
@@ -281,7 +313,10 @@ async fn next_entry(
};
metadata.last_modified(Timestamp::try_from(last_modified)?);
- return Ok(Some(oio::Entry::new(path, metadata.build())));
+ return Ok(Some(ListedEntry {
+ entry: oio::Entry::new(&path, metadata.build()),
+ descend,
+ }));
}
}
diff --git a/core/services/fs/src/reader.rs b/core/services/fs/src/reader.rs
index c050695888..09a591ae31 100644
--- a/core/services/fs/src/reader.rs
+++ b/core/services/fs/src/reader.rs
@@ -67,16 +67,30 @@ impl oio::PositionRead for FsReader {
DirectIoAlignment::open(&path, options,
ServiceOperation("OpenForRead"))?;
(file, Some(alignment))
} else {
- (File::open(path).map_err(new_std_io_error)?, None)
+ (File::open(&path).map_err(new_std_io_error)?, None)
};
#[cfg(not(target_os = "linux"))]
- let file = File::open(path).map_err(new_std_io_error)?;
+ let file = File::open(&path).map_err(|err| {
+ #[cfg(windows)]
+ if err.kind() == std::io::ErrorKind::PermissionDenied
+ && std::fs::metadata(&path).is_ok_and(|meta| meta.is_dir())
+ {
+ return Error::new(ErrorKind::IsADirectory, "read path is a
directory")
+ .set_source(err);
+ }
+ new_std_io_error(err)
+ })?;
+
+ let metadata = file.metadata().map_err(new_std_io_error)?;
+ if metadata.is_dir() {
+ return Err(Error::new(
+ ErrorKind::IsADirectory,
+ "read path is a directory",
+ ));
+ }
if if_modified_since.is_some() || if_unmodified_since.is_some() {
- let modified = file
- .metadata()
- .and_then(|metadata| metadata.modified())
- .map_err(new_std_io_error)?;
+ let modified = metadata.modified().map_err(new_std_io_error)?;
let modified = Timestamp::try_from(modified)?;
if if_modified_since.is_some_and(|since| modified <= since) {
return Err(Error::new(
@@ -133,3 +147,53 @@ impl oio::PositionRead for FsReader {
Ok(Buffer::from(frozen))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use opendal_core::raw::oio::Read;
+
+ #[tokio::test]
+ async fn test_read_directory_returns_is_a_directory() {
+ let temp_dir = tempfile::TempDir::new().unwrap();
+ std::fs::create_dir(temp_dir.path().join("dir")).unwrap();
+
+ let service = crate::Fs::default()
+ .root(temp_dir.path().to_str().unwrap())
+ .build()
+ .unwrap();
+ let raw_reader = service
+ .read(&OperationContext::new(), "dir", OpRead::default())
+ .unwrap();
+ let err = raw_reader
+ .read(BytesRange::new(0, Some(1)))
+ .await
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let op =
+
Operator::new(crate::Fs::default().root(temp_dir.path().to_str().unwrap())).unwrap();
+
+ let err = op.read("dir").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let err = op.read_with("dir").range(0..1).await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let err = op
+ .read_with("dir")
+ .if_modified_since(Timestamp::MAX)
+ .await
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let reader = op.reader("dir").await.unwrap();
+ let err = reader.read(..).await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ }
+}
diff --git a/core/services/fs/tests/direct_io.rs
b/core/services/fs/tests/direct_io.rs
index 6db07f49e0..873dee2a46 100644
--- a/core/services/fs/tests/direct_io.rs
+++ b/core/services/fs/tests/direct_io.rs
@@ -243,4 +243,30 @@ mod linux {
assert_eq!(fs::read(path).unwrap(), b"original");
assert_eq!(fs::read_dir(staging).unwrap().count(), 0);
}
+
+ #[tokio::test]
+ async fn direct_io_read_directory_returns_is_a_directory() {
+ let dir = tempfile::tempdir().unwrap();
+ fs::create_dir(dir.path().join("dir")).unwrap();
+
+ let op = Operator::new(
+ Fs::default()
+ .root(dir.path().to_str().unwrap())
+ .direct_io(true),
+ )
+ .unwrap();
+
+ let err = op.read("dir").await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let err = op.read_with("dir").range(0..1).await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+
+ let reader = op.reader("dir").await.unwrap();
+ let err = reader.read(..).await.unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::IsADirectory, "{err:?}");
+ assert!(!err.is_temporary(), "{err:?}");
+ }
}
diff --git a/core/services/fs/tests/list_start_after.rs
b/core/services/fs/tests/list_start_after.rs
index 2198c80d8e..6af1ac5e29 100644
--- a/core/services/fs/tests/list_start_after.rs
+++ b/core/services/fs/tests/list_start_after.rs
@@ -95,3 +95,116 @@ async fn test_list_with_start_after() {
assert!(capability.list_with_start_after);
assert!(capability.list_with_recursive);
}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn test_list_with_start_after_directory_symlink() {
+ use opendal_core::EntryMode;
+
+ let root = tempfile::tempdir().unwrap();
+ let root_path = root.path();
+ std::fs::create_dir(root_path.join("realdir")).unwrap();
+ std::fs::write(root_path.join("realdir/inside.txt"), b"data").unwrap();
+ std::fs::write(root_path.join("link-file"), b"data").unwrap();
+ std::os::unix::fs::symlink("realdir", root_path.join("link")).unwrap();
+ std::os::unix::fs::symlink("link-file",
root_path.join("file-link")).unwrap();
+ std::os::unix::fs::symlink("nonexistent",
root_path.join("dangle")).unwrap();
+
+ let op =
Operator::new(Fs::default().root(root_path.to_str().unwrap())).unwrap();
+
+ // start_after("link") must keep directory symlink "link/" ("link/" >
"link")
+ // and maintain strict lexicographical order ('-' < '/').
+ let entries = op.list_with("/").start_after("link").await.unwrap();
+ let paths: Vec<_> = entries
+ .iter()
+ .map(|entry| (entry.path(), entry.metadata().mode()))
+ .collect();
+ assert_eq!(
+ paths,
+ vec![
+ ("link-file", EntryMode::FILE),
+ ("link/", EntryMode::DIR),
+ ("realdir/", EntryMode::DIR),
+ ]
+ );
+
+ // Full sorted listing and cursor pagination must neither reorder nor skip
entries.
+ let entries = op.list_with("/").start_after("a").await.unwrap();
+ let paths: Vec<_> = entries
+ .iter()
+ .map(|entry| (entry.path(), entry.metadata().mode()))
+ .collect();
+ assert_eq!(
+ paths,
+ vec![
+ ("dangle", EntryMode::Unknown),
+ ("file-link", EntryMode::FILE),
+ ("link-file", EntryMode::FILE),
+ ("link/", EntryMode::DIR),
+ ("realdir/", EntryMode::DIR),
+ ]
+ );
+
+ let after_link_file: Vec<_> = op
+ .list_with("/")
+ .start_after("link-file")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|entry| entry.path().to_string())
+ .collect();
+ assert_eq!(after_link_file, vec!["link/", "realdir/"]);
+
+ let after_link_dir: Vec<_> = op
+ .list_with("/")
+ .start_after("link/")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|entry| entry.path().to_string())
+ .collect();
+ assert_eq!(after_link_dir, vec!["realdir/"]);
+
+ // Recursive listing must not descend into directory symlinks and must skip
+ // "link/" when start_after is beneath "link/".
+ let recursive: Vec<_> = op
+ .list_with("/")
+ .recursive(true)
+ .start_after("link")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|entry| entry.path().to_string())
+ .collect();
+ assert_eq!(
+ recursive,
+ vec!["link-file", "link/", "realdir/", "realdir/inside.txt"]
+ );
+
+ let recursive_after_link_child: Vec<_> = op
+ .list_with("/")
+ .recursive(true)
+ .start_after("link/a")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|entry| entry.path().to_string())
+ .collect();
+ assert_eq!(
+ recursive_after_link_child,
+ vec!["realdir/", "realdir/inside.txt"]
+ );
+
+ // Circular directory symlink must not trigger infinite recursion.
+ std::os::unix::fs::symlink(".", root_path.join("self-loop")).unwrap();
+ let with_loop: Vec<_> = op
+ .list_with("/")
+ .recursive(true)
+ .start_after("realdir/z")
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|entry| (entry.path().to_string(), entry.metadata().mode()))
+ .collect();
+ assert_eq!(with_loop, vec![("self-loop/".to_string(), EntryMode::DIR)]);
+}