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


##########
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:
   83a4121f2 opens the TCP stream itself and keeps a duplicate of the socket 
until authentication succeeds. If the stage ends early, by timeout or error, it 
shuts the socket down, so russh's session task stops. 
`stalled_ssh_connection_respects_subsecond_timeout` now uses a server that 
sends its version and then stalls in key exchange. The test waits for EOF on 
that socket, and it fails without the shutdown.
   
   *This comment is AI assisted.*



##########
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:
   83a4121f2 expands a leading `~` (`~` and `~/…`) in `key` at build time, as 
`ssh -i` does; `~user/` stays as is. It asks for `best_supported_rsa_hash()` 
only when the key or agent identity is RSA, and asks only once per connection.
   
   *This comment is AI assisted.*



##########
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:
   83a4121f2 returns `Unsupported` before reading extensions when the server 
answers with a version other than 3. 
`server_with_another_protocol_version_is_unsupported` checks it against an 
in-process server.
   
   *This comment is AI assisted.*



-- 
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