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
use crate::body::common::length_from_headers;
use futures::prelude::*;
use pin_project::pin_project;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};

#[pin_project]
pub struct BodyDecode<IO: AsyncRead + Unpin> {
    transport: IO,
    state: BodyDecodeState,
}

impl<IO: AsyncRead + Unpin> BodyDecode<IO> {
    pub fn from_headers(headers: &http::header::HeaderMap, transport: IO) -> anyhow::Result<Self> {
        Ok(BodyDecodeState::from_headers(headers)?.restore(transport))
    }
    pub fn new(transport: IO, length: Option<u64>) -> Self {
        BodyDecodeState::new(length).restore(transport)
    }
    pub fn checkpoint(self) -> (IO, BodyDecodeState) {
        (self.transport, self.state)
    }
}

impl<IO: AsyncRead + Unpin> AsyncRead for BodyDecode<IO> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let this = self.project();
        this.state.poll_read(this.transport, cx, buf)
    }
}

pub struct BodyDecodeState {
    parser_state: Parser,
    _compression_state: (),
    remaining: u64,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Parser {
    FixedLength,
    Chunked(ChunkState),
    Failed,
    Done,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ChunkState {
    Size,
    SizeLF,
    Content,
    ContentCR,
    ContentLF,
    EndCR,
    EndLF,
}

fn err_kind<T>(kind: io::ErrorKind) -> Poll<io::Result<T>> {
    Poll::Ready(Err(kind.into()))
}

impl BodyDecodeState {
    pub fn from_headers(headers: &http::header::HeaderMap) -> anyhow::Result<Self> {
        Ok(Self::new(length_from_headers(headers)?))
    }
    pub fn new(length: Option<u64>) -> Self {
        let (parser_state, remaining) = match length {
            Some(0) => (Parser::Done, 0),
            Some(length) => (Parser::FixedLength, length),
            None => (Parser::Chunked(ChunkState::Size), 0),
        };
        Self {
            parser_state,
            _compression_state: (),
            remaining,
        }
    }
    pub fn restore<IO: AsyncRead + Unpin>(self, transport: IO) -> BodyDecode<IO> {
        BodyDecode {
            transport,
            state: self,
        }
    }
    fn poll_read<IO: AsyncRead + Unpin>(
        &mut self,
        mut transport: IO,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        loop {
            let max_read_size = match self.parser_state {
                Parser::Failed => return err_kind(io::ErrorKind::BrokenPipe),
                Parser::Done => return Poll::Ready(Ok(0)),
                Parser::FixedLength | Parser::Chunked(ChunkState::Content) => {
                    if buf.len() as u64 > self.remaining {
                        self.remaining as usize
                    } else {
                        buf.len()
                    }
                }
                Parser::Chunked(chunked_state) => {
                    let mut next = [0u8];
                    match Pin::new(&mut transport).poll_read(cx, &mut next) {
                        Poll::Ready(Err(err)) => {
                            self.parser_state = Parser::Failed;
                            return Poll::Ready(Err(err));
                        }
                        Poll::Pending => return Poll::Pending,
                        Poll::Ready(Ok(0)) => {
                            self.parser_state = Parser::Failed;
                            return err_kind(io::ErrorKind::UnexpectedEof);
                        }
                        Poll::Ready(Ok(_)) => {
                            self.parser_state = match (chunked_state, next[0]) {
                                (ChunkState::Size, b'\r') => Parser::Chunked(ChunkState::SizeLF),
                                (ChunkState::Size, hex_digit) => {
                                    self.remaining *= 16;
                                    self.remaining += match hex_digit {
                                        b'0'..=b'9' => 0 + hex_digit - b'0',
                                        b'a'..=b'f' => 10 + hex_digit - b'a',
                                        b'A'..=b'F' => 10 + hex_digit - b'A',
                                        _ => {
                                            self.parser_state = Parser::Failed;
                                            return err_kind(io::ErrorKind::InvalidData);
                                        }
                                    } as u64;
                                    Parser::Chunked(ChunkState::Size)
                                }
                                (ChunkState::SizeLF, b'\n') => match self.remaining {
                                    0 => Parser::Chunked(ChunkState::EndCR),
                                    _ => Parser::Chunked(ChunkState::Content),
                                },
                                (ChunkState::Content, _) => unreachable!(),
                                (ChunkState::ContentCR, b'\r') => {
                                    Parser::Chunked(ChunkState::ContentLF)
                                }
                                (ChunkState::ContentLF, b'\n') => Parser::Chunked(ChunkState::Size),
                                (ChunkState::EndCR, b'\r') => Parser::Chunked(ChunkState::EndLF),
                                (ChunkState::EndLF, b'\n') => Parser::Done,
                                (_, _) => return err_kind(io::ErrorKind::InvalidData),
                            }
                        }
                    }
                    continue;
                }
            };
            return match Pin::new(&mut transport).poll_read(cx, &mut buf[0..max_read_size]) {
                Poll::Ready(Err(err)) => {
                    self.parser_state = Parser::Failed;
                    Poll::Ready(Err(err))
                }
                Poll::Ready(Ok(0)) => {
                    self.parser_state = Parser::Failed;
                    err_kind(io::ErrorKind::UnexpectedEof)
                }
                Poll::Ready(Ok(n)) => {
                    self.remaining -= n as u64;
                    if self.remaining == 0 {
                        self.parser_state = match self.parser_state {
                            Parser::FixedLength => Parser::Done,
                            Parser::Chunked(ChunkState::Content) => {
                                Parser::Chunked(ChunkState::ContentCR)
                            }
                            _ => unreachable!(),
                        }
                    }
                    Poll::Ready(Ok(n))
                }
                Poll::Pending => Poll::Pending,
            };
        }
    }
}