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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
extern crate buf_redux;
extern crate httparse;
extern crate safemem;
extern crate twoway;
use tempdir::TempDir;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fs;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::{io, mem};
use self::boundary::BoundaryReader;
use self::field::FieldHeaders;
pub use self::field::{MultipartField, MultipartFile, MultipartData, SavedFile};
macro_rules! try_opt (
($expr:expr) => (
match $expr {
Some(val) => val,
None => return None,
}
);
($expr:expr, $before_ret:expr) => (
match $expr {
Some(val) => val,
None => {
$before_ret;
return None;
}
}
)
);
mod boundary;
mod field;
#[cfg(feature = "hyper")]
pub mod hyper;
#[cfg(feature = "iron")]
pub mod iron;
#[cfg(feature = "nickel")]
pub mod nickel;
#[cfg(feature = "tiny_http")]
pub mod tiny_http;
pub struct Multipart<B> {
source: BoundaryReader<B>,
line_buf: String,
}
impl Multipart<()> {
pub fn from_request<R: HttpRequest>(req: R) -> Result<Multipart<R::Body>, R> {
let boundary = match req.multipart_boundary().map(String::from) {
Some(boundary) => boundary,
None => return Err(req),
};
Ok(Multipart::with_body(req.body(), boundary))
}
}
impl<B: Read> Multipart<B> {
pub fn with_body<Bnd: Into<String>>(body: B, boundary: Bnd) -> Self {
Multipart {
source: BoundaryReader::from_reader(body, boundary.into()),
line_buf: String::new(),
}
}
pub fn read_entry(&mut self) -> io::Result<Option<MultipartField<B>>> {
if try!(self.consume_boundary()) {
return Ok(None);
}
self::field::read_field(self)
}
fn read_field_headers(&mut self) -> io::Result<Option<FieldHeaders>> {
FieldHeaders::parse(&mut self.source)
}
pub fn foreach_entry<F>(&mut self, mut foreach: F) -> io::Result<()> where F: FnMut(MultipartField<B>) {
loop {
match self.read_entry() {
Ok(Some(field)) => foreach(field),
Ok(None) => return Ok(()),
Err(err) => return Err(err),
}
}
}
pub fn save_all(&mut self) -> SaveResult {
let mut entries = match Entries::new_tempdir() {
Ok(entries) => entries,
Err(err) => return SaveResult::Error(err),
};
match self.read_to_entries(&mut entries, None) {
Ok(()) => SaveResult::Full(entries),
Err(err) => SaveResult::Partial(entries, err),
}
}
pub fn save_all_under<P: AsRef<Path>>(&mut self, dir: P) -> SaveResult {
let mut entries = match Entries::new_tempdir_in(dir) {
Ok(entries) => entries,
Err(err) => return SaveResult::Error(err),
};
match self.read_to_entries(&mut entries, None) {
Ok(()) => SaveResult::Full(entries),
Err(err) => SaveResult::Partial(entries, err),
}
}
pub fn save_all_limited(&mut self, limit: u64) -> SaveResult {
let mut entries = match Entries::new_tempdir() {
Ok(entries) => entries,
Err(err) => return SaveResult::Error(err),
};
match self.read_to_entries(&mut entries, Some(limit)) {
Ok(()) => SaveResult::Full(entries),
Err(err) => SaveResult::Partial(entries, err),
}
}
pub fn save_all_under_limited<P: AsRef<Path>>(&mut self, dir: P, limit: u64) -> SaveResult {
let mut entries = match Entries::new_tempdir_in(dir) {
Ok(entries) => entries,
Err(err) => return SaveResult::Error(err),
};
match self.read_to_entries(&mut entries, Some(limit)) {
Ok(()) => SaveResult::Full(entries),
Err(err) => SaveResult::Partial(entries, err),
}
}
fn read_to_entries(&mut self, entries: &mut Entries, limit: Option<u64>) -> io::Result<()> {
while let Some(field) = try!(self.read_entry()) {
match field.data {
MultipartData::File(mut file) => {
let file = if let Some(limit) = limit {
try!(file.save_in_limited(&entries.dir, limit))
} else {
try!(file.save_in(&entries.dir))
};
entries.files.insert(field.name, file);
},
MultipartData::Text(text) => {
entries.fields.insert(field.name, text.into());
},
}
}
Ok(())
}
fn read_to_string(&mut self) -> io::Result<&str> {
self.line_buf.clear();
match self.source.read_to_string(&mut self.line_buf) {
Ok(read) => Ok(&self.line_buf[..read]),
Err(err) => Err(err),
}
}
fn consume_boundary(&mut self) -> io::Result<bool> {
debug!("Consume boundary!");
self.source.consume_boundary()
}
}
impl<B> Borrow<B> for Multipart<B> {
fn borrow(&self) -> &B {
self.source.borrow()
}
}
#[derive(Debug)]
pub enum SaveResult {
Full(Entries),
Partial(Entries, io::Error),
Error(io::Error),
}
impl SaveResult {
pub fn to_entries(self) -> Option<Entries> {
use self::SaveResult::*;
match self {
Full(entries) | Partial(entries, _) => Some(entries),
Error(_) => None,
}
}
pub fn to_opt(self) -> (Option<Entries>, Option<io::Error>) {
use self::SaveResult::*;
match self {
Full(entries) => (Some(entries), None),
Partial(entries, error) => (Some(entries), Some(error)),
Error(error) => (None, Some(error)),
}
}
pub fn to_result(self) -> io::Result<Entries> {
use self::SaveResult::*;
match self {
Full(entries) | Partial(entries, _) => Ok(entries),
Error(error) => Err(error),
}
}
}
pub trait HttpRequest {
type Body: Read;
fn multipart_boundary(&self) -> Option<&str>;
fn body(self) -> Self::Body;
}
#[derive(Debug)]
pub struct Entries {
pub fields: HashMap<String, String>,
pub files: HashMap<String, SavedFile>,
pub dir: SaveDir,
}
impl Entries {
fn new_tempdir_in<P: AsRef<Path>>(path: P) -> io::Result<Self> {
TempDir::new_in(path, "multipart").map(Self::with_tempdir)
}
fn new_tempdir() -> io::Result<Self> {
TempDir::new("multipart").map(Self::with_tempdir)
}
fn with_tempdir(tempdir: TempDir) -> Entries {
Entries {
fields: HashMap::new(),
files: HashMap::new(),
dir: SaveDir::Temp(tempdir),
}
}
}
#[derive(Debug)]
pub enum SaveDir {
Temp(TempDir),
Perm(PathBuf),
}
impl SaveDir {
pub fn as_path(&self) -> &Path {
use self::SaveDir::*;
match *self {
Temp(ref tempdir) => tempdir.path(),
Perm(ref pathbuf) => &*pathbuf,
}
}
pub fn is_temporary(&self) -> bool {
use self::SaveDir::*;
match *self {
Temp(_) => true,
Perm(_) => false,
}
}
pub fn into_path(self) -> PathBuf {
use self::SaveDir::*;
match self {
Temp(tempdir) => tempdir.into_path(),
Perm(pathbuf) => pathbuf,
}
}
pub fn keep(&mut self) {
use self::SaveDir::*;
*self = match mem::replace(self, Perm(PathBuf::new())) {
Temp(tempdir) => Perm(tempdir.into_path()),
old_self => old_self,
};
}
pub fn delete(self) -> io::Result<()> {
use self::SaveDir::*;
match self {
Temp(tempdir) => tempdir.close(),
Perm(pathbuf) => fs::remove_dir_all(&pathbuf),
}
}
}
impl AsRef<Path> for SaveDir {
fn as_ref(&self) -> &Path {
self.as_path()
}
}