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
use super::{Connection, Error, Response, Result};

use std::io::ErrorKind;

enum EstablishedSessionState {
    Exited(Option<u32>),
    TtyAllocFail,
}

/// # Cancel safety
///
/// All methods of this struct is not cancellation safe.
#[derive(Debug)]
pub struct EstablishedSession {
    pub(super) conn: Connection,
    pub(super) session_id: u32,
}
impl EstablishedSession {
    fn check_session_id(&self, session_id: u32) -> Result<()> {
        if self.session_id != session_id {
            Err(Error::UnmatchedSessionId)
        } else {
            Ok(())
        }
    }

    /// Return None if TtyAllocFail, Some(...) if the process exited.
    async fn wait_impl(&mut self) -> Result<EstablishedSessionState> {
        use Response::*;

        let response = match self.conn.read_response().await {
            Result::Ok(response) => response,
            Err(err) => match &err {
                Error::IOError(io_err) if io_err.kind() == ErrorKind::UnexpectedEof => {
                    return Result::Ok(EstablishedSessionState::Exited(None))
                }
                _ => return Err(err),
            },
        };

        match response {
            TtyAllocFail { session_id } => {
                self.check_session_id(session_id)?;
                Result::Ok(EstablishedSessionState::TtyAllocFail)
            }
            ExitMessage {
                session_id,
                exit_value,
            } => {
                self.check_session_id(session_id)?;
                Result::Ok(EstablishedSessionState::Exited(Some(exit_value)))
            }
            response => Err(Error::InvalidServerResponse(
                "Expected Response TtyAllocFail or ExitMessage",
                response,
            )),
        }
    }

    /// Wait for session status to change
    ///
    /// Return `Self` on error so that you can handle the error and restart
    /// the operation.
    ///
    /// If the server close the connection without sending anything,
    /// this function would return `Ok(None)`.
    pub async fn wait(mut self) -> Result<SessionStatus, (Error, Self)> {
        use EstablishedSessionState::*;

        match self.wait_impl().await {
            Ok(Exited(exit_value)) => Ok(SessionStatus::Exited { exit_value }),
            Ok(TtyAllocFail) => Ok(SessionStatus::TtyAllocFail(self)),
            Err(err) => Err((err, self)),
        }
    }

    /// Return None if the socket is not readable,
    /// Some(None) if TtyAllocFail, Some(Some(...)) if the process exited.
    fn try_wait_impl(&mut self) -> Result<Option<EstablishedSessionState>> {
        use Response::*;

        let response = match self.conn.try_read_response() {
            Result::Ok(Some(response)) => response,
            Result::Ok(None) => return Result::Ok(None),
            Err(err) => match &err {
                Error::IOError(io_err) if io_err.kind() == ErrorKind::UnexpectedEof => {
                    return Result::Ok(Some(EstablishedSessionState::Exited(None)))
                }
                _ => return Err(err),
            },
        };

        match response {
            TtyAllocFail { session_id } => {
                self.check_session_id(session_id)?;
                Result::Ok(Some(EstablishedSessionState::TtyAllocFail))
            }
            ExitMessage {
                session_id,
                exit_value,
            } => {
                self.check_session_id(session_id)?;
                Result::Ok(Some(EstablishedSessionState::Exited(Some(exit_value))))
            }
            response => Err(Error::InvalidServerResponse(
                "Expected Response TtyAllocFail or ExitMessage",
                response,
            )),
        }
    }

    /// Since waiting for the remote child to exit is basically waiting for the socket
    /// to become readable, try_wait is basically polling for readable.
    ///
    /// If it is readable, then it would read the entire packet in blocking manner.
    /// While this is indeed a blocking call, it is unlikely to block since
    /// the ssh multiplex master most likely would send it using one write/send.
    ///
    /// And even if it does employ multiple write/send, these functions would just
    /// return immediately since the buffer for the unix socket is empty
    /// and should be big enough for one packet.
    ///
    /// If it is not readable, then it would return Ok(InProgress).
    pub fn try_wait(mut self) -> Result<TryWaitSessionStatus, (Error, Self)> {
        use EstablishedSessionState::*;

        match self.try_wait_impl() {
            Ok(Some(Exited(exit_value))) => Ok(TryWaitSessionStatus::Exited { exit_value }),
            Ok(Some(TtyAllocFail)) => Ok(TryWaitSessionStatus::TtyAllocFail(self)),
            Ok(None) => Ok(TryWaitSessionStatus::InProgress(self)),
            Err(err) => Err((err, self)),
        }
    }
}

#[derive(Debug)]
pub enum SessionStatus {
    /// Remote ssh server failed to allocate a tty, you can now return the tty
    /// to cooked mode.
    ///
    /// This arm includes `EstablishedSession` so that you can call `wait` on it
    /// again and retrieve the exit status and the underlying connection.
    TtyAllocFail(EstablishedSession),

    /// The process on the remote machine has exited with `exit_value`.
    Exited { exit_value: Option<u32> },
}

#[derive(Debug)]
pub enum TryWaitSessionStatus {
    /// Remote ssh server failed to allocate a tty, you can now return the tty
    /// to cooked mode.
    ///
    /// This arm includes `EstablishedSession` so that you can call `wait` on it
    /// again and retrieve the exit status and the underlying connection.
    TtyAllocFail(EstablishedSession),

    /// The process on the remote machine has exited with `exit_value`.
    Exited {
        exit_value: Option<u32>,
    },

    InProgress(EstablishedSession),
}