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 37b4cf956e fix(services/sftp): fix lister panics, rename pool 
deadlock, writer/copy close, create_dir errors, and URI port (#8959)
37b4cf956e is described below

commit 37b4cf956ed4891160f96ec36b15c642f4b78afc
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 09:06:13 2026 +0800

    fix(services/sftp): fix lister panics, rename pool deadlock, writer/copy 
close, create_dir errors, and URI port (#8959)
    
    * fix(services/sftp): fix lister panics, rename pool deadlock, writer/copy 
close, create_dir errors, and URI port
    
    * chore(website): regenerate capabilities.json after sftp capability change
---
 core/services/sftp/src/backend.rs      | 148 ++++++++++++--------
 core/services/sftp/src/config.rs       |  55 +++++++-
 core/services/sftp/src/core.rs         |  82 +++++++----
 core/services/sftp/src/lister.rs       | 143 +++++++++++++++-----
 core/services/sftp/src/reader.rs       | 106 +++++++--------
 core/services/sftp/src/writer.rs       |  42 +++---
 core/services/sftp/tests/operations.rs | 240 +++++++++++++++++++++++++++++++++
 website/data/capabilities.json         |   1 -
 8 files changed, 625 insertions(+), 192 deletions(-)

diff --git a/core/services/sftp/src/backend.rs 
b/core/services/sftp/src/backend.rs
index 346c388453..69b2eb3573 100644
--- a/core/services/sftp/src/backend.rs
+++ b/core/services/sftp/src/backend.rs
@@ -15,8 +15,6 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use std::path::Path;
-use std::path::PathBuf;
 use std::sync::Arc;
 
 use log::debug;
@@ -26,7 +24,7 @@ use super::SFTP_SCHEME;
 use super::config::SftpConfig;
 use super::core::Manager;
 use super::core::SftpCore;
-use super::core::is_sftp_protocol_error;
+use super::core::create_dir_all;
 use super::core::parse_sftp_error;
 use super::core::to_metadata;
 use super::deleter::SftpDeleter;
@@ -231,7 +229,6 @@ impl Builder for SftpBuilder {
             delete: true,
 
             list: true,
-            list_with_limit: true,
 
             copy: true,
             rename: true,
@@ -290,23 +287,7 @@ impl Service for SftpBackend {
         _: OpCreateDir,
     ) -> Result<RpCreateDir> {
         let client = self.core.connect().await?;
-        let mut fs = client.fs();
-        fs.set_cwd(&self.core.root);
-
-        let paths = Path::new(&path).components();
-        let mut current = PathBuf::from(&self.core.root);
-        for p in paths {
-            current = current.join(p);
-            let res = fs.create_dir(p).await;
-
-            if let Err(e) = res {
-                // ignore error if dir already exists
-                if !is_sftp_protocol_error(&e) {
-                    return Err(parse_sftp_error(e));
-                }
-            }
-            fs.set_cwd(&current);
-        }
+        create_dir_all(&client, &self.core.root, 
path.trim_start_matches('/')).await?;
 
         Ok(RpCreateDir::default())
     }
@@ -332,8 +313,8 @@ impl Service for SftpBackend {
         Ok(output)
     }
 
-    fn write(&self, ctx: &OperationContext, path: &str, op: OpWrite) -> 
Result<Self::Writer> {
-        Ok(SftpLazyWriter::new(self.clone(), ctx.clone(), path, op))
+    fn write(&self, _ctx: &OperationContext, path: &str, op: OpWrite) -> 
Result<Self::Writer> {
+        Ok(SftpLazyWriter::new(self.clone(), path, op))
     }
 
     fn delete(&self, _ctx: &OperationContext) -> Result<Self::Deleter> {
@@ -352,58 +333,107 @@ impl Service for SftpBackend {
 
     fn copy(
         &self,
-        ctx: &OperationContext,
+        _ctx: &OperationContext,
         from: &str,
         to: &str,
         args: OpCopy,
     ) -> Result<Self::Copier> {
         let backend = self.clone();
-        let ctx = ctx.clone();
         let from = from.to_string();
         let to = to.to_string();
-        Ok(oio::OneShotCopier::new(async move {
-            if let Some((dir, _)) = to.rsplit_once('/') {
-                backend
-                    .create_dir(&ctx, dir, OpCreateDir::default())
-                    .await?;
-            }
+        let source_content_length_hint = args.source_content_length_hint();
+
+        Ok(oio::OneShotCopier::new_with(move || {
+            let backend = backend.clone();
+            let from = from.clone();
+            let to = to.clone();
+
+            async move {
+                let client = backend.core.connect().await?;
+                if !client.support_copy() {
+                    return Err(Error::new(
+                        ErrorKind::Unsupported,
+                        "sftp server does not support copy-data extension",
+                    ));
+                }
 
-            let client = backend.core.connect().await?;
-            let mut fs = client.fs();
-            fs.set_cwd(&backend.core.root);
+                let mut fs = client.fs();
+                fs.set_cwd(&backend.core.root);
+
+                let src = 
fs.canonicalize(&from).await.map_err(parse_sftp_error)?;
+                let mut src_file = 
client.open(&src).await.map_err(parse_sftp_error)?;
+
+                let source_size = match source_content_length_hint {
+                    Some(size) => size,
+                    None => match 
src_file.metadata().await.map_err(parse_sftp_error) {
+                        Ok(meta) => match meta.len() {
+                            Some(len) => len,
+                            None => {
+                                let _ = src_file.close().await;
+                                return Err(Error::new(
+                                    ErrorKind::Unexpected,
+                                    "sftp source metadata does not contain 
file length",
+                                ));
+                            }
+                        },
+                        Err(err) => {
+                            let _ = src_file.close().await;
+                            return Err(err);
+                        }
+                    },
+                };
+
+                if let Some((dir, _)) = to.rsplit_once('/')
+                    && let Err(err) =
+                        create_dir_all(&client, &backend.core.root, 
dir.trim_start_matches('/'))
+                            .await
+                {
+                    let _ = src_file.close().await;
+                    return Err(err);
+                }
 
-            let src = fs.canonicalize(&from).await.map_err(parse_sftp_error)?;
-            let dst = fs.canonicalize(&to).await.map_err(parse_sftp_error)?;
-            let mut src_file = 
client.open(&src).await.map_err(parse_sftp_error)?;
-            let mut dst_file = 
client.create(dst).await.map_err(parse_sftp_error)?;
+                let dst = match 
fs.canonicalize(&to).await.map_err(parse_sftp_error) {
+                    Ok(dst) => dst,
+                    Err(err) => {
+                        let _ = src_file.close().await;
+                        return Err(err);
+                    }
+                };
+                if src == dst {
+                    let _ = src_file.close().await;
+                    return Err(Error::new(
+                        ErrorKind::IsSameFile,
+                        "copy source and destination resolve to the same file",
+                    ));
+                }
+
+                let mut dst_file = match 
client.create(dst).await.map_err(parse_sftp_error) {
+                    Ok(dst_file) => dst_file,
+                    Err(err) => {
+                        let _ = src_file.close().await;
+                        return Err(err);
+                    }
+                };
 
-            let source_size = match args.source_content_length_hint() {
-                Some(size) => size,
-                None => src_file
-                    .metadata()
+                let copy_res = src_file
+                    .copy_all_to(&mut dst_file)
                     .await
-                    .map_err(parse_sftp_error)?
-                    .len()
-                    .ok_or_else(|| {
-                        Error::new(
-                            ErrorKind::Unexpected,
-                            "sftp source metadata does not contain file 
length",
-                        )
-                    })?,
-            };
+                    .map_err(parse_sftp_error);
+                let dst_close_res = 
dst_file.close().await.map_err(parse_sftp_error);
+                let src_close_res = 
src_file.close().await.map_err(parse_sftp_error);
 
-            src_file
-                .copy_all_to(&mut dst_file)
-                .await
-                .map_err(parse_sftp_error)?;
+                copy_res?;
+                dst_close_res?;
+                src_close_res?;
 
-            Ok(MetadataBuilder::file(source_size).build())
+                Ok(MetadataBuilder::file(source_size).build())
+            }
         }))
     }
 
     async fn rename(
         &self,
-        ctx: &OperationContext,
+        _ctx: &OperationContext,
         from: &str,
         to: &str,
         _: OpRename,
@@ -414,7 +444,9 @@ impl Service for SftpBackend {
         fs.set_cwd(&self.core.root);
 
         if let Some((dir, _)) = to.rsplit_once('/') {
-            self.create_dir(ctx, dir, OpCreateDir::default()).await?;
+            // Verify source exists before creating destination parent 
directories.
+            fs.metadata(from).await.map_err(parse_sftp_error)?;
+            create_dir_all(&client, &self.core.root, 
dir.trim_start_matches('/')).await?;
         }
         fs.rename(from, to).await.map_err(parse_sftp_error)?;
 
diff --git a/core/services/sftp/src/config.rs b/core/services/sftp/src/config.rs
index 5dfe4410a5..864ed41932 100644
--- a/core/services/sftp/src/config.rs
+++ b/core/services/sftp/src/config.rs
@@ -70,7 +70,12 @@ impl opendal_core::Configurator for SftpConfig {
     fn from_uri(uri: &opendal_core::OperatorUri) -> opendal_core::Result<Self> 
{
         let mut map = uri.options().clone();
         if let Some(authority) = uri.authority() {
-            map.insert("endpoint".to_string(), authority.to_string());
+            map.insert("endpoint".to_string(), format!("ssh://{authority}"));
+        }
+
+        if let Some(username) = uri.username() {
+            map.entry("user".to_string())
+                .or_insert_with(|| username.to_string());
         }
 
         if let Some(root) = uri.root() {
@@ -103,10 +108,42 @@ mod tests {
         .unwrap();
 
         let cfg = SftpConfig::from_uri(&uri).unwrap();
-        assert_eq!(cfg.endpoint.as_deref(), Some("sftp.example.com"));
+        assert_eq!(cfg.endpoint.as_deref(), Some("ssh://sftp.example.com"));
         assert_eq!(cfg.root.as_deref(), Some("home/alice"));
     }
 
+    #[test]
+    fn from_uri_preserves_port_and_username() {
+        let uri = OperatorUri::new(
+            "sftp://[email protected]:2222/upload/data";,
+            Vec::<(String, String)>::new(),
+        )
+        .unwrap();
+
+        let cfg = SftpConfig::from_uri(&uri).unwrap();
+        assert_eq!(cfg.endpoint.as_deref(), Some("ssh://127.0.0.1:2222"));
+        assert_eq!(cfg.user.as_deref(), Some("foo"));
+        assert_eq!(cfg.root.as_deref(), Some("upload/data"));
+
+        let builder = openssh::SessionBuilder::default();
+        let (resolved, destination) = 
builder.resolve(cfg.endpoint.as_deref().unwrap());
+        assert_eq!(resolved.get_port(), Some("2222"));
+        assert_eq!(destination, "127.0.0.1");
+    }
+
+    #[test]
+    fn from_uri_explicit_user_option_overrides_uri_username() {
+        let uri = OperatorUri::new(
+            "sftp://[email protected]:2222/upload";,
+            [("user".to_string(), "alice".to_string())],
+        )
+        .unwrap();
+
+        let cfg = SftpConfig::from_uri(&uri).unwrap();
+        assert_eq!(cfg.endpoint.as_deref(), Some("ssh://127.0.0.1:2222"));
+        assert_eq!(cfg.user.as_deref(), Some("alice"));
+    }
+
     #[test]
     fn from_uri_applies_timeout_overrides() {
         let uri = OperatorUri::new(
@@ -162,7 +199,7 @@ mod tests {
         .unwrap();
 
         let cfg = SftpConfig::from_uri(&uri).unwrap();
-        assert_eq!(cfg.endpoint.as_deref(), Some("host"));
+        assert_eq!(cfg.endpoint.as_deref(), Some("ssh://host"));
         assert_eq!(cfg.user.as_deref(), Some("alice"));
         assert_eq!(cfg.key.as_deref(), Some("/home/alice/.ssh/id_rsa"));
         assert_eq!(cfg.known_hosts_strategy.as_deref(), Some("accept"));
@@ -211,4 +248,16 @@ mod tests {
             .control_directory("/tmp/sftp-control");
         assert!(builder.build().is_ok());
     }
+
+    #[test]
+    fn capability_does_not_advertise_list_with_limit() {
+        use opendal_core::Builder;
+        use opendal_core::raw::Service;
+
+        let service = SftpBuilder::default().endpoint("host").build().unwrap();
+        assert!(!service.capability().list_with_limit);
+
+        let op = 
opendal_core::Operator::new(SftpBuilder::default().endpoint("host")).unwrap();
+        assert!(!op.info().capability().list_with_limit);
+    }
 }
diff --git a/core/services/sftp/src/core.rs b/core/services/sftp/src/core.rs
index a9d9185a35..a970482ce8 100644
--- a/core/services/sftp/src/core.rs
+++ b/core/services/sftp/src/core.rs
@@ -112,34 +112,57 @@ pub struct Manager {
 
 impl Manager {
     async fn initialize_root(&self, sftp: &Sftp) -> Result<()> {
-        let mut fs = sftp.fs();
-        let mut current = PathBuf::new();
-        for component in Path::new(&self.root).components() {
-            let path = component.as_os_str();
-            current.push(path);
-            if component != Component::RootDir
-                && let Err(error) = fs.create_dir(path).await
-            {
-                // Servers may reject mkdir even when an existing directory 
can be used.
-                if !matches!(
-                    error,
-                    SftpClientError::SftpError(
-                        SftpErrorKind::Failure | SftpErrorKind::PermDenied,
-                        _
-                    )
-                ) {
-                    return Err(parse_sftp_error(error));
+        create_dir_all(sftp, "", &self.root).await
+    }
+}
+
+pub(crate) async fn create_dir_all(sftp: &Sftp, base: &str, path: &str) -> 
Result<()> {
+    let mut fs = sftp.fs();
+    let mut current = PathBuf::from(base);
+    if !base.is_empty() {
+        fs.set_cwd(&current);
+    }
+
+    for component in Path::new(path).components() {
+        let segment = component.as_os_str();
+        match component {
+            Component::RootDir => {
+                if base.is_empty() {
+                    current.push(segment);
+                    fs.set_cwd(&current);
                 }
-                match fs.metadata(path).await {
-                    Ok(metadata) if metadata.file_type().is_some_and(|kind| 
kind.is_dir()) => {}
-                    Err(err) if classify_sftp_error(&err).1 => return 
Err(parse_sftp_error(err)),
-                    _ => return Err(parse_sftp_error(error)),
+                continue;
+            }
+            Component::CurDir => continue,
+            _ => {}
+        }
+
+        current.push(segment);
+        if let Err(error) = fs.create_dir(segment).await {
+            // Servers may reject mkdir even when an existing directory can be 
used.
+            if !matches!(
+                error,
+                SftpClientError::SftpError(SftpErrorKind::Failure | 
SftpErrorKind::PermDenied, _)
+            ) {
+                return Err(parse_sftp_error(error));
+            }
+            match fs.metadata(segment).await {
+                Ok(metadata) if metadata.file_type().is_some_and(|kind| 
kind.is_dir()) => {}
+                Ok(_) => {
+                    return Err(Error::new(
+                        ErrorKind::NotADirectory,
+                        "path exists and is not a directory",
+                    )
+                    .set_source(error));
                 }
+                Err(err) if classify_sftp_error(&err).1 => return 
Err(parse_sftp_error(err)),
+                _ => return Err(parse_sftp_error(error)),
             }
-            fs.set_cwd(&current);
         }
-        Ok(())
+        fs.set_cwd(&current);
     }
+
+    Ok(())
 }
 
 impl ManageObject for Manager {
@@ -264,6 +287,7 @@ pub fn parse_sftp_error(e: SftpClientError) -> Error {
 fn classify_sftp_error(error: &SftpClientError) -> (ErrorKind, bool) {
     match error {
         SftpClientError::UnsupportedSftpProtocol { .. }
+        | SftpClientError::UnsupportedExtension(_)
         | SftpClientError::SftpError(SftpErrorKind::OpUnsupported, _) => {
             (ErrorKind::Unsupported, false)
         }
@@ -361,10 +385,6 @@ pub(crate) fn is_not_found(e: &SftpClientError) -> bool {
     matches!(e, SftpClientError::SftpError(SftpErrorKind::NoSuchFile, _))
 }
 
-pub(crate) fn is_sftp_protocol_error(e: &SftpClientError) -> bool {
-    matches!(e, SftpClientError::SftpError(_, _))
-}
-
 pub(crate) fn is_sftp_failure(e: &SftpClientError) -> bool {
     matches!(e, SftpClientError::SftpError(SftpErrorKind::Failure, _))
 }
@@ -538,4 +558,12 @@ mod tests {
             assert!(error.source().unwrap().is::<SftpClientError>());
         }
     }
+
+    #[test]
+    fn unsupported_extension_maps_to_unsupported() {
+        let error = 
parse_sftp_error(SftpClientError::UnsupportedExtension(&"copy-data"));
+        assert_eq!(error.kind(), ErrorKind::Unsupported);
+        assert!(!error.is_temporary());
+        assert!(error.source().unwrap().is::<SftpClientError>());
+    }
 }
diff --git a/core/services/sftp/src/lister.rs b/core/services/sftp/src/lister.rs
index 9ba3f0ef75..d08ded32b4 100644
--- a/core/services/sftp/src/lister.rs
+++ b/core/services/sftp/src/lister.rs
@@ -15,30 +15,39 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::path::Path;
 use std::pin::Pin;
 
 use futures::StreamExt;
-use openssh_sftp_client::fs::DirEntry;
 use openssh_sftp_client::fs::ReadDir;
+use openssh_sftp_client::metadata::MetaData as SftpMeta;
 
+use super::core::SftpConnection;
 use super::core::parse_sftp_error;
 use super::core::to_metadata;
+use opendal_core::Error;
+use opendal_core::ErrorKind;
+use opendal_core::MetadataBuilder;
 use opendal_core::Result;
+use opendal_core::raw::Timestamp;
 use opendal_core::raw::oio;
 use opendal_core::raw::oio::Entry;
 
 pub struct SftpLister {
-    dir: Pin<Box<ReadDir>>,
+    dir: Option<Pin<Box<ReadDir>>>,
     prefix: String,
+    // Keep the connection checked out until after the directory handle drops.
+    _conn: Option<SftpConnection>,
 }
 
 impl SftpLister {
-    pub fn new(dir: ReadDir, path: String) -> Self {
+    pub fn new(dir: ReadDir, path: String, conn: SftpConnection) -> Self {
         let prefix = if path == "/" { "".to_owned() } else { path };
 
         SftpLister {
-            dir: Box::pin(dir),
+            dir: Some(Box::pin(dir)),
             prefix,
+            _conn: Some(conn),
         }
     }
 }
@@ -46,44 +55,116 @@ impl SftpLister {
 impl oio::List for SftpLister {
     async fn next(&mut self) -> Result<Option<Entry>> {
         loop {
-            let item = self
-                .dir
-                .next()
-                .await
-                .transpose()
-                .map_err(parse_sftp_error)?;
+            let Some(dir) = self.dir.as_mut() else {
+                return Ok(None);
+            };
+            let item = dir.next().await.transpose().map_err(parse_sftp_error)?;
 
             match item {
                 Some(e) => {
-                    if e.filename().to_str() == Some("..") {
+                    let filename = e.filename();
+                    if filename == Path::new("..") {
                         continue;
-                    } else if e.filename().to_str() == Some(".") {
-                        let mut path = self.prefix.as_str();
-                        if self.prefix.is_empty() {
-                            path = "/";
-                        }
-                        return Ok(Some(Entry::new(path, 
to_metadata(e.metadata())?)));
+                    } else if filename == Path::new(".") {
+                        return Ok(Some(map_current_dir_entry(
+                            self.prefix.as_str(),
+                            e.metadata(),
+                        )));
                     } else {
-                        return Ok(Some(map_entry(self.prefix.as_str(), e)?));
+                        return Ok(Some(map_entry(
+                            self.prefix.as_str(),
+                            filename,
+                            e.metadata(),
+                        )?));
                     }
                 }
-                None => return Ok(None),
+                None => {
+                    // Drop the directory handle before releasing the pooled 
connection.
+                    self.dir = None;
+                    self._conn = None;
+                    return Ok(None);
+                }
             }
         }
     }
 }
 
-fn map_entry(prefix: &str, value: DirEntry) -> Result<Entry> {
-    let path = format!(
-        "{}{}{}",
-        prefix,
-        value.filename().to_str().unwrap(),
-        if value.file_type().unwrap().is_dir() {
-            "/"
-        } else {
-            ""
-        }
-    );
+fn map_current_dir_entry(prefix: &str, meta: SftpMeta) -> Entry {
+    let path = if prefix.is_empty() { "/" } else { prefix };
+    let mut metadata = MetadataBuilder::dir();
+    if let Some(modified) = meta.modified()
+        && let Ok(m) = Timestamp::try_from(modified.as_system_time())
+    {
+        metadata.last_modified(m);
+    }
+
+    Entry::new(path, metadata.build())
+}
 
-    Ok(Entry::new(path.as_str(), to_metadata(value.metadata())?))
+fn map_entry(prefix: &str, filename: &Path, meta: SftpMeta) -> Result<Entry> {
+    let filename = filename
+        .to_str()
+        .ok_or_else(|| Error::new(ErrorKind::Unexpected, "sftp filename is not 
valid utf-8"))?;
+    let is_dir = meta.file_type().is_some_and(|ft| ft.is_dir());
+    let path = format!("{prefix}{filename}{}", if is_dir { "/" } else { "" });
+
+    Ok(Entry::new(path.as_str(), to_metadata(meta)?))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal_core::EntryMode;
+    use openssh_sftp_client::metadata::{MetaDataBuilder, Permissions, 
RawPermissions};
+
+    #[test]
+    fn map_entry_handles_missing_permissions() {
+        let meta = MetaDataBuilder::new().create();
+        let entry = map_entry("dir/", Path::new("entry"), meta).unwrap();
+        assert_eq!(entry.path(), "dir/entry");
+        assert_eq!(entry.mode(), EntryMode::Unknown);
+    }
+
+    #[test]
+    fn map_current_dir_entry_handles_missing_permissions() {
+        let meta = MetaDataBuilder::new().create();
+        let root_entry = map_current_dir_entry("", meta);
+        assert_eq!(root_entry.path(), "/");
+        assert_eq!(root_entry.mode(), EntryMode::DIR);
+
+        let sub_entry = map_current_dir_entry("dir/", 
MetaDataBuilder::new().create());
+        assert_eq!(sub_entry.path(), "dir/");
+        assert_eq!(sub_entry.mode(), EntryMode::DIR);
+    }
+
+    #[test]
+    fn map_entry_maps_directory_and_file() {
+        let dir_perm = 
Permissions::from_raw(RawPermissions::from_bits_retain(0o040_755));
+        let dir_meta = MetaDataBuilder::new().permissions(dir_perm).create();
+        let dir_entry = map_entry("prefix/", Path::new("sub"), 
dir_meta).unwrap();
+        assert_eq!(dir_entry.path(), "prefix/sub/");
+        assert_eq!(dir_entry.mode(), EntryMode::DIR);
+
+        let file_perm = 
Permissions::from_raw(RawPermissions::from_bits_retain(0o100_644));
+        let file_meta = MetaDataBuilder::new()
+            .permissions(file_perm)
+            .len(42)
+            .create();
+        let file_entry = map_entry("prefix/", Path::new("data.bin"), 
file_meta).unwrap();
+        assert_eq!(file_entry.path(), "prefix/data.bin");
+        assert_eq!(file_entry.mode(), EntryMode::FILE);
+        assert_eq!(file_entry.metadata().content_length(), 42);
+    }
+
+    #[cfg(unix)]
+    #[test]
+    fn map_entry_rejects_non_utf8_filename_without_panic() {
+        use std::ffi::OsStr;
+        use std::os::unix::ffi::OsStrExt;
+
+        let filename = Path::new(OsStr::from_bytes(b"bad-\xff-name"));
+        let err = map_entry("", filename, MetaDataBuilder::new().create())
+            .expect_err("non-utf8 filename must return an error");
+        assert_eq!(err.kind(), ErrorKind::Unexpected);
+    }
 }
diff --git a/core/services/sftp/src/reader.rs b/core/services/sftp/src/reader.rs
index fc345f9bc6..ec6aa020bb 100644
--- a/core/services/sftp/src/reader.rs
+++ b/core/services/sftp/src/reader.rs
@@ -17,6 +17,7 @@
 
 use super::backend::*;
 use super::core::SftpConnection;
+use super::core::create_dir_all;
 use super::core::is_not_found;
 use super::core::is_sftp_failure;
 use super::core::parse_sftp_error;
@@ -30,25 +31,24 @@ use std::io::SeekFrom;
 use tokio::io::AsyncSeekExt;
 
 pub struct SftpReadStream {
-    /// Keep the connection alive while data stream is alive.
-    _conn: SftpConnection,
-
     file: File,
     chunk: usize,
     size: Option<usize>,
     read: usize,
     buf: BytesMut,
+    // Keep the connection checked out until after the file handle drops.
+    _conn: SftpConnection,
 }
 
 impl SftpReadStream {
     pub fn new(conn: SftpConnection, file: File, size: Option<u64>) -> Self {
         Self {
-            _conn: conn,
             file,
             size: size.map(|v| v as usize),
             chunk: 2 * 1024 * 1024,
             read: 0,
             buf: BytesMut::new(),
+            _conn: conn,
         }
     }
 }
@@ -129,22 +129,15 @@ impl oio::StreamRead for SftpReader {
 
 pub struct SftpLazyWriter {
     backend: SftpBackend,
-    ctx: OperationContext,
     path: String,
     op: OpWrite,
     inner: Option<SftpWriter>,
 }
 
 impl SftpLazyWriter {
-    pub(super) fn new(
-        backend: SftpBackend,
-        ctx: OperationContext,
-        path: &str,
-        op: OpWrite,
-    ) -> Self {
+    pub(super) fn new(backend: SftpBackend, path: &str, op: OpWrite) -> Self {
         Self {
             backend,
-            ctx,
             path: path.to_string(),
             op,
             inner: None,
@@ -153,51 +146,55 @@ impl SftpLazyWriter {
 
     async fn inner(&mut self) -> Result<&mut SftpWriter> {
         if self.inner.is_none() {
-            if let Some((dir, _)) = self.path.rsplit_once('/') {
-                self.backend
-                    .create_dir(&self.ctx, dir, OpCreateDir::default())
-                    .await?;
-            }
-
             let client = self.backend.core.connect().await?;
 
-            let mut fs = client.fs();
-            fs.set_cwd(&self.backend.core.root);
-            let path = fs
-                .canonicalize(&self.path)
-                .await
-                .map_err(parse_sftp_error)?;
-
-            let mut option = client.options();
-            if self.op.if_not_exists() {
-                option.create_new(true);
-            } else {
-                option.create(true);
+            if let Some((dir, _)) = self.path.rsplit_once('/') {
+                create_dir_all(
+                    &client,
+                    &self.backend.core.root,
+                    dir.trim_start_matches('/'),
+                )
+                .await?;
             }
 
-            if self.op.append() {
-                option.append(true);
-            } else {
-                option.write(true).truncate(true);
-            }
+            let file = {
+                let mut fs = client.fs();
+                fs.set_cwd(&self.backend.core.root);
+                let path = fs
+                    .canonicalize(&self.path)
+                    .await
+                    .map_err(parse_sftp_error)?;
+
+                let mut option = client.options();
+                if self.op.if_not_exists() {
+                    option.create_new(true);
+                } else {
+                    option.create(true);
+                }
 
-            let res = option.open(&path).await;
-            let file = match res {
-                Ok(f) => f,
-                Err(e) if self.op.if_not_exists() && is_sftp_failure(&e) => {
-                    if fs.metadata(&path).await.is_ok() {
-                        return Err(Error::new(
-                            ErrorKind::ConditionNotMatch,
-                            "file already exists, doesn't match the condition 
if_not_exists",
-                        )
-                        .set_source(e));
+                if self.op.append() {
+                    option.append(true);
+                } else {
+                    option.write(true).truncate(true);
+                }
+
+                match option.open(&path).await {
+                    Ok(f) => f,
+                    Err(e) if self.op.if_not_exists() && is_sftp_failure(&e) 
=> {
+                        if fs.metadata(&path).await.is_ok() {
+                            return Err(Error::new(
+                                ErrorKind::ConditionNotMatch,
+                                "file already exists, doesn't match the 
condition if_not_exists",
+                            )
+                            .set_source(e));
+                        }
+                        return Err(parse_sftp_error(e));
                     }
-                    return Err(parse_sftp_error(e));
+                    Err(e) => return Err(parse_sftp_error(e)),
                 }
-                Err(e) => return Err(parse_sftp_error(e)),
             };
 
-            self.inner = Some(SftpWriter::new(file));
+            self.inner = Some(SftpWriter::new(file, client));
         }
 
         Ok(self.inner.as_mut().expect("writer must be initialized"))
@@ -244,13 +241,16 @@ impl oio::List for SftpLazyLister {
     async fn next(&mut self) -> Result<Option<oio::Entry>> {
         if self.inner.is_none() {
             let client = self.backend.core.connect().await?;
-            let mut fs = client.fs();
-            fs.set_cwd(&self.backend.core.root);
+            let dir = {
+                let mut fs = client.fs();
+                fs.set_cwd(&self.backend.core.root);
 
-            let file_path = format!("./{}", self.path);
+                let file_path = format!("./{}", self.path);
+                fs.open_dir(&file_path).await
+            };
 
-            self.inner = Some(match fs.open_dir(&file_path).await {
-                Ok(dir) => Some(SftpLister::new(dir.read_dir(), 
self.path.clone())),
+            self.inner = Some(match dir {
+                Ok(dir) => Some(SftpLister::new(dir.read_dir(), 
self.path.clone(), client)),
                 Err(e) if is_not_found(&e) => None,
                 Err(e) => return Err(parse_sftp_error(e)),
             });
diff --git a/core/services/sftp/src/writer.rs b/core/services/sftp/src/writer.rs
index 8c82c3bf9c..9dea1874e4 100644
--- a/core/services/sftp/src/writer.rs
+++ b/core/services/sftp/src/writer.rs
@@ -15,45 +15,49 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use std::pin::Pin;
-
-use bytes::Buf;
+use bytes::Bytes;
 use openssh_sftp_client::file::File;
-use openssh_sftp_client::file::TokioCompatFile;
-use tokio::io::AsyncWriteExt;
 
+use super::core::SftpConnection;
+use super::core::parse_sftp_error;
 use opendal_core::raw::*;
 use opendal_core::*;
 
 pub struct SftpWriter {
-    /// TODO: maybe we can use `File` directly?
-    file: Pin<Box<TokioCompatFile>>,
+    file: Option<File>,
+    // Keep the connection checked out until after the file handle closes.
+    _conn: Option<SftpConnection>,
 }
 
 impl SftpWriter {
-    pub fn new(file: File) -> Self {
+    pub fn new(file: File, conn: SftpConnection) -> Self {
         SftpWriter {
-            file: Box::pin(TokioCompatFile::new(file)),
+            file: Some(file),
+            _conn: Some(conn),
         }
     }
 }
 
 impl oio::Write for SftpWriter {
-    async fn write(&mut self, mut bs: Buffer) -> Result<()> {
-        while bs.has_remaining() {
-            let n = self
-                .file
-                .write(bs.chunk())
-                .await
-                .map_err(new_std_io_error)?;
-            bs.advance(n);
-        }
+    async fn write(&mut self, bs: Buffer) -> Result<()> {
+        let file = self.file.as_mut().ok_or_else(|| {
+            Error::new(ErrorKind::Unexpected, "sftp writer has already been 
closed")
+        })?;
+
+        let mut chunks: Vec<Bytes> = bs.into_iter().collect();
+        file.write_all_zero_copy(&mut chunks)
+            .await
+            .map_err(parse_sftp_error)?;
 
         Ok(())
     }
 
     async fn close(&mut self) -> Result<Metadata> {
-        self.file.shutdown().await.map_err(new_std_io_error)?;
+        if let Some(file) = self.file.take() {
+            let res = file.close().await.map_err(parse_sftp_error);
+            self._conn = None;
+            res?;
+        }
 
         Ok(MetadataBuilder::unknown().build())
     }
diff --git a/core/services/sftp/tests/operations.rs 
b/core/services/sftp/tests/operations.rs
new file mode 100644
index 0000000000..4b615adbcf
--- /dev/null
+++ b/core/services/sftp/tests/operations.rs
@@ -0,0 +1,240 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::time::Duration;
+
+use futures::TryStreamExt;
+use opendal_core::{Configurator, ErrorKind, Operator, OperatorUri};
+use opendal_service_sftp::{Sftp, SftpConfig};
+
+const POOL_CAPACITY: usize = 64;
+
+// Use the key-auth fixture in fixtures/sftp/docker-compose-sftp.yml.
+fn fixture_builder(endpoint: &str) -> Sftp {
+    Sftp::default()
+        .endpoint(endpoint)
+        .root("/upload")
+        .user("foo")
+        .key(&std::env::var("OPENDAL_SFTP_KEY").unwrap())
+        .known_hosts_strategy("accept")
+}
+
+fn unique_path(name: &str) -> String {
+    let nanos = std::time::SystemTime::now()
+        .duration_since(std::time::UNIX_EPOCH)
+        .unwrap()
+        .as_nanos();
+    format!("{name}-{}-{nanos}", std::process::id())
+}
+
+#[tokio::test]
+#[ignore = "requires the real OpenSSH SFTP fixture"]
+async fn create_dir_propagates_non_directory_and_permission_errors() {
+    let endpoint = std::env::var("OPENDAL_SFTP_ENDPOINT").unwrap();
+    let op = Operator::new(fixture_builder(&endpoint)).unwrap();
+
+    let file_path = unique_path("create-dir-existing-file");
+    op.write(&file_path, "data").await.unwrap();
+
+    let err = op
+        .create_dir(&format!("{file_path}/"))
+        .await
+        .expect_err("create_dir on an existing regular file must fail");
+    assert_eq!(err.kind(), ErrorKind::NotADirectory, "{err:?}");
+
+    op.delete(&file_path).await.unwrap();
+
+    // The fixture home directory (`/`) is chrooted and owned by root (not 
writable by `foo`).
+    let root_op = Operator::new(fixture_builder(&endpoint).root("/")).unwrap();
+    let forbidden_dir = format!("{}/", unique_path("forbidden-dir"));
+    let err = root_op
+        .create_dir(&forbidden_dir)
+        .await
+        .expect_err("create_dir without write permission must fail");
+    assert_eq!(err.kind(), ErrorKind::PermissionDenied, "{err:?}");
+}
+
+#[tokio::test]
+#[ignore = "requires the real OpenSSH SFTP fixture"]
+async fn copy_canonical_alias_self_does_not_truncate_source() {
+    let endpoint = std::env::var("OPENDAL_SFTP_ENDPOINT").unwrap();
+    let op = Operator::new(fixture_builder(&endpoint)).unwrap();
+
+    let base = unique_path("copy-self-alias");
+    let sub_dir = format!("{base}/sub/");
+    let file_path = format!("{base}/real.txt");
+    let alias_path = format!("{base}/sub/../real.txt");
+
+    op.create_dir(&sub_dir).await.unwrap();
+    op.write(&file_path, "precious-content").await.unwrap();
+
+    let err = op
+        .copy(&alias_path, &file_path)
+        .await
+        .expect_err("copying a file onto its canonical alias must fail");
+    assert_eq!(err.kind(), ErrorKind::IsSameFile, "{err:?}");
+
+    let content = op.read(&file_path).await.unwrap().to_vec();
+    assert_eq!(content, b"precious-content");
+
+    op.delete(&file_path).await.unwrap();
+    op.delete(&sub_dir).await.unwrap();
+    op.delete(&format!("{base}/")).await.unwrap();
+}
+
+#[tokio::test]
+#[ignore = "requires the real OpenSSH SFTP fixture"]
+async fn from_uri_connects_with_port_and_embedded_username() {
+    let endpoint = std::env::var("OPENDAL_SFTP_ENDPOINT").unwrap();
+    let authority = endpoint.strip_prefix("ssh://").unwrap_or(&endpoint);
+    let key = std::env::var("OPENDAL_SFTP_KEY").unwrap();
+
+    let uri = OperatorUri::new(
+        &format!("sftp://foo@{authority}/upload";),
+        [
+            ("key".to_string(), key),
+            ("known_hosts_strategy".to_string(), "accept".to_string()),
+        ],
+    )
+    .unwrap();
+    let cfg = SftpConfig::from_uri(&uri).unwrap();
+    let op = Operator::new(cfg.into_builder()).unwrap();
+
+    let file_path = unique_path("from-uri-test.txt");
+    op.write(&file_path, "hello-uri").await.unwrap();
+    assert_eq!(op.read(&file_path).await.unwrap().to_vec(), b"hello-uri");
+    op.delete(&file_path).await.unwrap();
+}
+
+#[tokio::test]
+#[ignore = "requires the real OpenSSH SFTP fixture"]
+async fn open_writers_and_listers_hold_pool_capacity_until_closed() {
+    let endpoint = std::env::var("OPENDAL_SFTP_ENDPOINT").unwrap();
+    let op = Operator::new(
+        fixture_builder(&endpoint)
+            .acquire_timeout(Duration::from_millis(200))
+            .connect_timeout(Duration::from_secs(10)),
+    )
+    .unwrap();
+
+    let base = unique_path("pool-capacity-test");
+    op.create_dir(&format!("{base}/")).await.unwrap();
+
+    // Open POOL_CAPACITY writers sequentially so every pool slot is checked 
out.
+    let mut writers = Vec::with_capacity(POOL_CAPACITY);
+    let mut paths = Vec::with_capacity(POOL_CAPACITY);
+    for i in 0..POOL_CAPACITY {
+        let path = format!("{base}/w-{i}.txt");
+        let mut writer = op.writer(&path).await.unwrap();
+        writer.write("a").await.unwrap();
+        writers.push(writer);
+        paths.push(path);
+    }
+
+    let err = op
+        .stat(&paths[0])
+        .await
+        .expect_err("pool must be exhausted while all writers are open");
+    assert!(err.is_temporary(), "{err:?}");
+    assert!(err.to_string().contains("waiting for pool capacity"));
+
+    // Closing one writer must synchronously close its file and release its 
pool slot.
+    let mut last_writer = writers.pop().unwrap();
+    last_writer.close().await.unwrap();
+    assert_eq!(op.read(paths.last().unwrap()).await.unwrap().to_vec(), b"a");
+    drop(last_writer);
+
+    for mut writer in writers {
+        writer.close().await.unwrap();
+    }
+
+    // Open POOL_CAPACITY listers sequentially so every pool slot is checked 
out.
+    let mut listers = Vec::with_capacity(POOL_CAPACITY);
+    for _ in 0..POOL_CAPACITY {
+        let mut lister = op.lister(&format!("{base}/")).await.unwrap();
+        assert!(lister.try_next().await.unwrap().is_some());
+        listers.push(lister);
+    }
+
+    let err = op
+        .stat(&paths[0])
+        .await
+        .expect_err("pool must be exhausted while all listers are open");
+    assert!(err.is_temporary(), "{err:?}");
+    assert!(err.to_string().contains("waiting for pool capacity"));
+
+    drop(listers);
+    assert!(op.stat(&paths[0]).await.unwrap().is_file());
+
+    for path in paths {
+        op.delete(&path).await.unwrap();
+    }
+    op.delete(&format!("{base}/")).await.unwrap();
+}
+
+#[tokio::test]
+#[ignore = "requires the real OpenSSH SFTP fixture"]
+async fn concurrent_nested_renames_do_not_deadlock_pool() {
+    let endpoint = std::env::var("OPENDAL_SFTP_ENDPOINT").unwrap();
+    let op = Operator::new(
+        fixture_builder(&endpoint)
+            .acquire_timeout(Duration::from_secs(5))
+            .connect_timeout(Duration::from_secs(15)),
+    )
+    .unwrap();
+
+    let base = unique_path("concurrent-rename");
+    op.create_dir(&format!("{base}/")).await.unwrap();
+
+    // Create POOL_CAPACITY source files first and warm up the pool so sshd 
MaxStartups
+    // is not hit during the concurrent rename burst.
+    let mut srcs = Vec::with_capacity(POOL_CAPACITY);
+    let mut dsts = Vec::with_capacity(POOL_CAPACITY);
+    let mut warm_writers = Vec::with_capacity(POOL_CAPACITY);
+    for i in 0..POOL_CAPACITY {
+        let src = format!("{base}/src-{i}.txt");
+        let dst = format!("{base}/nested-{i}/dst-{i}.txt");
+        let mut w = op.writer(&src).await.unwrap();
+        w.write(format!("payload-{i}")).await.unwrap();
+        warm_writers.push(w);
+        srcs.push(src);
+        dsts.push(dst);
+    }
+    for mut w in warm_writers {
+        w.close().await.unwrap();
+    }
+
+    let mut handles = Vec::with_capacity(POOL_CAPACITY);
+    for (src, dst) in srcs.iter().cloned().zip(dsts.iter().cloned()) {
+        let op = op.clone();
+        handles.push(tokio::spawn(async move { op.rename(&src, &dst).await }));
+    }
+
+    for handle in handles {
+        handle.await.unwrap().unwrap();
+    }
+
+    for (i, dst) in dsts.iter().enumerate() {
+        assert_eq!(
+            op.read(dst).await.unwrap().to_vec(),
+            format!("payload-{i}").into_bytes()
+        );
+        op.delete(dst).await.unwrap();
+        op.delete(&format!("{base}/nested-{i}/")).await.unwrap();
+    }
+    op.delete(&format!("{base}/")).await.unwrap();
+}
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index 48a8b7fd86..dde27b3861 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -2112,7 +2112,6 @@
         "create_dir": true,
         "delete": true,
         "list": true,
-        "list_with_limit": true,
         "read": true,
         "rename": true,
         "shared": true,

Reply via email to