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
use bytes::{Buf, Bytes, BytesMut};
use futures::{Async, Future, Poll, Stream};
use http::header::HeaderMap;
use hyper::body::{self, Body, Payload as _Payload};
use mime;
use std::marker::PhantomData;
use std::ops::Deref;
use std::{fmt, mem};
use error::{CritError, Error};
use super::global::with_get_current;
use super::header::content_type;
use super::upgrade::{OnUpgrade, OnUpgradeObj};
use super::Input;
pub struct RequestBody {
body: Option<Body>,
on_upgrade: Option<OnUpgradeObj>,
}
impl fmt::Debug for RequestBody {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("RequestBody")
.field("body", &self.body)
.field("on_upgrade", &self.on_upgrade.as_ref().map(|_| "<upgrade>"))
.finish()
}
}
impl RequestBody {
pub(crate) fn from_hyp(body: Body) -> RequestBody {
RequestBody {
body: Some(body),
on_upgrade: None,
}
}
pub fn is_gone(&self) -> bool {
self.body.is_none()
}
pub fn payload(&mut self) -> Payload {
Payload(self.body.take())
}
pub fn read_all(&mut self) -> ReadAll {
ReadAll {
state: ReadAllState::Init(self.body.take()),
}
}
pub fn is_upgraded(&self) -> bool {
self.on_upgrade.is_some()
}
pub fn on_upgrade<T: OnUpgrade>(&mut self, on_upgrade: T) -> Option<T> {
if self.on_upgrade.is_some() {
return Some(on_upgrade);
}
self.on_upgrade = Some(OnUpgradeObj::new(on_upgrade));
None
}
pub(crate) fn deconstruct(self) -> (Option<Body>, Option<OnUpgradeObj>) {
(self.body, self.on_upgrade)
}
}
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Payload(Option<Body>);
impl Payload {
fn with_body<T>(&mut self, f: impl FnOnce(&mut Body) -> Result<T, CritError>) -> Result<T, CritError> {
match self.0 {
Some(ref mut bd) => f(bd),
None => Err(format_err!("").compat().into()),
}
}
}
impl body::Payload for Payload {
type Data = Chunk;
type Error = CritError;
fn poll_data(&mut self) -> Poll<Option<Chunk>, CritError> {
self.with_body(|bd| {
bd.poll_data()
.map(|x| x.map(|c| c.map(Chunk::from_hyp)))
.map_err(Into::into)
})
}
fn poll_trailers(&mut self) -> Poll<Option<HeaderMap>, CritError> {
self.with_body(|bd| bd.poll_trailers().map_err(Into::into))
}
fn is_end_stream(&self) -> bool {
self.0.as_ref().map_or(true, |bd| bd.is_end_stream())
}
fn content_length(&self) -> Option<u64> {
self.0.as_ref().and_then(|bd| bd.content_length())
}
}
impl Stream for Payload {
type Item = Chunk;
type Error = CritError;
#[inline]
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
self.poll_data()
}
}
#[derive(Debug)]
pub struct Chunk(pub(crate) body::Chunk);
impl Chunk {
fn from_hyp(chunk: body::Chunk) -> Chunk {
Chunk(chunk)
}
pub fn into_bytes(self) -> Bytes {
self.0.into_bytes()
}
}
impl Into<Bytes> for Chunk {
fn into(self) -> Bytes {
self.into_bytes()
}
}
impl AsRef<[u8]> for Chunk {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl Deref for Chunk {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl IntoIterator for Chunk {
type Item = u8;
type IntoIter = <body::Chunk as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl Buf for Chunk {
fn remaining(&self) -> usize {
self.0.remaining()
}
fn bytes(&self) -> &[u8] {
self.0.bytes()
}
fn advance(&mut self, cnt: usize) {
self.0.advance(cnt)
}
}
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct ReadAll {
state: ReadAllState,
}
#[derive(Debug)]
enum ReadAllState {
Init(Option<Body>),
Receiving(Body, BytesMut),
Done,
}
impl ReadAll {
pub fn poll_ready(&mut self) -> Poll<Bytes, CritError> {
use self::ReadAllState::*;
loop {
match self.state {
Init(..) => {}
Receiving(ref mut body, ref mut buf) => {
while let Some(chunk) = try_ready!(body.poll_data()) {
buf.extend_from_slice(&*chunk);
}
}
Done => panic!("cannot resolve twice"),
}
match mem::replace(&mut self.state, Done) {
Init(Some(body)) => {
self.state = Receiving(body, BytesMut::new());
continue;
}
Init(None) => return Err(format_err!("").compat().into()),
Receiving(_body, buf) => {
return Ok(Async::Ready(buf.freeze()));
}
Done => unreachable!(),
}
}
}
pub fn convert_to<T>(self) -> ConvertTo<T>
where
T: FromData + 'static,
{
ConvertTo {
read_all: self,
_marker: PhantomData,
}
}
}
impl Future for ReadAll {
type Item = Bytes;
type Error = CritError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.poll_ready()
}
}
#[must_use = "futures do nothing unless polled"]
pub struct ConvertTo<T> {
read_all: ReadAll,
_marker: PhantomData<fn() -> T>,
}
impl<T> fmt::Debug for ConvertTo<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ConvertTo").field("read_all", &self.read_all).finish()
}
}
impl<T> ConvertTo<T>
where
T: FromData,
{
pub fn poll_ready(&mut self, input: &mut Input) -> Poll<T, Error> {
let data = try_ready!(self.read_all.poll().map_err(Error::critical));
T::from_data(data, input).map(Async::Ready)
}
}
impl<T> Future for ConvertTo<T>
where
T: FromData,
{
type Item = T;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let data = try_ready!(self.read_all.poll().map_err(Error::critical));
with_get_current(|input| T::from_data(data, input)).map(Async::Ready)
}
}
pub trait FromData: Sized {
fn from_data(data: Bytes, input: &mut Input) -> Result<Self, Error>;
}
impl FromData for String {
fn from_data(data: Bytes, input: &mut Input) -> Result<Self, Error> {
if let Some(m) = content_type(input)? {
if *m != mime::TEXT_PLAIN {
return Err(Error::bad_request(format_err!("the content type must be text/plain")));
}
if m.get_param("charset").map_or(true, |charset| charset != "utf-8") {
return Err(Error::bad_request(format_err!("the charset must be utf-8")));
}
}
String::from_utf8(data.to_vec()).map_err(Error::bad_request)
}
}