ssh/channel/backend/
channel_shell.rs

1use super::channel::ChannelBroker;
2use crate::constant::{ssh_connection_code, ssh_str};
3use crate::error::SshResult;
4use crate::model::Data;
5use crate::TerminalSize;
6use std::ops::{Deref, DerefMut};
7
8pub struct ShellBrocker(ChannelBroker);
9
10impl ShellBrocker {
11    pub(crate) fn open(channel: ChannelBroker, tv: TerminalSize) -> SshResult<Self> {
12        // to open a shell channel, we need to request a pesudo-terminal
13        let mut channel_shell = ShellBrocker(channel);
14        channel_shell.request_pty(tv)?;
15        channel_shell.get_shell()?;
16        Ok(channel_shell)
17    }
18
19    fn request_pty(&mut self, tv: TerminalSize) -> SshResult<()> {
20        let tvs = tv.fetch();
21        let mut data = Data::new();
22        data.put_u8(ssh_connection_code::CHANNEL_REQUEST)
23            .put_u32(self.server_channel_no)
24            .put_str(ssh_str::PTY_REQ)
25            .put_u8(true as u8)
26            .put_str(ssh_str::XTERM_VAR)
27            .put_u32(tvs.0)
28            .put_u32(tvs.1)
29            .put_u32(tvs.2)
30            .put_u32(tvs.3);
31        let model = [
32            128, // TTY_OP_ISPEED
33            0, 1, 0xc2, 0,   // 115200
34            129, // TTY_OP_OSPEED
35            0, 1, 0xc2, 0,    // 115200 again
36            0_u8, // TTY_OP_END
37        ];
38        data.put_u8s(&model);
39        self.send(data)
40    }
41
42    fn get_shell(&mut self) -> SshResult<()> {
43        let mut data = Data::new();
44        data.put_u8(ssh_connection_code::CHANNEL_REQUEST)
45            .put_u32(self.server_channel_no)
46            .put_str(ssh_str::SHELL)
47            .put_u8(true as u8);
48        self.send(data)
49    }
50
51    /// this method will try to read as much data as we can from the server,
52    /// but it will block until at least one packet is received
53    ///
54    pub fn read(&mut self) -> SshResult<Vec<u8>> {
55        let mut out = self.recv()?;
56        while let Ok(Some(mut data)) = self.try_recv() {
57            out.append(&mut data)
58        }
59        Ok(out)
60    }
61
62    /// this method send `buf` to the remote pty
63    ///
64    pub fn write(&mut self, buf: &[u8]) -> SshResult<()> {
65        self.send_data(buf.to_vec().into())?;
66        Ok(())
67    }
68}
69
70impl Deref for ShellBrocker {
71    type Target = ChannelBroker;
72    fn deref(&self) -> &Self::Target {
73        &self.0
74    }
75}
76
77impl DerefMut for ShellBrocker {
78    fn deref_mut(&mut self) -> &mut Self::Target {
79        &mut self.0
80    }
81}