openssh_sftp_client/sftp/
openssh_session.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::{fmt::Debug, future::Future, ops::Deref, pin::Pin, sync::Arc};

use openssh::{ChildStdin, ChildStdout, Error as OpensshError, Session, Stdio};
use tokio::{sync::oneshot, task::JoinHandle};

use crate::{utils::ErrorExt, Error, Sftp, SftpAuxiliaryData, SftpOptions};

/// The openssh session
#[derive(Debug)]
pub struct OpensshSession(JoinHandle<Option<Error>>);

/// Check for openssh connection to be alive
pub trait CheckOpensshConnection {
    /// This function should only return on `Err()`.
    /// Once the sftp session is closed, the future will be cancelled (dropped).
    fn check_connection<'session>(
        self: Box<Self>,
        session: &'session Session,
    ) -> Pin<Box<dyn Future<Output = Result<(), OpensshError>> + Send + Sync + 'session>>;
}

impl<F> CheckOpensshConnection for F
where
    F: for<'session> FnOnce(
        &'session Session,
    ) -> Pin<
        Box<dyn Future<Output = Result<(), OpensshError>> + Send + Sync + 'session>,
    >,
{
    fn check_connection<'session>(
        self: Box<Self>,
        session: &'session Session,
    ) -> Pin<Box<dyn Future<Output = Result<(), OpensshError>> + Send + Sync + 'session>> {
        (self)(session)
    }
}

impl Drop for OpensshSession {
    fn drop(&mut self) {
        self.0.abort();
    }
}

#[cfg_attr(
    feature = "tracing",
    tracing::instrument(name = "session_task", skip(tx, check_openssh_connection))
)]
async fn create_session_task(
    session: impl Deref<Target = Session> + Clone + Debug + Send + Sync,
    tx: oneshot::Sender<Result<(ChildStdin, ChildStdout), OpensshError>>,
    check_openssh_connection: Option<Box<dyn CheckOpensshConnection + Send + Sync>>,
) -> Option<Error> {
    #[cfg(feature = "tracing")]
    tracing::info!("Connecting to sftp subsystem, session = {session:?}");

    let res = Session::to_subsystem(session.clone(), "sftp")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .await;

    let mut child = match res {
        Ok(child) => child,
        Err(err) => {
            #[cfg(feature = "tracing")]
            tracing::error!(
                "Failed to connect to remote sftp subsystem: {err}, session = {session:?}"
            );

            tx.send(Err(err)).unwrap(); // Err
            return None;
        }
    };

    #[cfg(feature = "tracing")]
    tracing::info!("Connection to sftp subsystem established, session = {session:?}");

    let stdin = child.stdin().take().unwrap();
    let stdout = child.stdout().take().unwrap();
    tx.send(Ok((stdin, stdout))).unwrap(); // Ok

    let original_error = {
        let check_conn_future = async {
            if let Some(checker) = check_openssh_connection {
                checker
                    .check_connection(&session)
                    .await
                    .err()
                    .map(Error::from)
            } else {
                None
            }
        };

        let wait_on_child_future = async {
            match child.wait().await {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        Some(Error::SftpServerFailure(exit_status))
                    } else {
                        None
                    }
                }
                Err(err) => Some(err.into()),
            }
        };
        tokio::pin!(wait_on_child_future);

        tokio::select! {
            biased;

            original_error = check_conn_future => {
                let occuring_error = wait_on_child_future.await;
                match (original_error, occuring_error) {
                    (Some(original_error), Some(occuring_error)) => {
                        Some(original_error.error_on_cleanup(occuring_error))
                    }
                    (Some(err), None) | (None, Some(err)) => Some(err),
                    (None, None) => None,
                }
            }
            original_error = &mut wait_on_child_future => original_error,
        }
    };

    #[cfg(feature = "tracing")]
    if let Some(err) = &original_error {
        tracing::error!(
            "Waiting on remote sftp subsystem to exit failed: {err}, session = {session:?}"
        );
    }

    original_error
}

impl Sftp {
    /// Create [`Sftp`] from [`openssh::Session`].
    ///
    /// Calling [`Sftp::close`] on sftp instances created using this function
    /// would also await on [`openssh::RemoteChild::wait`] and
    /// [`openssh::Session::close`] and propagate their error in
    /// [`Sftp::close`].
    pub async fn from_session(session: Session, options: SftpOptions) -> Result<Self, Error> {
        Self::from_session_with_check_connection_inner(session, options, None).await
    }

    /// Similar to [`Sftp::from_session`], but takes an additional parameter
    /// for checking if the connection is still alive.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// fn check_connection<'session>(
    ///     session: &'session openssh::Session,
    /// ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), openssh::Error>> + Send + Sync + 'session>> {
    ///     Box::pin(async move {
    ///         loop {
    ///             tokio::time::sleep(std::time::Duration::from_secs(10)).await;
    ///             session.check().await?;
    ///         }
    ///         Ok(())
    ///     })
    /// }
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), openssh_sftp_client::Error> {
    /// openssh_sftp_client::Sftp::from_session_with_check_connection(
    ///     openssh::Session::connect_mux("me@ssh.example.com", openssh::KnownHosts::Strict).await?,
    ///     openssh_sftp_client::SftpOptions::default(),
    ///     check_connection,
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_session_with_check_connection(
        session: Session,
        options: SftpOptions,
        check_openssh_connection: impl CheckOpensshConnection + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        Self::from_session_with_check_connection_inner(
            session,
            options,
            Some(Box::new(check_openssh_connection)),
        )
        .await
    }

    async fn from_session_with_check_connection_inner(
        session: Session,
        options: SftpOptions,
        check_openssh_connection: Option<Box<dyn CheckOpensshConnection + Send + Sync>>,
    ) -> Result<Self, Error> {
        let (tx, rx) = oneshot::channel();

        Self::from_session_task(
            options,
            rx,
            tokio::spawn(async move {
                let original_error =
                    create_session_task(&session, tx, check_openssh_connection).await;

                let _session_str = format!("{session:?}");
                let occuring_error = session.close().await.err().map(Error::from);

                #[cfg(feature = "tracing")]
                if let Some(err) = &occuring_error {
                    tracing::error!("Closing session failed: {err}, session = {_session_str}");
                }

                match (original_error, occuring_error) {
                    (Some(original_error), Some(occuring_error)) => {
                        Some(original_error.error_on_cleanup(occuring_error))
                    }
                    (Some(err), None) | (None, Some(err)) => Some(err),
                    (None, None) => None,
                }
            }),
        )
        .await
    }

    /// Create [`Sftp`] from any type that can be dereferenced to [`openssh::Session`]
    /// and is clonable.
    pub async fn from_clonable_session(
        session: impl Deref<Target = Session> + Clone + Debug + Send + Sync + 'static,
        options: SftpOptions,
    ) -> Result<Self, Error> {
        Self::from_clonable_session_with_check_connection_inner(session, options, None).await
    }

    /// Similar to [`Sftp::from_session_with_check_connection`], but takes an additional parameter
    /// for checking if the connection is still alive.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// fn check_connection<'session>(
    ///     session: &'session openssh::Session,
    /// ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), openssh::Error>> + Send + Sync + 'session>> {
    ///     Box::pin(async move {
    ///         loop {
    ///             tokio::time::sleep(std::time::Duration::from_secs(10)).await;
    ///             session.check().await?;
    ///         }
    ///         Ok(())
    ///     })
    /// }
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), openssh_sftp_client::Error> {
    /// openssh_sftp_client::Sftp::from_clonable_session_with_check_connection(
    ///     std::sync::Arc::new(openssh::Session::connect_mux("me@ssh.example.com", openssh::KnownHosts::Strict).await?),
    ///     openssh_sftp_client::SftpOptions::default(),
    ///     check_connection,
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_clonable_session_with_check_connection(
        session: impl Deref<Target = Session> + Clone + Debug + Send + Sync + 'static,
        options: SftpOptions,
        check_openssh_connection: impl CheckOpensshConnection + Send + Sync + 'static,
    ) -> Result<Self, Error> {
        Self::from_clonable_session_with_check_connection_inner(
            session,
            options,
            Some(Box::new(check_openssh_connection)),
        )
        .await
    }

    async fn from_clonable_session_with_check_connection_inner(
        session: impl Deref<Target = Session> + Clone + Debug + Send + Sync + 'static,
        options: SftpOptions,
        check_openssh_connection: Option<Box<dyn CheckOpensshConnection + Send + Sync>>,
    ) -> Result<Self, Error> {
        let (tx, rx) = oneshot::channel();

        Self::from_session_task(
            options,
            rx,
            tokio::spawn(create_session_task(session, tx, check_openssh_connection)),
        )
        .await
    }

    async fn from_session_task(
        options: SftpOptions,
        rx: oneshot::Receiver<Result<(ChildStdin, ChildStdout), OpensshError>>,
        handle: JoinHandle<Option<Error>>,
    ) -> Result<Self, Error> {
        let msg = "Task failed without sending anything, so it must have panicked";

        let (stdin, stdout) = match rx.await {
            Ok(res) => res?,
            Err(_) => return Err(handle.await.expect_err(msg).into()),
        };

        Self::new_with_auxiliary(
            stdin,
            stdout,
            options,
            SftpAuxiliaryData::ArcedOpensshSession(Arc::new(OpensshSession(handle))),
        )
        .await
    }
}

impl OpensshSession {
    pub(super) async fn recover_session_err(mut self) -> Result<(), Error> {
        if let Some(err) = (&mut self.0).await? {
            Err(err)
        } else {
            Ok(())
        }
    }
}