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
use std::{
    io::{Read, Write},
    sync::mpsc::{Receiver, Sender},
    vec,
};

use crate::{
    client::Client,
    constant::ssh_connection_code,
    error::{SshError, SshResult},
    model::{BackendResp, BackendRqst, Data, FlowControl, Packet},
    TerminalSize,
};
use tracing::*;

#[cfg(feature = "scp")]
use super::channel_scp::ScpBroker;
use super::{channel_exec::ExecBroker, channel_shell::ShellBrocker};

pub(crate) struct Channel {
    snd: Sender<BackendResp>,
    server_channel_no: u32,
    client_channel_no: u32,
    remote_close: bool,
    local_close: bool,
    flow_control: FlowControl,
    pending_send: Vec<u8>,
}

impl Channel {
    pub fn new(
        server_channel_no: u32,
        client_channel_no: u32,
        remote_window: u32,
        snd: Sender<BackendResp>,
    ) -> SshResult<Self> {
        snd.send(BackendResp::Ok(server_channel_no))?;

        Ok(Self {
            snd,
            server_channel_no,
            client_channel_no,
            remote_close: false,
            local_close: false,
            flow_control: FlowControl::new(remote_window),
            pending_send: vec![],
        })
    }

    pub fn send_data<S>(&mut self, data: Data, client: &mut Client, stream: &mut S) -> SshResult<()>
    where
        S: Read + Write,
    {
        self.pending_send.append(&mut data.into_inner());
        self.try_send_data(client, stream)
    }

    fn try_send_data<S>(&mut self, client: &mut Client, stream: &mut S) -> SshResult<()>
    where
        S: Read + Write,
    {
        // try to send as much as we can
        while !self.pending_send.is_empty() {
            if self.flow_control.can_send() {
                let maybe_remain = self.flow_control.tune_on_send(&mut self.pending_send);

                // send it
                let mut data = Data::new();
                data.put_u8(ssh_connection_code::CHANNEL_DATA)
                    .put_u32(self.server_channel_no)
                    .put_u8s(&self.pending_send);

                // update remain
                self.pending_send = maybe_remain;

                self.send(data, client, stream)?;
            } else {
                break;
            }
        }
        Ok(())
    }

    pub fn send<S>(&mut self, data: Data, client: &mut Client, stream: &mut S) -> SshResult<()>
    where
        S: Read + Write,
    {
        if !self.is_close() {
            data.pack(client).write_stream(stream)
        } else {
            Err(SshError::GeneralError(
                "Send data on a closed channel".to_owned(),
            ))
        }
    }

    pub fn recv<S>(&mut self, mut data: Data, client: &mut Client, stream: &mut S) -> SshResult<()>
    where
        S: Read + Write,
    {
        let mut buf = data.get_u8s();
        // flow_control
        self.flow_control.tune_on_recv(&mut buf);
        self.send_window_adjust(buf.len() as u32, client, stream)?;
        self.snd.send(BackendResp::Data(buf.into()))?;
        Ok(())
    }

    fn send_window_adjust<S>(
        &mut self,
        to_add: u32,
        client: &mut Client,
        stream: &mut S,
    ) -> SshResult<()>
    where
        S: Read + Write,
    {
        let mut data = Data::new();
        data.put_u8(ssh_connection_code::CHANNEL_WINDOW_ADJUST)
            .put_u32(self.server_channel_no)
            .put_u32(to_add);
        self.flow_control.on_send(to_add);
        self.send(data, client, stream)
    }

    pub fn recv_window_adjust<S>(
        &mut self,
        to_add: u32,
        client: &mut Client,
        stream: &mut S,
    ) -> SshResult<()>
    where
        S: Read + Write,
    {
        self.flow_control.on_recv(to_add);
        if !self.pending_send.is_empty() {
            self.try_send_data(client, stream)
        } else {
            Ok(())
        }
    }

    pub fn local_close(&mut self) -> SshResult<()> {
        trace!("Channel {} send local close", self.client_channel_no);
        self.local_close = true;
        Ok(())
    }

    pub fn remote_close(&mut self) -> SshResult<()> {
        trace!("Channel {} recv remote close", self.client_channel_no);
        self.remote_close = true;
        if !self.local_close {
            self.snd.send(BackendResp::Close)?;
        }
        Ok(())
    }

    pub fn success(&mut self) -> SshResult<()> {
        self.snd.send(BackendResp::Ok(self.client_channel_no))?;
        Ok(())
    }

    pub fn failed(&mut self) -> SshResult<()> {
        self.snd.send(BackendResp::Fail("".to_owned()))?;
        Ok(())
    }

    pub fn is_close(&self) -> bool {
        self.local_close && self.remote_close
    }
}

impl Drop for Channel {
    fn drop(&mut self) {
        info!("Channel {} closed", self.client_channel_no);
    }
}

pub struct ChannelBroker {
    pub(crate) client_channel_no: u32,
    pub(crate) server_channel_no: u32,
    pub(crate) rcv: Receiver<BackendResp>,
    pub(crate) snd: Sender<BackendRqst>,
    pub(crate) close: bool,
}

impl ChannelBroker {
    pub(crate) fn new(
        client_id: u32,
        server_id: u32,
        rcv: Receiver<BackendResp>,
        snd: Sender<BackendRqst>,
    ) -> Self {
        Self {
            client_channel_no: client_id,
            server_channel_no: server_id,
            rcv,
            snd,
            close: false,
        }
    }

    /// open a [ExecBroker] channel which can excute commands
    ///
    pub fn exec(self) -> SshResult<ExecBroker> {
        Ok(ExecBroker::open(self))
    }

    /// open a [ScpBroker] channel which can download/upload files/directories
    ///
    #[cfg(feature = "scp")]
    pub fn scp(self) -> SshResult<ScpBroker> {
        Ok(ScpBroker::open(self))
    }

    /// open a [ShellBrocker] channel which  can be used as a pseudo terminal (AKA PTY)
    ///
    pub fn shell(self, tv: TerminalSize) -> SshResult<ShellBrocker> {
        ShellBrocker::open(self, tv)
    }

    /// close the backend channel and consume the channel broker itself
    ///
    pub fn close(mut self) -> SshResult<()> {
        self.close_no_consue()
    }

    fn close_no_consue(&mut self) -> SshResult<()> {
        if !self.close {
            let mut data = Data::new();
            data.put_u8(ssh_connection_code::CHANNEL_CLOSE)
                .put_u32(self.server_channel_no);
            self.close = true;
            self.snd
                .send(BackendRqst::CloseChannel(self.client_channel_no, data))?;
        }
        Ok(())
    }

    pub(super) fn send_data(&self, data: Data) -> SshResult<()> {
        self.snd
            .send(BackendRqst::Data(self.client_channel_no, data))?;
        Ok(())
    }

    pub(super) fn send(&self, data: Data) -> SshResult<()> {
        self.snd
            .send(BackendRqst::Command(self.client_channel_no, data))?;
        if !self.close {
            match self.rcv.recv().unwrap() {
                BackendResp::Ok(_) => trace!("{}: control command ok", self.client_channel_no),
                BackendResp::Fail(msg) => error!(
                    "{}: channel error with reason {}",
                    self.client_channel_no, msg
                ),
                _ => unreachable!(),
            }
        }
        Ok(())
    }

    pub(super) fn recv(&mut self) -> SshResult<Vec<u8>> {
        if self.close {
            Ok(vec![])
        } else {
            match self.rcv.recv().unwrap() {
                BackendResp::Close => {
                    // the remote actively close their end
                    // but we can send close later when the broker get dropped
                    // just set a flag here
                    self.close = true;
                    Ok(vec![])
                }
                BackendResp::Data(data) => Ok(data.into_inner()),
                _ => unreachable!(),
            }
        }
    }

    pub(super) fn try_recv(&mut self) -> SshResult<Option<Vec<u8>>> {
        if !self.close {
            if let Ok(rqst) = self.rcv.try_recv() {
                match rqst {
                    BackendResp::Close => {
                        // the remote actively close their end
                        // but we can send close later when the broker get dropped
                        // just set a flag here
                        self.close = true;
                        Ok(None)
                    }
                    BackendResp::Data(data) => Ok(Some(data.into_inner())),
                    _ => unreachable!(),
                }
            } else {
                Ok(None)
            }
        } else {
            Err(SshError::GeneralError(
                "Read data on a closed channel".to_owned(),
            ))
        }
    }

    pub(super) fn recv_to_end(&mut self) -> SshResult<Vec<u8>> {
        let mut buf = vec![];
        while !self.close {
            buf.append(&mut self.recv()?);
        }
        Ok(buf)
    }
}

impl Drop for ChannelBroker {
    fn drop(&mut self) {
        let _ = self.close_no_consue();
    }
}