openssh_sftp_client_lowlevel/
read_end.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#![forbid(unsafe_code)]

use super::{
    awaitable_responses::ArenaArc, awaitable_responses::Response, connection::SharedData,
    reader_buffered::ReaderBuffered, Error, Extensions, ToBuffer,
};

use std::{io, num::NonZeroUsize, pin::Pin};

use openssh_sftp_error::RecursiveError;
use openssh_sftp_protocol::{
    constants::SSH2_FILEXFER_VERSION,
    response::{self, ServerVersion},
    serde::de::DeserializeOwned,
    ssh_format::{self, from_bytes},
};
use pin_project::pin_project;
use tokio::io::{copy_buf, sink, AsyncBufReadExt, AsyncRead, AsyncReadExt};
use tokio_io_utility::{read_exact_to_bytes, read_exact_to_vec};

/// The ReadEnd for the lowlevel API.
#[derive(Debug)]
#[pin_project]
pub struct ReadEnd<R, Buffer, Q, Auxiliary = ()> {
    #[pin]
    reader: ReaderBuffered<R>,
    shared_data: SharedData<Buffer, Q, Auxiliary>,
}

impl<R, Buffer, Q, Auxiliary> ReadEnd<R, Buffer, Q, Auxiliary>
where
    R: AsyncRead,
    Buffer: ToBuffer + 'static + Send + Sync,
{
    /// Must call [`ReadEnd::receive_server_hello_pinned`]
    /// or [`ReadEnd::receive_server_hello`] after this
    /// function call.
    pub fn new(
        reader: R,
        reader_buffer_len: NonZeroUsize,
        shared_data: SharedData<Buffer, Q, Auxiliary>,
    ) -> Self {
        Self {
            reader: ReaderBuffered::new(reader, reader_buffer_len),
            shared_data,
        }
    }

    /// Must be called once right after [`ReadEnd::new`]
    /// to receive the hello message from the server.
    pub async fn receive_server_hello_pinned(
        mut self: Pin<&mut Self>,
    ) -> Result<Extensions, Error> {
        // Receive server version
        let len: u32 = self.as_mut().read_and_deserialize(4).await?;
        if (len as usize) > 4096 {
            return Err(Error::SftpServerHelloMsgTooLong { len });
        }

        let drain = self
            .project()
            .reader
            .read_exact_into_buffer(len as usize)
            .await?;
        let server_version =
            ServerVersion::deserialize(&mut ssh_format::Deserializer::from_bytes(&drain))?;

        if server_version.version != SSH2_FILEXFER_VERSION {
            Err(Error::UnsupportedSftpProtocol {
                version: server_version.version,
            })
        } else {
            Ok(server_version.extensions)
        }
    }

    async fn read_and_deserialize<T: DeserializeOwned>(
        self: Pin<&mut Self>,
        size: usize,
    ) -> Result<T, Error> {
        let drain = self.project().reader.read_exact_into_buffer(size).await?;
        Ok(from_bytes(&drain)?.0)
    }

    async fn consume_packet(self: Pin<&mut Self>, len: u32, err: Error) -> Result<(), Error> {
        let reader = self.project().reader;
        if let Err(consumption_err) = copy_buf(&mut reader.take(len as u64), &mut sink()).await {
            Err(Error::RecursiveErrors(Box::new(RecursiveError {
                original_error: err,
                occuring_error: consumption_err.into(),
            })))
        } else {
            Err(err)
        }
    }

    async fn read_into_box(self: Pin<&mut Self>, len: usize) -> Result<Box<[u8]>, Error> {
        let mut vec = Vec::new();
        read_exact_to_vec(&mut self.project().reader, &mut vec, len).await?;

        Ok(vec.into_boxed_slice())
    }

    async fn read_in_data_packet_fallback(
        self: Pin<&mut Self>,
        len: usize,
    ) -> Result<Response<Buffer>, Error> {
        self.read_into_box(len).await.map(Response::AllocatedBox)
    }

    /// * `len` - excludes packet_type and request_id.
    async fn read_in_data_packet(
        mut self: Pin<&mut Self>,
        len: u32,
        buffer: Option<Buffer>,
    ) -> Result<Response<Buffer>, Error> {
        // Since the data is sent as a string, we need to consume the 4-byte length first.
        self.as_mut()
            .project()
            .reader
            .read_exact_into_buffer(4)
            .await?;

        let len = (len - 4) as usize;

        if let Some(mut buffer) = buffer {
            match buffer.get_buffer() {
                super::Buffer::Vector(vec) => {
                    read_exact_to_vec(&mut self.project().reader, vec, len).await?;
                    Ok(Response::Buffer(buffer))
                }
                super::Buffer::Slice(slice) => {
                    if slice.len() >= len {
                        self.project().reader.read_exact(slice).await?;
                        Ok(Response::Buffer(buffer))
                    } else {
                        self.read_in_data_packet_fallback(len).await
                    }
                }
                super::Buffer::Bytes(bytes) => {
                    read_exact_to_bytes(&mut self.project().reader, bytes, len).await?;
                    Ok(Response::Buffer(buffer))
                }
            }
        } else {
            self.read_in_data_packet_fallback(len).await
        }
    }

    /// * `len` - includes packet_type and request_id.
    async fn read_in_packet(self: Pin<&mut Self>, len: u32) -> Result<Response<Buffer>, Error> {
        let response: response::Response = self.read_and_deserialize(len as usize).await?;

        Ok(Response::Header(response.response_inner))
    }

    /// * `len` - excludes packet_type and request_id.
    async fn read_in_extended_reply(
        self: Pin<&mut Self>,
        len: u32,
    ) -> Result<Response<Buffer>, Error> {
        self.read_into_box(len as usize)
            .await
            .map(Response::ExtendedReply)
    }

    /// # Restart on Error
    ///
    /// Only when the returned error is [`Error::InvalidResponseId`] or
    /// [`Error::AwaitableError`], can the function be restarted.
    ///
    /// Upon other errors [`Error::IOError`], [`Error::FormatError`] and
    /// [`Error::RecursiveErrors`], the sftp session has to be discarded.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let readend = ...;
    /// loop {
    ///     let new_requests_submit = readend.wait_for_new_request().await;
    ///     if new_requests_submit == 0 {
    ///         break;
    ///     }
    ///
    ///     // If attempt to read in more than new_requests_submit, then
    ///     // `read_in_one_packet` might block forever.
    ///     for _ in 0..new_requests_submit {
    ///         readend.read_in_one_packet().await.unwrap();
    ///     }
    /// }
    /// ```
    /// # Cancel Safety
    ///
    /// This function is not cancel safe.
    ///
    /// Dropping the future might cause the response packet to be partially read,
    /// and the next read would treat the partial response as a new response.
    pub async fn read_in_one_packet_pinned(mut self: Pin<&mut Self>) -> Result<(), Error> {
        let this = self.as_mut().project();
        let drain = this.reader.read_exact_into_buffer(9).await?;
        let (len, packet_type, response_id): (u32, u8, u32) = from_bytes(&drain)?.0;

        let len = len - 5;

        let res = this.shared_data.responses().get(response_id);

        let callback = match res {
            Ok(callback) => callback,

            // Invalid response_id
            Err(err) => {
                drop(drain);

                // Consume the invalid data to return self to a valid state
                // where read_in_one_packet can be called again.
                return self.consume_packet(len, err).await;
            }
        };

        let response = if response::Response::is_data(packet_type) {
            drop(drain);

            let buffer = match callback.take_input() {
                Ok(buffer) => buffer,
                Err(err) => {
                    // Consume the invalid data to return self to a valid state
                    // where read_in_one_packet can be called again.
                    return self.consume_packet(len, err.into()).await;
                }
            };
            self.read_in_data_packet(len, buffer).await?
        } else if response::Response::is_extended_reply(packet_type) {
            drop(drain);

            self.read_in_extended_reply(len).await?
        } else {
            // Consumes 4 bytes and put back the rest, since
            // read_in_packet needs the packet_type and response_id.
            drain.subdrain(4);

            self.read_in_packet(len + 5).await?
        };

        let res = callback.done(response);

        // If counter == 2, then it must be one of the following situation:
        //  - `ReadEnd` is the only holder other than the `Arena` itself;
        //  - `ReadEnd` and the `AwaitableInner` is the holder and `AwaitableInner::drop`
        //    has already `ArenaArc::remove`d it.
        //
        // In case 1, since there is no `AwaitableInner` holding reference to it,
        // it can be removed safely.
        //
        // In case 2, since it is already removed, remove it again is a no-op.
        //
        // NOTE that if the arc is dropped after this call while having the
        // `Awaitable*::drop` executed before `callback.done`, then the callback
        // would not be removed.
        //
        // Though this kind of situation is rare.
        if ArenaArc::strong_count(&callback) == 2 {
            ArenaArc::remove(&callback);
        }

        Ok(res?)
    }

    /// Wait for next packet to be readable.
    ///
    /// Return `Ok(())` if next packet is ready and readable, `Error::IOError(io_error)`
    /// where `io_error.kind() == ErrorKind::UnexpectedEof` if `EOF` is met.
    ///
    /// # Cancel Safety
    ///
    /// This function is cancel safe.
    pub async fn ready_for_read_pinned(self: Pin<&mut Self>) -> Result<(), io::Error> {
        if self.project().reader.fill_buf().await?.is_empty() {
            // Empty buffer means EOF
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, ""))
        } else {
            Ok(())
        }
    }
}

impl<R, Buffer, Q, Auxiliary> ReadEnd<R, Buffer, Q, Auxiliary>
where
    Self: Unpin,
    R: AsyncRead,
    Buffer: ToBuffer + 'static + Send + Sync,
{
    /// Must be called once right after [`super::connect`]
    /// to receive the hello message from the server.
    pub async fn receive_server_hello(&mut self) -> Result<Extensions, Error> {
        Pin::new(self).receive_server_hello_pinned().await
    }

    /// # Restart on Error
    ///
    /// Only when the returned error is [`Error::InvalidResponseId`] or
    /// [`Error::AwaitableError`], can the function be restarted.
    ///
    /// Upon other errors [`Error::IOError`], [`Error::FormatError`] and
    /// [`Error::RecursiveErrors`], the sftp session has to be discarded.
    ///
    /// # Cancel Safety
    ///
    /// This function is not cancel safe.
    ///
    /// Dropping the future might cause the response packet to be partially read,
    /// and the next read would treat the partial response as a new response.
    pub async fn read_in_one_packet(&mut self) -> Result<(), Error> {
        Pin::new(self).read_in_one_packet_pinned().await
    }

    /// Wait for next packet to be readable.
    ///
    /// Return `Ok(())` if next packet is ready and readable, `Error::IOError(io_error)`
    /// where `io_error.kind() == ErrorKind::UnexpectedEof` if `EOF` is met.
    ///
    /// # Cancel Safety
    ///
    /// This function is cancel safe.
    pub async fn ready_for_read(&mut self) -> Result<(), io::Error> {
        Pin::new(self).ready_for_read_pinned().await
    }
}

impl<R, Buffer, Q, Auxiliary> ReadEnd<R, Buffer, Q, Auxiliary> {
    /// Return the [`SharedData`] held by [`ReadEnd`].
    pub fn get_shared_data(&self) -> &SharedData<Buffer, Q, Auxiliary> {
        &self.shared_data
    }
}