Xuanwo commented on code in PR #7977:
URL: https://github.com/apache/opendal/pull/7977#discussion_r4757359994


##########
core/services/sftp/src/core.rs:
##########
@@ -15,40 +15,135 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::borrow::Cow;
 use std::fmt::Debug;
 use std::future::Future;
 use std::io;
 use std::ops::Deref;
-use std::path::{Component, Path, PathBuf};
+use std::path::PathBuf;
 use std::sync::Arc;
 
 use asyncband::pool::{ManageObject, ObjectStatus, unbounded};
 use asyncband::semaphore::{OwnedSemaphorePermit, Semaphore};
 use log::debug;
 use opendal_core::raw::*;
 use opendal_core::*;
-use openssh::Error as SshError;
-use openssh::{KnownHosts, SessionBuilder};
-use openssh_sftp_client::Error as SftpClientError;
-use openssh_sftp_client::error::SftpErrorKind;
-use openssh_sftp_client::{Sftp, SftpOptions};
+use russh::client;
+use russh::keys::PrivateKeyWithHashAlg;
+use russh::keys::ssh_key::Algorithm;
+use russh::keys::ssh_key::HashAlg;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::error::Error as SftpClientError;
+use russh_sftp::client::rawsession::Limits;
+use russh_sftp::extensions;
+use russh_sftp::protocol::{FileAttributes, Handle, OpenFlags, SftpHandle, 
SftpString, StatusCode};
+use url::Url;
+
+use super::known_hosts::HostKeyVerifier;
 
 const POOL_CAPACITY: usize = 64;
 
+/// SSH handshakes that one pool runs at a time. OpenSSH starts to drop
+/// unauthenticated connections at 10 (`MaxStartups 10:30:100`).
+pub(crate) const MAX_CONCURRENT_HANDSHAKES: usize = 4;
+
+/// Payload limit of one read or write when the server does not send
+/// `[email protected]`. SFTP v3 servers must accept packets of 32 KiB.
+const DEFAULT_PAYLOAD_LEN: u64 = 32 * 1024;
+
+/// Bytes of a packet that a read or write request header can use. OpenSSH
+/// keeps the same distance between its packet and payload limits.
+const REQUEST_HEADER_LEN: u64 = 1024;
+
+const COPY_DATA: &str = "copy-data";
+
+/// SSH server address and login user parsed from the `endpoint` option.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SshEndpoint {
+    pub user: Option<String>,
+    pub host: String,
+    pub port: u16,
+}
+
+impl SshEndpoint {
+    /// Parses `[user@]host[:port]` or `ssh://[user@]host[:port]`.
+    ///
+    /// The port defaults to 22. An IPv6 address must be in brackets.
+    pub fn parse(endpoint: &str) -> Result<Self> {
+        let invalid = |reason: &str| {
+            Error::new(
+                ErrorKind::ConfigInvalid,
+                format!("sftp endpoint is invalid: {reason}"),
+            )
+            .with_context("endpoint", endpoint)

Review Comment:
   Please omit the raw endpoint from the rejection error. A synthetic 
credential marker should be absent from both the displayed error and its Debug 
output. A separate fix covers the baseline builder diagnostics. Please rebase 
onto it if it lands first.



##########
core/services/sftp/src/core.rs:
##########
@@ -83,71 +177,417 @@ impl SftpCore {
             _permit: permit,
         })
     }
+
+    /// Returns the server path for an OpenDAL path.
+    pub fn remote_path(&self, path: &str) -> String {
+        remote_path(&self.root, path)
+    }
+}
+
+/// Returns the server path for `path` under `root`.
+///
+/// An empty root keeps the path relative to the login directory.
+fn remote_path(root: &str, path: &str) -> String {
+    let joined = if root.is_empty() {
+        build_absolute_path("/", path)
+    } else {
+        build_rooted_absolute_path(root, path)
+    };
+
+    // OpenSSH for Windows rejects a path with a trailing separator.
+    match joined.trim_end_matches('/') {
+        "" if root.is_empty() => ".".to_string(),
+        "" => "/".to_string(),
+        trimmed => trimmed.to_string(),
+    }
 }
 
 pub struct SftpConnection {
     // Return the connection to the pool before another checkout can take its 
slot.
-    object: unbounded::Object<Sftp, Manager>,
+    object: unbounded::Object<SftpClient, Manager>,
     _permit: OwnedSemaphorePermit,
 }
 
 impl Deref for SftpConnection {
-    type Target = Sftp;
+    type Target = SftpClient;
 
     fn deref(&self) -> &Self::Target {
         &self.object
     }
 }
 
+/// An authenticated SSH connection with an open SFTP session.
+pub struct SftpClient {
+    pub sftp: RawSftpSession,
+    /// Largest payload of one read request.
+    pub read_len: u32,
+    /// Largest payload of one write request.
+    pub write_len: u32,
+    pub posix_rename: bool,
+    pub copy_data: bool,
+    /// The runtime of the SSH connection tasks.
+    pub runtime: tokio::runtime::Handle,
+    _ssh: client::Handle<SshHandler>,
+}
+
+/// An open file or directory handle on a pooled connection.
+///
+/// The connection stays checked out while a handle is open. Dropping the
+/// handle without [`OpenHandle::close`] closes it in the background.
+pub struct OpenHandle {
+    conn: Arc<SftpConnection>,
+    handle: Option<SftpHandle>,
+}
+
+impl OpenHandle {
+    /// Opens a file with `flags`.
+    pub async fn open(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+        flags: OpenFlags,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(conn, move |conn| async move {
+            conn.sftp.open(path, flags, FileAttributes::empty()).await
+        })
+        .await
+    }
+
+    /// Opens a directory to list.
+    pub async fn open_dir(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(
+            conn,
+            move |conn| async move { conn.sftp.opendir(path).await },
+        )
+        .await
+    }
+
+    /// Sends the open request in a task that owns the result. If the caller
+    /// stops waiting, the task drops the new handle, which closes it.
+    async fn spawn_open<F, Fut>(conn: Arc<SftpConnection>, open: F) -> 
Result<Self, SftpClientError>
+    where
+        F: FnOnce(Arc<SftpConnection>) -> Fut,
+        Fut: Future<Output = Result<Handle, SftpClientError>> + Send + 'static,
+    {
+        let runtime = conn.runtime.clone();
+        let request = open(conn.clone());
+        runtime
+            .spawn(async move {
+                let handle = request.await?.handle;
+                Ok(Self {
+                    conn,
+                    handle: Some(handle),
+                })
+            })
+            .await
+            .unwrap_or_else(|err| {
+                Err(SftpClientError::UnexpectedBehavior(format!(
+                    "sftp open task failed: {err}"
+                )))
+            })
+    }
+
+    pub fn client(&self) -> &SftpClient {
+        &self.conn
+    }
+
+    pub fn connection(&self) -> &Arc<SftpConnection> {
+        &self.conn
+    }
+
+    pub fn handle(&self) -> &SftpHandle {
+        self.handle
+            .as_ref()
+            .expect("handle must stay open until close")
+    }
+
+    pub async fn close(mut self) -> Result<()> {
+        let handle = self.handle.take().expect("handle must not be closed 
twice");
+        self.conn
+            .sftp
+            .close(handle)
+            .await
+            .map(|_| ())
+            .map_err(parse_sftp_error)
+    }
+}
+
+impl Drop for OpenHandle {
+    fn drop(&mut self) {
+        let Some(handle) = self.handle.take() else {
+            return;
+        };
+        let conn = self.conn.clone();
+        self.conn.runtime.spawn(async move {

Review Comment:
   This task owns a pooled connection until `close` completes. The detached 
open and directory-read tasks also retain one after the caller stops waiting. 
Please bound how long those tasks can retain the connection after cancellation, 
and retire it when the handle state is uncertain.



##########
core/services/sftp/src/core.rs:
##########
@@ -83,71 +177,417 @@ impl SftpCore {
             _permit: permit,
         })
     }
+
+    /// Returns the server path for an OpenDAL path.
+    pub fn remote_path(&self, path: &str) -> String {
+        remote_path(&self.root, path)
+    }
+}
+
+/// Returns the server path for `path` under `root`.
+///
+/// An empty root keeps the path relative to the login directory.
+fn remote_path(root: &str, path: &str) -> String {
+    let joined = if root.is_empty() {
+        build_absolute_path("/", path)
+    } else {
+        build_rooted_absolute_path(root, path)
+    };
+
+    // OpenSSH for Windows rejects a path with a trailing separator.
+    match joined.trim_end_matches('/') {
+        "" if root.is_empty() => ".".to_string(),
+        "" => "/".to_string(),
+        trimmed => trimmed.to_string(),
+    }
 }
 
 pub struct SftpConnection {
     // Return the connection to the pool before another checkout can take its 
slot.
-    object: unbounded::Object<Sftp, Manager>,
+    object: unbounded::Object<SftpClient, Manager>,
     _permit: OwnedSemaphorePermit,
 }
 
 impl Deref for SftpConnection {
-    type Target = Sftp;
+    type Target = SftpClient;
 
     fn deref(&self) -> &Self::Target {
         &self.object
     }
 }
 
+/// An authenticated SSH connection with an open SFTP session.
+pub struct SftpClient {
+    pub sftp: RawSftpSession,
+    /// Largest payload of one read request.
+    pub read_len: u32,
+    /// Largest payload of one write request.
+    pub write_len: u32,
+    pub posix_rename: bool,
+    pub copy_data: bool,
+    /// The runtime of the SSH connection tasks.
+    pub runtime: tokio::runtime::Handle,
+    _ssh: client::Handle<SshHandler>,
+}
+
+/// An open file or directory handle on a pooled connection.
+///
+/// The connection stays checked out while a handle is open. Dropping the
+/// handle without [`OpenHandle::close`] closes it in the background.
+pub struct OpenHandle {
+    conn: Arc<SftpConnection>,
+    handle: Option<SftpHandle>,
+}
+
+impl OpenHandle {
+    /// Opens a file with `flags`.
+    pub async fn open(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+        flags: OpenFlags,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(conn, move |conn| async move {
+            conn.sftp.open(path, flags, FileAttributes::empty()).await
+        })
+        .await
+    }
+
+    /// Opens a directory to list.
+    pub async fn open_dir(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(
+            conn,
+            move |conn| async move { conn.sftp.opendir(path).await },
+        )
+        .await
+    }
+
+    /// Sends the open request in a task that owns the result. If the caller
+    /// stops waiting, the task drops the new handle, which closes it.
+    async fn spawn_open<F, Fut>(conn: Arc<SftpConnection>, open: F) -> 
Result<Self, SftpClientError>
+    where
+        F: FnOnce(Arc<SftpConnection>) -> Fut,
+        Fut: Future<Output = Result<Handle, SftpClientError>> + Send + 'static,
+    {
+        let runtime = conn.runtime.clone();
+        let request = open(conn.clone());
+        runtime
+            .spawn(async move {
+                let handle = request.await?.handle;
+                Ok(Self {
+                    conn,
+                    handle: Some(handle),
+                })
+            })
+            .await
+            .unwrap_or_else(|err| {
+                Err(SftpClientError::UnexpectedBehavior(format!(
+                    "sftp open task failed: {err}"
+                )))
+            })
+    }
+
+    pub fn client(&self) -> &SftpClient {
+        &self.conn
+    }
+
+    pub fn connection(&self) -> &Arc<SftpConnection> {
+        &self.conn
+    }
+
+    pub fn handle(&self) -> &SftpHandle {
+        self.handle
+            .as_ref()
+            .expect("handle must stay open until close")
+    }
+
+    pub async fn close(mut self) -> Result<()> {
+        let handle = self.handle.take().expect("handle must not be closed 
twice");
+        self.conn
+            .sftp
+            .close(handle)
+            .await
+            .map(|_| ())
+            .map_err(parse_sftp_error)
+    }
+}
+
+impl Drop for OpenHandle {
+    fn drop(&mut self) {
+        let Some(handle) = self.handle.take() else {
+            return;
+        };
+        let conn = self.conn.clone();
+        self.conn.runtime.spawn(async move {
+            if let Err(err) = conn.sftp.close(handle).await {
+                debug!("failed to close SFTP handle: {err}");
+            }
+        });
+    }
+}
+
 pub struct Manager {
-    pub(super) endpoint: String,
+    pub(super) endpoint: SshEndpoint,
     pub(super) root: String,
-    pub(super) user: Option<String>,
+    pub(super) user: String,
     pub(super) key: Option<String>,
-    pub(super) known_hosts_strategy: KnownHosts,
+    pub(super) host_keys: HostKeyVerifier,
     pub(super) connect_timeout: Option<Duration>,
-    #[cfg(not(windows))]
-    pub(super) control_directory: Option<String>,
+    pub(super) handshakes: Semaphore,
 }
 
 impl Manager {
-    async fn initialize_root(&self, sftp: &Sftp) -> Result<()> {
-        create_dir_all(sftp, "", &self.root).await
-    }
-}
+    async fn connect_ssh(&self) -> Result<client::Handle<SshHandler>> {
+        let host = self.endpoint.known_hosts_name();
+        let mut config = client::Config::default();
+        config.preferred.key = Cow::Owned(prefer_recorded_algorithms(
+            &config.preferred.key,
+            &self.host_keys.recorded_algorithms(&host),
+        ));
 
-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);
+        let handler = SshHandler {
+            host,
+            host_keys: self.host_keys.clone(),
+        };
+        let mut ssh = client::connect(
+            Arc::new(config),
+            (self.endpoint.host.as_str(), self.endpoint.port),
+            handler,
+        )
+        .await
+        .map_err(SshClientError::into_error)?;
+
+        self.authenticate(&mut ssh, &self.user).await?;
+        Ok(ssh)
     }
 
-    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);
+    /// Authenticates with `key`, or with the SSH agent and the default
+    /// identity files when `key` is not set.
+    async fn authenticate(&self, ssh: &mut client::Handle<SshHandler>, user: 
&str) -> Result<()> {
+        let rsa_hash = ssh
+            .best_supported_rsa_hash()
+            .await
+            .map_err(parse_ssh_error)?
+            .flatten();
+
+        if let Some(path) = &self.key {
+            let key = russh::keys::load_secret_key(path, None).map_err(|err| {

Review Comment:
   The old backend accepted an explicit `~/…` key path. With the same OpenSSH 
server and key, this draft rejected the home-relative path and succeeded with 
the absolute path. Please preserve home-relative paths or document the 
migration to absolute paths. Also, please query `best_supported_rsa_hash()` 
only for RSA keys so other key types can authenticate without waiting for that 
extension.



##########
core/services/sftp/src/core.rs:
##########
@@ -83,71 +177,417 @@ impl SftpCore {
             _permit: permit,
         })
     }
+
+    /// Returns the server path for an OpenDAL path.
+    pub fn remote_path(&self, path: &str) -> String {
+        remote_path(&self.root, path)
+    }
+}
+
+/// Returns the server path for `path` under `root`.
+///
+/// An empty root keeps the path relative to the login directory.
+fn remote_path(root: &str, path: &str) -> String {
+    let joined = if root.is_empty() {
+        build_absolute_path("/", path)
+    } else {
+        build_rooted_absolute_path(root, path)
+    };
+
+    // OpenSSH for Windows rejects a path with a trailing separator.
+    match joined.trim_end_matches('/') {
+        "" if root.is_empty() => ".".to_string(),
+        "" => "/".to_string(),
+        trimmed => trimmed.to_string(),
+    }
 }
 
 pub struct SftpConnection {
     // Return the connection to the pool before another checkout can take its 
slot.
-    object: unbounded::Object<Sftp, Manager>,
+    object: unbounded::Object<SftpClient, Manager>,
     _permit: OwnedSemaphorePermit,
 }
 
 impl Deref for SftpConnection {
-    type Target = Sftp;
+    type Target = SftpClient;
 
     fn deref(&self) -> &Self::Target {
         &self.object
     }
 }
 
+/// An authenticated SSH connection with an open SFTP session.
+pub struct SftpClient {
+    pub sftp: RawSftpSession,
+    /// Largest payload of one read request.
+    pub read_len: u32,
+    /// Largest payload of one write request.
+    pub write_len: u32,
+    pub posix_rename: bool,
+    pub copy_data: bool,
+    /// The runtime of the SSH connection tasks.
+    pub runtime: tokio::runtime::Handle,
+    _ssh: client::Handle<SshHandler>,
+}
+
+/// An open file or directory handle on a pooled connection.
+///
+/// The connection stays checked out while a handle is open. Dropping the
+/// handle without [`OpenHandle::close`] closes it in the background.
+pub struct OpenHandle {
+    conn: Arc<SftpConnection>,
+    handle: Option<SftpHandle>,
+}
+
+impl OpenHandle {
+    /// Opens a file with `flags`.
+    pub async fn open(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+        flags: OpenFlags,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(conn, move |conn| async move {
+            conn.sftp.open(path, flags, FileAttributes::empty()).await
+        })
+        .await
+    }
+
+    /// Opens a directory to list.
+    pub async fn open_dir(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(
+            conn,
+            move |conn| async move { conn.sftp.opendir(path).await },
+        )
+        .await
+    }
+
+    /// Sends the open request in a task that owns the result. If the caller
+    /// stops waiting, the task drops the new handle, which closes it.
+    async fn spawn_open<F, Fut>(conn: Arc<SftpConnection>, open: F) -> 
Result<Self, SftpClientError>
+    where
+        F: FnOnce(Arc<SftpConnection>) -> Fut,
+        Fut: Future<Output = Result<Handle, SftpClientError>> + Send + 'static,
+    {
+        let runtime = conn.runtime.clone();
+        let request = open(conn.clone());
+        runtime
+            .spawn(async move {
+                let handle = request.await?.handle;
+                Ok(Self {
+                    conn,
+                    handle: Some(handle),
+                })
+            })
+            .await
+            .unwrap_or_else(|err| {
+                Err(SftpClientError::UnexpectedBehavior(format!(
+                    "sftp open task failed: {err}"
+                )))
+            })
+    }
+
+    pub fn client(&self) -> &SftpClient {
+        &self.conn
+    }
+
+    pub fn connection(&self) -> &Arc<SftpConnection> {
+        &self.conn
+    }
+
+    pub fn handle(&self) -> &SftpHandle {
+        self.handle
+            .as_ref()
+            .expect("handle must stay open until close")
+    }
+
+    pub async fn close(mut self) -> Result<()> {
+        let handle = self.handle.take().expect("handle must not be closed 
twice");
+        self.conn
+            .sftp
+            .close(handle)
+            .await
+            .map(|_| ())
+            .map_err(parse_sftp_error)
+    }
+}
+
+impl Drop for OpenHandle {
+    fn drop(&mut self) {
+        let Some(handle) = self.handle.take() else {
+            return;
+        };
+        let conn = self.conn.clone();
+        self.conn.runtime.spawn(async move {
+            if let Err(err) = conn.sftp.close(handle).await {
+                debug!("failed to close SFTP handle: {err}");
+            }
+        });
+    }
+}
+
 pub struct Manager {
-    pub(super) endpoint: String,
+    pub(super) endpoint: SshEndpoint,
     pub(super) root: String,
-    pub(super) user: Option<String>,
+    pub(super) user: String,
     pub(super) key: Option<String>,
-    pub(super) known_hosts_strategy: KnownHosts,
+    pub(super) host_keys: HostKeyVerifier,
     pub(super) connect_timeout: Option<Duration>,
-    #[cfg(not(windows))]
-    pub(super) control_directory: Option<String>,
+    pub(super) handshakes: Semaphore,
 }
 
 impl Manager {
-    async fn initialize_root(&self, sftp: &Sftp) -> Result<()> {
-        create_dir_all(sftp, "", &self.root).await
-    }
-}
+    async fn connect_ssh(&self) -> Result<client::Handle<SshHandler>> {
+        let host = self.endpoint.known_hosts_name();
+        let mut config = client::Config::default();
+        config.preferred.key = Cow::Owned(prefer_recorded_algorithms(
+            &config.preferred.key,
+            &self.host_keys.recorded_algorithms(&host),
+        ));
 
-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);
+        let handler = SshHandler {
+            host,
+            host_keys: self.host_keys.clone(),
+        };
+        let mut ssh = client::connect(

Review Comment:
   Please make `connect_timeout` terminate the underlying SSH setup when the 
deadline expires during key exchange. Dropping the outer future can leave the 
session task running after the handshake permit is released.



##########
core/services/sftp/src/core.rs:
##########
@@ -83,71 +177,417 @@ impl SftpCore {
             _permit: permit,
         })
     }
+
+    /// Returns the server path for an OpenDAL path.
+    pub fn remote_path(&self, path: &str) -> String {
+        remote_path(&self.root, path)
+    }
+}
+
+/// Returns the server path for `path` under `root`.
+///
+/// An empty root keeps the path relative to the login directory.
+fn remote_path(root: &str, path: &str) -> String {
+    let joined = if root.is_empty() {
+        build_absolute_path("/", path)
+    } else {
+        build_rooted_absolute_path(root, path)
+    };
+
+    // OpenSSH for Windows rejects a path with a trailing separator.
+    match joined.trim_end_matches('/') {
+        "" if root.is_empty() => ".".to_string(),
+        "" => "/".to_string(),
+        trimmed => trimmed.to_string(),
+    }
 }
 
 pub struct SftpConnection {
     // Return the connection to the pool before another checkout can take its 
slot.
-    object: unbounded::Object<Sftp, Manager>,
+    object: unbounded::Object<SftpClient, Manager>,
     _permit: OwnedSemaphorePermit,
 }
 
 impl Deref for SftpConnection {
-    type Target = Sftp;
+    type Target = SftpClient;
 
     fn deref(&self) -> &Self::Target {
         &self.object
     }
 }
 
+/// An authenticated SSH connection with an open SFTP session.
+pub struct SftpClient {
+    pub sftp: RawSftpSession,
+    /// Largest payload of one read request.
+    pub read_len: u32,
+    /// Largest payload of one write request.
+    pub write_len: u32,
+    pub posix_rename: bool,
+    pub copy_data: bool,
+    /// The runtime of the SSH connection tasks.
+    pub runtime: tokio::runtime::Handle,
+    _ssh: client::Handle<SshHandler>,
+}
+
+/// An open file or directory handle on a pooled connection.
+///
+/// The connection stays checked out while a handle is open. Dropping the
+/// handle without [`OpenHandle::close`] closes it in the background.
+pub struct OpenHandle {
+    conn: Arc<SftpConnection>,
+    handle: Option<SftpHandle>,
+}
+
+impl OpenHandle {
+    /// Opens a file with `flags`.
+    pub async fn open(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+        flags: OpenFlags,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(conn, move |conn| async move {
+            conn.sftp.open(path, flags, FileAttributes::empty()).await
+        })
+        .await
+    }
+
+    /// Opens a directory to list.
+    pub async fn open_dir(
+        conn: Arc<SftpConnection>,
+        path: SftpString,
+    ) -> Result<Self, SftpClientError> {
+        Self::spawn_open(
+            conn,
+            move |conn| async move { conn.sftp.opendir(path).await },
+        )
+        .await
+    }
+
+    /// Sends the open request in a task that owns the result. If the caller
+    /// stops waiting, the task drops the new handle, which closes it.
+    async fn spawn_open<F, Fut>(conn: Arc<SftpConnection>, open: F) -> 
Result<Self, SftpClientError>
+    where
+        F: FnOnce(Arc<SftpConnection>) -> Fut,
+        Fut: Future<Output = Result<Handle, SftpClientError>> + Send + 'static,
+    {
+        let runtime = conn.runtime.clone();
+        let request = open(conn.clone());
+        runtime
+            .spawn(async move {
+                let handle = request.await?.handle;
+                Ok(Self {
+                    conn,
+                    handle: Some(handle),
+                })
+            })
+            .await
+            .unwrap_or_else(|err| {
+                Err(SftpClientError::UnexpectedBehavior(format!(
+                    "sftp open task failed: {err}"
+                )))
+            })
+    }
+
+    pub fn client(&self) -> &SftpClient {
+        &self.conn
+    }
+
+    pub fn connection(&self) -> &Arc<SftpConnection> {
+        &self.conn
+    }
+
+    pub fn handle(&self) -> &SftpHandle {
+        self.handle
+            .as_ref()
+            .expect("handle must stay open until close")
+    }
+
+    pub async fn close(mut self) -> Result<()> {
+        let handle = self.handle.take().expect("handle must not be closed 
twice");
+        self.conn
+            .sftp
+            .close(handle)
+            .await
+            .map(|_| ())
+            .map_err(parse_sftp_error)
+    }
+}
+
+impl Drop for OpenHandle {
+    fn drop(&mut self) {
+        let Some(handle) = self.handle.take() else {
+            return;
+        };
+        let conn = self.conn.clone();
+        self.conn.runtime.spawn(async move {
+            if let Err(err) = conn.sftp.close(handle).await {
+                debug!("failed to close SFTP handle: {err}");
+            }
+        });
+    }
+}
+
 pub struct Manager {
-    pub(super) endpoint: String,
+    pub(super) endpoint: SshEndpoint,
     pub(super) root: String,
-    pub(super) user: Option<String>,
+    pub(super) user: String,
     pub(super) key: Option<String>,
-    pub(super) known_hosts_strategy: KnownHosts,
+    pub(super) host_keys: HostKeyVerifier,
     pub(super) connect_timeout: Option<Duration>,
-    #[cfg(not(windows))]
-    pub(super) control_directory: Option<String>,
+    pub(super) handshakes: Semaphore,
 }
 
 impl Manager {
-    async fn initialize_root(&self, sftp: &Sftp) -> Result<()> {
-        create_dir_all(sftp, "", &self.root).await
-    }
-}
+    async fn connect_ssh(&self) -> Result<client::Handle<SshHandler>> {
+        let host = self.endpoint.known_hosts_name();
+        let mut config = client::Config::default();
+        config.preferred.key = Cow::Owned(prefer_recorded_algorithms(
+            &config.preferred.key,
+            &self.host_keys.recorded_algorithms(&host),
+        ));
 
-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);
+        let handler = SshHandler {
+            host,
+            host_keys: self.host_keys.clone(),
+        };
+        let mut ssh = client::connect(
+            Arc::new(config),
+            (self.endpoint.host.as_str(), self.endpoint.port),
+            handler,
+        )
+        .await
+        .map_err(SshClientError::into_error)?;
+
+        self.authenticate(&mut ssh, &self.user).await?;
+        Ok(ssh)
     }
 
-    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);
+    /// Authenticates with `key`, or with the SSH agent and the default
+    /// identity files when `key` is not set.
+    async fn authenticate(&self, ssh: &mut client::Handle<SshHandler>, user: 
&str) -> Result<()> {
+        let rsa_hash = ssh
+            .best_supported_rsa_hash()
+            .await
+            .map_err(parse_ssh_error)?
+            .flatten();
+
+        if let Some(path) = &self.key {
+            let key = russh::keys::load_secret_key(path, None).map_err(|err| {
+                Error::new(ErrorKind::ConfigInvalid, "failed to load SSH 
private key")
+                    .with_context("key", path)
+                    .set_source(err)
+            })?;
+            if authenticate_with_key(ssh, user, key, rsa_hash).await? {
+                return Ok(());
+            }
+            return Err(authentication_failed(user));
+        }
+
+        let mut rejected = false;
+        let result = async {
+            if authenticate_with_agent(ssh, user, rsa_hash, &mut 
rejected).await? {
+                return Ok(true);
+            }
+            for path in default_identity_files() {
+                // OpenSSH skips default identity files that it cannot load.
+                let Ok(key) = russh::keys::load_secret_key(&path, None) else {
+                    continue;
+                };
+                if authenticate_with_key(ssh, user, key, rsa_hash).await? {
+                    return Ok(true);
                 }
-                continue;
+                rejected = true;
+            }
+            Ok(false)
+        }
+        .await;
+        match result {
+            Ok(true) => Ok(()),
+            Ok(false) => Err(authentication_failed(user)),
+            // A server closes the connection after `MaxAuthTries` rejected 
keys.
+            Err(err) if rejected && ssh.is_closed() => {
+                Err(authentication_failed(user).set_source(err))
             }
-            Component::CurDir => continue,
-            _ => {}
+            Err(err) => Err(err),
+        }
+    }
+
+    async fn initialize_root(&self, sftp: &RawSftpSession) -> Result<()> {
+        match self.root.strip_prefix('/') {
+            Some(root) => create_dir_all(sftp, "/", root).await,
+            None => Ok(()),
         }
+    }
+}
+
+fn authentication_failed(user: &str) -> Error {
+    Error::new(
+        ErrorKind::PermissionDenied,
+        "SSH public key authentication failed",
+    )
+    .with_context("user", user)
+}
+
+async fn authenticate_with_key(
+    ssh: &mut client::Handle<SshHandler>,
+    user: &str,
+    key: russh::keys::PrivateKey,
+    rsa_hash: Option<HashAlg>,
+) -> Result<bool> {
+    let key = PrivateKeyWithHashAlg::new(Arc::new(key), rsa_hash);
+    let result = ssh
+        .authenticate_publickey(user, key)
+        .await
+        .map_err(parse_ssh_error)?;
+    Ok(result.success())
+}
+
+#[cfg(unix)]
+async fn authenticate_with_agent(
+    ssh: &mut client::Handle<SshHandler>,
+    user: &str,
+    rsa_hash: Option<HashAlg>,
+    rejected: &mut bool,
+) -> Result<bool> {
+    use russh::AgentAuthError;
+    use russh::keys::agent::AgentIdentity;
+    use russh::keys::agent::client::AgentClient;
 
-        current.push(segment);
-        if let Err(error) = fs.create_dir(segment).await {
+    let Ok(mut agent) = AgentClient::connect_env().await else {
+        return Ok(false);
+    };
+    let Ok(identities) = agent.request_identities().await else {
+        return Ok(false);
+    };
+
+    for identity in identities {
+        let AgentIdentity::PublicKey { key, .. } = identity else {
+            continue;
+        };
+        match ssh
+            .authenticate_publickey_with(user, key, rsa_hash, &mut agent)
+            .await
+        {
+            Ok(result) if result.success() => return Ok(true),
+            Ok(_) => *rejected = true,
+            // The agent can refuse to sign with one key and still hold others.
+            Err(AgentAuthError::Key(err)) => debug!("SSH agent did not sign: 
{err}"),
+            Err(AgentAuthError::Send(_)) => return 
Err(parse_ssh_error(russh::Error::SendError)),
+        }
+    }
+    Ok(false)
+}
+
+#[cfg(not(unix))]
+async fn authenticate_with_agent(
+    _: &mut client::Handle<SshHandler>,
+    _: &str,
+    _: Option<HashAlg>,
+    _: &mut bool,
+) -> Result<bool> {
+    Ok(false)
+}
+
+/// Moves the recorded host key algorithms to the front, like OpenSSH, so that 
a
+/// server with several host keys presents one that `known_hosts` records.
+fn prefer_recorded_algorithms(supported: &[Algorithm], recorded: &[Algorithm]) 
-> Vec<Algorithm> {
+    // An RSA key signs with several hash algorithms.
+    let is_recorded = |algorithm: &&Algorithm| {
+        recorded.iter().any(|r| {
+            r == *algorithm
+                || matches!(
+                    (r, algorithm),
+                    (Algorithm::Rsa { .. }, Algorithm::Rsa { .. })
+                )
+        })
+    };
+    let (mut preferred, others): (Vec<_>, Vec<_>) = 
supported.iter().partition(is_recorded);
+    preferred.extend(others);
+    preferred.into_iter().cloned().collect()
+}
+
+fn default_identity_files() -> Vec<PathBuf> {
+    let Some(home) = std::env::home_dir() else {
+        return Vec::new();
+    };
+    ["id_rsa", "id_ecdsa", "id_ed25519"]
+        .into_iter()
+        .map(|name| home.join(".ssh").join(name))
+        .collect()
+}
+
+async fn open_sftp(ssh: client::Handle<SshHandler>) -> Result<SftpClient> {
+    let channel = ssh.channel_open_session().await.map_err(parse_ssh_error)?;
+    channel
+        .request_subsystem(true, "sftp")
+        .await
+        .map_err(parse_ssh_error)?;
+
+    let config = russh_sftp::client::Config {
+        // OpenDAL's TimeoutLayer bounds operations. A per-request limit would
+        // also abort a server-side copy of a large file.
+        request_timeout_secs: u64::MAX,
+        ..Default::default()
+    };
+    let max_packet_len = u64::from(config.max_packet_len);
+    let mut sftp = RawSftpSession::new_with_config(channel.into_stream(), 
config);
+    let version = sftp.init().await.map_err(parse_sftp_error)?;

Review Comment:
   Please check the negotiated protocol version before consuming its 
extensions. The previous client rejected versions other than SFTP v3.



##########
core/services/sftp/src/writer.rs:
##########
@@ -69,3 +81,148 @@ impl oio::Write for SftpWriter {
         ))
     }
 }
+
+/// Writes `bs` to the file at `offset` and returns the offset after it once
+/// the server has acknowledged every request.
+async fn write_at(
+    sftp: &RawSftpSession,
+    handle: &SftpHandle,
+    write_len: u32,
+    mut offset: u64,
+    bs: Buffer,
+) -> Result<u64> {
+    let mut pending: VecDeque<PendingWrite> = 
VecDeque::with_capacity(MAX_PENDING_WRITES);
+    for bytes in bs {
+        for data in bytes.chunks(write_len as usize) {
+            if pending.len() == MAX_PENDING_WRITES
+                && let Some(ack) = pending.pop_front()
+            {
+                ack.await.map_err(parse_sftp_error)?;
+            }
+            pending.push_back(
+                sftp.write_nowait(handle, offset, data)
+                    .map_err(parse_sftp_error)?,
+            );
+            offset += data.len() as u64;
+        }
+    }
+    for ack in pending {
+        ack.await.map_err(parse_sftp_error)?;
+    }
+    Ok(offset)
+}
+
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+    use std::sync::Mutex;
+
+    use russh_sftp::protocol::{
+        FileAttributes, Handle, OpenFlags, SftpString, Status, StatusCode, 
Version,
+    };
+    use russh_sftp::server::StatusReply;
+
+    use super::*;
+
+    const WRITE_LEN: u32 = 4;
+
+    /// Stores one file in memory and fails the third write request once.
+    struct FlakyServer {
+        file: Arc<Mutex<Vec<u8>>>,
+        writes: usize,
+    }
+
+    impl russh_sftp::server::Handler for FlakyServer {
+        type Error = StatusReply;
+
+        fn unimplemented(&self) -> Self::Error {
+            StatusCode::OpUnsupported.into()
+        }
+
+        async fn init(
+            &mut self,
+            _: u32,
+            _: std::collections::HashMap<String, String>,
+        ) -> std::result::Result<Version, Self::Error> {
+            Ok(Version::new())
+        }
+
+        async fn open(
+            &mut self,
+            id: u32,
+            _: SftpString,
+            _: OpenFlags,
+            _: FileAttributes,
+        ) -> std::result::Result<Handle, Self::Error> {
+            Ok(Handle {
+                id,
+                handle: SftpHandle::from("file"),
+            })
+        }
+
+        async fn write(
+            &mut self,
+            id: u32,
+            _: SftpHandle,
+            offset: u64,
+            data: Vec<u8>,
+        ) -> std::result::Result<Status, Self::Error> {
+            self.writes += 1;
+            if self.writes == 3 {
+                return Err(StatusCode::Failure.into());
+            }
+            let mut file = self.file.lock().unwrap();
+            let end = offset as usize + data.len();
+            if file.len() < end {
+                file.resize(end, 0);
+            }
+            file[offset as usize..end].copy_from_slice(&data);
+            Ok(Status {
+                id,
+                status_code: StatusCode::Ok,
+                error_message: String::new(),
+                language_tag: String::new(),
+            })
+        }
+    }
+
+    #[tokio::test]
+    async fn 
retried_write_after_partial_acknowledgement_writes_each_byte_once() {
+        let (client, server) = tokio::io::duplex(64 * 1024);
+        let file = Arc::new(Mutex::new(Vec::new()));
+        russh_sftp::server::run(
+            server,
+            FlakyServer {
+                file: file.clone(),
+                writes: 0,
+            },
+        )
+        .await;
+        let sftp = RawSftpSession::new(client);
+        sftp.init().await.unwrap();
+        let handle = sftp
+            .open("file", OpenFlags::WRITE, FileAttributes::empty())
+            .await
+            .unwrap()
+            .handle;
+
+        let head = b"0123".to_vec();
+        let end = write_at(&sftp, &handle, WRITE_LEN, 0, 
Buffer::from(head.clone()))
+            .await
+            .unwrap();
+        assert_eq!(end, 4);
+
+        // The server acknowledges the first request of this buffer and fails 
the second.
+        let tail = b"abcdefghij".to_vec();
+        let err = write_at(&sftp, &handle, WRITE_LEN, end, 
Buffer::from(tail.clone()))

Review Comment:
   The retry here supplies `end` directly to `write_at`, so this test would 
still pass if `SftpWriter::write` advanced its own offset prematurely. Please 
retry through the same `SftpWriter` and verify the final file bytes.



##########
core/services/sftp/src/writer.rs:
##########
@@ -15,48 +15,60 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use bytes::Bytes;
-use openssh_sftp_client::file::File;
+use std::collections::VecDeque;
 
-use super::core::SftpConnection;
+use russh_sftp::client::RawSftpSession;
+use russh_sftp::client::rawsession::PendingWrite;
+use russh_sftp::protocol::SftpHandle;
+
+use super::core::OpenHandle;
 use super::core::parse_sftp_error;
 use opendal_core::raw::*;
 use opendal_core::*;
 
+/// Write requests sent before the writer waits for the oldest acknowledgement.
+/// Each request needs a round trip, so one request at a time is bound by 
latency.
+const MAX_PENDING_WRITES: usize = 16;
+
 pub struct SftpWriter {
-    file: Option<File>,
-    // Keep the connection checked out until after the file handle closes.
-    _conn: Option<SftpConnection>,
+    file: Option<OpenHandle>,
+    /// End of the data that the server has acknowledged.
+    offset: u64,
 }
 
 impl SftpWriter {
-    pub fn new(file: File, conn: SftpConnection) -> Self {
+    pub fn new(file: OpenHandle) -> Self {
         SftpWriter {
             file: Some(file),
-            _conn: Some(conn),
+            offset: 0,
         }
     }
 }
 
 impl oio::Write for SftpWriter {
     async fn write(&mut self, bs: Buffer) -> Result<()> {
-        let file = self.file.as_mut().ok_or_else(|| {
+        let file = self.file.as_ref().ok_or_else(|| {
             Error::new(ErrorKind::Unexpected, "sftp writer has already been 
closed")
         })?;
+        let client = file.client();
 
-        let mut chunks: Vec<Bytes> = bs.into_iter().collect();
-        file.write_all_zero_copy(&mut chunks)
-            .await
-            .map_err(parse_sftp_error)?;
-
+        // A failed write keeps the offset, so a retry sends the same bytes to
+        // the same offsets.
+        self.offset = write_at(
+            &client.sftp,
+            file.handle(),
+            client.write_len,
+            self.offset,
+            bs,
+        )
+        .await?;
         Ok(())
     }
 
     async fn close(&mut self) -> Result<Metadata> {
         if let Some(file) = self.file.take() {
-            let res = file.close().await.map_err(parse_sftp_error);
-            self._conn = None;
-            res?;
+            // The server releases the handle even when close fails, so a 
retry cannot help.
+            file.close().await.map_err(Error::set_permanent)?;

Review Comment:
   The writer takes `self.file` before the server acknowledges the close. If 
the wait is cancelled or returns an error, a second `close()` can report 
success. Please preserve the pending result or keep returning an error when the 
outcome is unknown. This behavior also existed in the previous backend.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to