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
use std::{fmt::Debug, task::Poll};

use futures::{
    io::{BufReader, Lines},
    stream::{once, BoxStream},
    AsyncBufReadExt, AsyncRead, AsyncReadExt, Stream, StreamExt,
};
use http::{
    header::{CONTENT_LENGTH, TRANSFER_ENCODING},
    HeaderMap,
};

#[derive(Debug, thiserror::Error)]
pub enum BodyReaderError {
    #[error("Parse CONTENT_LENGTH header with error: {0}")]
    ParseContentLength(String),

    #[error("Parse TRANSFER_ENCODING header with error: {0}")]
    ParseTransferEncoding(String),

    #[error("CONTENT_LENGTH or TRANSFER_ENCODING not found.")]
    UnsporTransferEncoding,

    #[error(transparent)]
    Io(#[from] std::io::Error),
}

pub type BodyReaderResult<T> = Result<T, BodyReaderError>;

/// The sender to send http body data to peer.
pub struct BodyReader {
    length: Option<usize>,
    stream: BoxStream<'static, std::io::Result<Vec<u8>>>,
}

impl Debug for BodyReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "BodyReader, length={:?}", self.length)
    }
}

impl From<Vec<u8>> for BodyReader {
    fn from(value: Vec<u8>) -> Self {
        Self {
            length: Some(value.len()),
            stream: Box::pin(once(async move { Ok(value) })),
        }
    }
}

impl From<&[u8]> for BodyReader {
    fn from(value: &[u8]) -> Self {
        value.to_owned().into()
    }
}

impl From<&str> for BodyReader {
    fn from(value: &str) -> Self {
        value.as_bytes().into()
    }
}

impl From<String> for BodyReader {
    fn from(value: String) -> Self {
        value.as_bytes().into()
    }
}

impl BodyReader {
    pub fn empty() -> Self {
        BodyReader::from(vec![])
    }
    /// Create a new `BodySender` instance from `stream`
    pub fn from_stream<S>(stream: S) -> Self
    where
        S: Stream<Item = std::io::Result<Vec<u8>>> + Send + Unpin + 'static,
    {
        Self {
            length: None,
            stream: Box::pin(stream),
        }
    }

    /// Return true if the underlying data is a stream
    pub fn len(&self) -> Option<usize> {
        self.length
    }

    /// Parse headers and generate property `BodyReader`.
    pub async fn parse<R>(headers: &HeaderMap, mut read: R) -> BodyReaderResult<Self>
    where
        R: AsyncRead + Unpin + Send + 'static,
    {
        // TRANSFER_ENCODING has higher priority
        if let Some(transfer_encoding) = headers.get(TRANSFER_ENCODING) {
            let transfer_encoding = transfer_encoding
                .to_str()
                .map_err(|err| BodyReaderError::ParseTransferEncoding(err.to_string()))?;

            if transfer_encoding != "chunked" {
                return Err(BodyReaderError::ParseTransferEncoding(format!(
                    "Unsupport TRANSFER_ENCODING: {}",
                    transfer_encoding
                )));
            }

            return Ok(Self::from_stream(ChunkedBodyStream::from(read)));
        }

        if let Some(content_length) = headers.get(CONTENT_LENGTH) {
            let content_length = content_length
                .to_str()
                .map_err(|err| BodyReaderError::ParseContentLength(err.to_string()))?;

            let content_length = usize::from_str_radix(content_length, 10)
                .map_err(|err| BodyReaderError::ParseContentLength(err.to_string()))?;

            let mut buf = vec![0u8; content_length];

            read.read_exact(&mut buf).await?;

            return Ok(buf.into());
        }

        Ok(Self::from(vec![]))
    }
}

impl Stream for BodyReader {
    type Item = std::io::Result<Vec<u8>>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.stream.poll_next_unpin(cx)
    }
}

struct ChunkedBodyStream<R> {
    lines: Lines<BufReader<R>>,
    chunk_len: Option<usize>,
}

impl<R> From<R> for ChunkedBodyStream<R>
where
    R: AsyncRead + Unpin,
{
    fn from(value: R) -> Self {
        Self {
            lines: BufReader::new(value).lines(),
            chunk_len: None,
        }
    }
}

impl<R> Stream for ChunkedBodyStream<R>
where
    R: AsyncRead + Unpin,
{
    type Item = std::io::Result<Vec<u8>>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        loop {
            if let Some(mut len) = self.chunk_len {
                match self.lines.poll_next_unpin(cx) {
                    Poll::Ready(Some(Ok(buf))) => {
                        if buf.len() > len {
                            return Poll::Ready(Some(Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "chunck data overflow",
                            ))));
                        }

                        len -= buf.len();

                        if len == 0 {
                            self.chunk_len.take();
                        } else {
                            self.chunk_len = Some(len);
                        }

                        return Poll::Ready(Some(Ok(buf.into_bytes())));
                    }
                    poll => return poll.map_ok(|s| s.into_bytes()),
                }
            } else {
                match self.lines.poll_next_unpin(cx) {
                    Poll::Ready(Some(Ok(line))) => match usize::from_str_radix(&line, 16) {
                        Ok(len) => {
                            // body last chunk.
                            if len == 0 {
                                return Poll::Ready(None);
                            }

                            self.chunk_len = Some(len);
                            continue;
                        }
                        Err(err) => {
                            return Poll::Ready(Some(Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                format!("Parse chunck length with error: {}", err),
                            ))))
                        }
                    },
                    poll => return poll.map_ok(|s| s.into_bytes()),
                }
            }
        }
    }
}