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
use bytes::{Bytes, BytesMut};
use futures::{Async, Stream};
use http::header::{HeaderMap, HeaderName, HeaderValue};
use std::str;
use crate::Error;
pub const DEFAULT_BUFFER_CAP: usize = 35000;
pub trait Multipart<T>
where
Self: Sized,
T: Sized,
{
fn into_multipart_with_capacity(self, buf_cap: usize) -> Result<MultipartChunks<T>, Error>;
fn into_multipart(self) -> Result<MultipartChunks<T>, Error> {
self.into_multipart_with_capacity(DEFAULT_BUFFER_CAP)
}
}
impl Multipart<hyper::Body> for hyper::Response<hyper::Body> {
fn into_multipart_with_capacity(
self,
buf_cap: usize,
) -> Result<MultipartChunks<hyper::Body>, Error> {
let (parts, body) = self.into_parts();
let header = parts
.headers
.get(http::header::CONTENT_TYPE)
.ok_or(Error::ContentTypeMissing)
.and_then(|header_value| header_value.to_str().map_err(Error::InvalidHeader))
.and_then(|s| s.parse::<mime::Mime>().map_err(Error::InvalidMimeType))?;
let boundary = header.get_param("boundary").ok_or(Error::NotMultipart)?;
Ok(MultipartChunks::new(
body,
buf_cap,
format!("\r\n--{}\r\n", boundary.as_str()),
))
}
}
impl Multipart<hyper::Body> for hyper::Request<hyper::Body> {
fn into_multipart_with_capacity(
self,
buf_cap: usize,
) -> Result<MultipartChunks<hyper::Body>, Error> {
let (parts, body) = self.into_parts();
let header = parts
.headers
.get(http::header::CONTENT_TYPE)
.ok_or(Error::ContentTypeMissing)
.and_then(|header_value| header_value.to_str().map_err(Error::InvalidHeader))
.and_then(|s| s.parse::<mime::Mime>().map_err(Error::InvalidMimeType))?;
let boundary = header.get_param("boundary").ok_or(Error::NotMultipart)?;
Ok(MultipartChunks::new(
body,
buf_cap,
format!("\r\n--{}\r\n", boundary.as_str()),
))
}
}
pub struct MultipartChunks<T> {
inner: T,
first_read: bool,
buffer: BytesMut,
boundary: String,
}
impl<T> MultipartChunks<T> {
fn new(inner: T, buf_cap: usize, boundary: String) -> Self {
Self {
inner,
boundary,
first_read: false,
buffer: BytesMut::with_capacity(buf_cap),
}
}
}
impl Stream for MultipartChunks<hyper::Body> {
type Item = Part;
type Error = Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
match self.inner.poll() {
Ok(Async::Ready(Some(chunk))) => {
self.buffer.extend(chunk.into_bytes());
let boundary = self.boundary.as_bytes();
match twoway::find_bytes(&self.buffer[..], boundary) {
Some(i) => {
let part_bs = if self.first_read {
self.buffer.split_to(i).freeze()
} else {
let n_shave = self.boundary.len() - 2;
self.buffer.advance(n_shave);
self.first_read = true;
self.buffer.split_to(i - n_shave).freeze()
};
self.buffer.split_to(self.boundary.as_bytes().len());
Ok(Async::Ready(Some(Part::from(part_bs))))
}
None => self.poll(),
}
}
Ok(Async::NotReady) => {
Ok(Async::NotReady)
}
Ok(Async::Ready(None)) => {
Ok(Async::Ready(None))
}
Err(e) => {
Err(Error::Http(e))
}
}
}
}
pub struct Part {
headers_data: Bytes,
pub body_data: Bytes,
}
impl Part {
pub fn body(&self) -> &[u8] {
&self.body_data
}
pub fn into_body(self) -> Bytes {
self.body_data
}
pub fn body_len(&self) -> usize {
self.body_data.len()
}
pub fn header_lines(&self) -> impl Iterator<Item = Result<&str, str::Utf8Error>> {
let slice = &self.headers_data;
slice.split(|e| *e == b'\n').map(|line| {
str::from_utf8(line).map(|s| s.trim())
})
}
pub fn headers(&self) -> HeaderMap<HeaderValue> {
let mut res = HeaderMap::new();
self.header_lines()
.filter_map(|line| line.ok())
.map(|s| parse_header_line(s))
.for_each(|tuple| match tuple {
Some((name, value)) => {
res.insert(name, value);
}
_ => (),
});
res
}
}
fn parse_header_line(s: &str) -> Option<(HeaderName, HeaderValue)> {
if let None = s.find(":") {
return None;
}
let mut parts = s.split(":");
let header_name = parts
.next()
.map(|s| HeaderName::from_bytes(s.trim().as_bytes()));
let header_value = parts.next().map(|s| HeaderValue::from_str(s.trim()));
match (header_name, header_value) {
(Some(Ok(name)), Some(Ok(value))) => Some((name, value)),
_ => None,
}
}
#[test]
fn test_parse_header_lines() {
let tests = [
("Content-Type: image/jpeg", "content-type", "image/jpeg"),
("Content-Length: 40669", "content-length", "40669"),
(
"X-Timestamp: 1550567095.266",
"x-timestamp",
"1550567095.266",
),
(
"X-SendTimestamp: 1550567095.439",
"x-sendtimestamp",
"1550567095.439",
),
("X-TimeDiff: 173", "x-timediff", "173"),
];
for (header, exp_name, exp_val) in &tests {
let (name, val) = parse_header_line(header).expect("Parse header line");
assert_eq!(exp_name, &name.as_str());
assert_eq!(
exp_val,
&val.to_str().expect("Converting header value to_str")
);
}
}
impl From<Bytes> for Part {
fn from(mut bs: Bytes) -> Self {
match twoway::find_bytes(&bs[..], b"\r\n\r\n") {
None => Part {
headers_data: Bytes::with_capacity(0),
body_data: bs,
},
Some(p) => {
let headers = bs.split_to(p);
bs.advance(4);
Part {
headers_data: headers,
body_data: bs,
}
}
}
}
}