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
extern crate httparse;
extern crate hyper;
#[macro_use]
extern crate mime;
extern crate tempdir;
extern crate textnonce;
#[macro_use]
extern crate log;
extern crate encoding;
extern crate buf_read_ext;
pub mod error;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub use error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::PathBuf;
use std::borrow::Cow;
use std::ops::Drop;
use encoding::{all, Encoding, DecoderTrap};
use hyper::header::{ContentType, Headers, ContentDisposition, DispositionParam,
DispositionType, Charset};
use tempdir::TempDir;
use textnonce::TextNonce;
use mime::{Attr, Mime, TopLevel, Value};
use buf_read_ext::BufReadExt;
#[derive(Clone, Debug, PartialEq)]
pub struct Part {
headers: Headers,
body: Vec<u8>,
}
impl Part {
pub fn content_type(&self) -> Option<Mime> {
let ct: Option<&ContentType> = self.headers.get();
ct.map(|ref ct| ct.0.clone())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FilePart {
pub headers: Headers,
pub path: PathBuf,
pub size: usize,
tempdir: PathBuf,
}
impl FilePart {
pub fn new(headers: Headers) -> Result<FilePart, Error> {
let tempdir = try!(TempDir::new("mime_multipart")).into_path();
let mut path = tempdir.clone();
path.push(TextNonce::sized_urlsafe(32).unwrap().into_string());
Ok(FilePart {
path: path,
size: 0,
headers: headers,
tempdir: tempdir,
})
}
pub fn filename(&self) -> Result<Option<String>, Error> {
let cd: Option<&ContentDisposition> = self.headers.get();
match cd {
Some(cd) => get_content_disposition_filename(cd),
None => Ok(None),
}
}
pub fn content_type(&self) -> Option<Mime> {
let ct: Option<&ContentType> = self.headers.get();
ct.map(|ref ct| ct.0.clone())
}
}
impl Drop for FilePart {
fn drop(&mut self) {
let _ = ::std::fs::remove_file(&self.path);
let _ = ::std::fs::remove_dir(&self.tempdir);
}
}
#[derive(Clone, Debug)]
pub enum Node {
Part(Part),
File(FilePart),
Multipart((Headers, Vec<Node>)),
}
pub fn parse_multipart<S: Read>(
stream: &mut S,
headers: &Headers,
always_use_files: bool)
-> Result<Vec<Node>, Error>
{
let mut reader = BufReader::with_capacity(4096, stream);
let mut nodes: Vec<Node> = Vec::new();
try!(inner(&mut reader, headers, &mut nodes, always_use_files));
Ok(nodes)
}
fn inner<R: BufRead>(
reader: &mut R,
headers: &Headers,
nodes: &mut Vec<Node>,
always_use_files: bool)
-> Result<(), Error>
{
let mut buf: Vec<u8> = Vec::new();
let boundary = try!(get_multipart_boundary(headers));
let crlf_boundary = prepend_crlf(&boundary);
let (_, found) = try!(reader.stream_until_token(&boundary, &mut buf));
if ! found { return Err(Error::Eof); }
loop {
{
let peeker = try!(reader.fill_buf());
if peeker.len() >= 2 && &peeker[..2] == b"--" {
return Ok(());
}
}
let (_, found) = try!(reader.stream_until_token(b"\r\n", &mut buf));
if ! found { return Err(Error::Eof); }
buf.truncate(0);
let (_, found) = try!(reader.stream_until_token(b"\r\n\r\n", &mut buf));
if ! found { return Err(Error::Eof); }
buf.extend(b"\r\n\r\n".iter().cloned());
let mut header_memory = [httparse::EMPTY_HEADER; 4];
let part_headers = try!(match httparse::parse_headers(&buf, &mut header_memory) {
Ok(httparse::Status::Complete((_, raw_headers))) => {
Headers::from_raw(raw_headers).map_err(|e| From::from(e))
},
Ok(httparse::Status::Partial) => Err(Error::PartialHeaders),
Err(err) => Err(From::from(err)),
});
let nested = {
let ct: Option<&ContentType> = part_headers.get();
if let Some(ct) = ct {
let &ContentType(Mime(ref top_level, _, _)) = ct;
*top_level == TopLevel::Multipart
} else {
false
}
};
if nested {
let mut inner_nodes: Vec<Node> = Vec::new();
try!(inner(reader, &part_headers, &mut inner_nodes, always_use_files));
nodes.push(Node::Multipart((part_headers, inner_nodes)));
continue;
}
let is_file = always_use_files || {
let cd: Option<&ContentDisposition> = part_headers.get();
if cd.is_some() {
if cd.unwrap().disposition == DispositionType::Attachment {
true
} else {
cd.unwrap().parameters.iter().any(|x| match x {
&DispositionParam::Filename(_,_,_) => true,
_ => false
})
}
} else {
false
}
};
if is_file {
let mut filepart = try!(FilePart::new(part_headers));
let mut file = try!(File::create(filepart.path.clone()));
let (read, found) = try!(reader.stream_until_token(&crlf_boundary, &mut file));
if ! found { return Err(Error::Eof); }
filepart.size = read;
nodes.push(Node::File(filepart));
} else {
buf.truncate(0);
let (_, found) = try!(reader.stream_until_token(&crlf_boundary, &mut buf));
if ! found { return Err(Error::Eof); }
nodes.push(Node::Part(Part {
headers: part_headers,
body: buf.clone(),
}));
}
}
}
pub fn get_multipart_boundary(headers: &Headers) -> Result<Vec<u8>, Error> {
let ct: &ContentType = match headers.get() {
Some(ct) => ct,
None => return Err(Error::NoRequestContentType),
};
let ContentType(ref mime) = *ct;
let Mime(ref top_level, _, ref params) = *mime;
if *top_level != TopLevel::Multipart {
return Err(Error::NotMultipart);
}
for &(ref attr, ref val) in params.iter() {
if let (&Attr::Boundary, &Value::Ext(ref val)) = (attr, val) {
let mut boundary = Vec::with_capacity(2 + val.len());
boundary.extend(b"--".iter().cloned());
boundary.extend(val.as_bytes());
return Ok(boundary);
}
}
Err(Error::BoundaryNotSpecified)
}
fn prepend_crlf(input: &[u8]) -> Vec<u8> {
let mut output = Vec::with_capacity(2 + input.len());
output.extend(b"\r\n".iter().cloned());
output.extend(input.clone());
output
}
#[inline]
fn get_content_disposition_filename(cd: &ContentDisposition) -> Result<Option<String>, Error> {
if let Some(&DispositionParam::Filename(ref charset, _, ref bytes)) =
cd.parameters.iter().find(|&x| match *x {
DispositionParam::Filename(_,_,_) => true,
_ => false,
})
{
match charset_decode(charset, bytes) {
Ok(filename) => Ok(Some(filename)),
Err(e) => Err(Error::Decoding(e)),
}
} else {
Ok(None)
}
}
fn charset_decode(charset: &Charset, bytes: &[u8]) -> Result<String, Cow<'static, str>> {
Ok(match *charset {
Charset::Us_Ascii => try!(all::ASCII.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_1 => try!(all::ISO_8859_1.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_2 => try!(all::ISO_8859_2.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_3 => try!(all::ISO_8859_3.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_4 => try!(all::ISO_8859_4.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_5 => try!(all::ISO_8859_5.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_6 => try!(all::ISO_8859_6.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_7 => try!(all::ISO_8859_7.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_8 => try!(all::ISO_8859_8.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_8859_9 => return Err("ISO_8859_9 is not supported".into()),
Charset::Iso_8859_10 => try!(all::ISO_8859_10.decode(bytes, DecoderTrap::Strict)),
Charset::Shift_Jis => return Err("Shift_Jis is not supported".into()),
Charset::Euc_Jp => try!(all::EUC_JP.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_2022_Kr => return Err("Iso_2022_Kr is not supported".into()),
Charset::Euc_Kr => return Err("Euc_Kr is not supported".into()),
Charset::Iso_2022_Jp => try!(all::ISO_2022_JP.decode(bytes, DecoderTrap::Strict)),
Charset::Iso_2022_Jp_2 => return Err("Iso_2022_Jp_2 is not supported".into()),
Charset::Iso_8859_6_E => return Err("Iso_8859_6_E is not supported".into()),
Charset::Iso_8859_6_I => return Err("Iso_8859_6_I is not supported".into()),
Charset::Iso_8859_8_E => return Err("Iso_8859_8_E is not supported".into()),
Charset::Iso_8859_8_I => return Err("Iso_8859_8_I is not supported".into()),
Charset::Gb2312 => return Err("Gb2312 is not supported".into()),
Charset::Big5 => try!(all::BIG5_2003.decode(bytes, DecoderTrap::Strict)),
Charset::Koi8_R => try!(all::KOI8_R.decode(bytes, DecoderTrap::Strict)),
Charset::Ext(ref s) => match &**s {
"UTF-8" => try!(all::UTF_8.decode(bytes, DecoderTrap::Strict)),
_ => return Err("Encoding is not supported".into()),
},
})
}