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
use core::{
    pin::Pin,
    task::{Context, Poll},
};
use std::{
    io::{Error as IoError, Read as _, Write as _},
    sync::Arc,
};

use futures_util::io::{AsyncRead, AsyncWrite};
use ssh2::{Channel, ExitSignal, ExtendedData, PtyModes, ReadWindow, Session, Stream, WriteWindow};

use crate::{error::Error, session_stream::AsyncSessionStream};

//
pub struct AsyncChannel<S> {
    inner: Channel,
    sess: Session,
    stream: Arc<S>,
}

impl<S> AsyncChannel<S> {
    pub(crate) fn from_parts(inner: Channel, sess: Session, stream: Arc<S>) -> Self {
        Self {
            inner,
            sess,
            stream,
        }
    }
}

impl<S> AsyncChannel<S>
where
    S: AsyncSessionStream + Send + Sync + 'static,
{
    pub async fn setenv(&mut self, var: &str, val: &str) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.setenv(var, val), &self.sess)
            .await
    }

    pub async fn request_pty(
        &mut self,
        term: &str,
        mode: Option<PtyModes>,
        dim: Option<(u32, u32, u32, u32)>,
    ) -> Result<(), Error> {
        self.stream
            .rw_with(
                || self.inner.request_pty(term, mode.clone(), dim),
                &self.sess,
            )
            .await
    }

    pub async fn request_pty_size(
        &mut self,
        width: u32,
        height: u32,
        width_px: Option<u32>,
        height_px: Option<u32>,
    ) -> Result<(), Error> {
        self.stream
            .rw_with(
                || {
                    self.inner
                        .request_pty_size(width, height, width_px, height_px)
                },
                &self.sess,
            )
            .await
    }

    pub async fn request_auth_agent_forwarding(&mut self) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.request_auth_agent_forwarding(), &self.sess)
            .await
    }

    pub async fn exec(&mut self, command: &str) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.exec(command), &self.sess)
            .await
    }

    pub async fn shell(&mut self) -> Result<(), Error> {
        self.stream.rw_with(|| self.inner.shell(), &self.sess).await
    }

    pub async fn subsystem(&mut self, system: &str) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.subsystem(system), &self.sess)
            .await
    }

    pub async fn process_startup(
        &mut self,
        request: &str,
        message: Option<&str>,
    ) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.process_startup(request, message), &self.sess)
            .await
    }

    pub fn stderr(&self) -> AsyncStream<S> {
        AsyncStream::from_parts(self.inner.stderr(), self.sess.clone(), self.stream.clone())
    }

    pub fn stream(&self, stream_id: i32) -> AsyncStream<S> {
        AsyncStream::from_parts(
            self.inner.stream(stream_id),
            self.sess.clone(),
            self.stream.clone(),
        )
    }

    pub async fn handle_extended_data(&mut self, mode: ExtendedData) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.handle_extended_data(mode), &self.sess)
            .await
    }

    pub fn exit_status(&self) -> Result<i32, Error> {
        self.inner.exit_status().map_err(Into::into)
    }

    pub async fn exit_signal(&self) -> Result<ExitSignal, Error> {
        self.inner.exit_signal().map_err(Into::into)
    }

    pub fn read_window(&self) -> ReadWindow {
        self.inner.read_window()
    }
    pub fn write_window(&self) -> WriteWindow {
        self.inner.write_window()
    }

    pub async fn adjust_receive_window(&mut self, adjust: u64, force: bool) -> Result<u64, Error> {
        self.stream
            .rw_with(
                || self.inner.adjust_receive_window(adjust, force),
                &self.sess,
            )
            .await
    }

    pub fn eof(&self) -> bool {
        self.inner.eof()
    }

    pub async fn send_eof(&mut self) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.send_eof(), &self.sess)
            .await
    }

    pub async fn wait_eof(&mut self) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.wait_eof(), &self.sess)
            .await
    }

    pub async fn close(&mut self) -> Result<(), Error> {
        self.stream.rw_with(|| self.inner.close(), &self.sess).await
    }

    pub async fn wait_close(&mut self) -> Result<(), Error> {
        self.stream
            .rw_with(|| self.inner.wait_close(), &self.sess)
            .await
    }
}

impl<S> AsyncRead for AsyncChannel<S>
where
    S: AsyncSessionStream + Send + Sync + 'static,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize, IoError>> {
        Pin::new(&mut self.stream(0)).poll_read(cx, buf)
    }
}

impl<S> AsyncWrite for AsyncChannel<S>
where
    S: AsyncSessionStream + Send + Sync + 'static,
{
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context,
        buf: &[u8],
    ) -> Poll<Result<usize, IoError>> {
        Pin::new(&mut self.stream(0)).poll_write(cx, buf)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), IoError>> {
        Pin::new(&mut self.stream(0)).poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), IoError>> {
        Pin::new(&mut self.stream(0)).poll_close(cx)
    }
}

//
//
//
pub struct AsyncStream<S> {
    inner: Stream,
    sess: Session,
    stream: Arc<S>,
}

impl<S> AsyncStream<S> {
    pub(crate) fn from_parts(inner: Stream, sess: Session, stream: Arc<S>) -> Self {
        Self {
            inner,
            sess,
            stream,
        }
    }
}

impl<S> AsyncRead for AsyncStream<S>
where
    S: AsyncSessionStream + Send + Sync + 'static,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize, IoError>> {
        let this = self.get_mut();
        let sess = this.sess.clone();
        let inner = &mut this.inner;

        this.stream.poll_read_with(cx, || inner.read(buf), &sess)
    }
}

impl<S> AsyncWrite for AsyncStream<S>
where
    S: AsyncSessionStream + Send + Sync + 'static,
{
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context,
        buf: &[u8],
    ) -> Poll<Result<usize, IoError>> {
        let this = self.get_mut();
        let sess = this.sess.clone();
        let inner = &mut this.inner;

        this.stream.poll_write_with(cx, || inner.write(buf), &sess)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), IoError>> {
        let this = self.get_mut();
        let sess = this.sess.clone();
        let inner = &mut this.inner;

        this.stream.poll_write_with(cx, || inner.flush(), &sess)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), IoError>> {
        self.poll_flush(cx)
    }
}