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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use super::httparse::{self, EMPTY_HEADER, Status};
use super::{Multipart, ReadEntryResult};
use mime::{Attr, Mime, Value};
use std::borrow::BorrowMut;
use std::io::{self, Read, BufRead, Write};
use std::fs::{self, File};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::{mem, str};
const RANDOM_FILENAME_LEN: usize = 12;
macro_rules! try_io(
($try:expr) => (
{
use std::io::{Error, ErrorKind};
match $try {
Ok(val) => val,
Err(e) => return Err(Error::new(ErrorKind::InvalidData, e)),
}
}
)
);
macro_rules! assert_log_ret_none (
($expr, $else_:expr) => (
if !$expr {
$else_;
return None;
}
)
);
const EMPTY_STR_HEADER: StrHeader<'static> = StrHeader {
name: "",
val: "",
};
#[derive(Copy, Clone, Debug)]
struct StrHeader<'a> {
name: &'a str,
val: &'a str,
}
struct FieldHeaders {
cont_disp: ContentDisp,
cont_type: Option<ContentType>,
}
impl FieldHeaders {
fn read_from<R: BufRead>(r: &mut R) -> io::Result<Option<Self>> {
const HEADER_LEN: usize = 4;
let consume;
let header_len;
let mut headers = [EMPTY_STR_HEADER; HEADER_LEN];
{
let mut raw_headers = [EMPTY_HEADER; HEADER_LEN];
loop {
let buf = try!(r.fill_buf());
match try_io!(httparse::parse_headers(buf, &mut raw_headers)) {
Status::Complete((consume_, raw_headers)) => {
consume = consume_;
header_len = raw_headers.len();
break;
},
Status::Partial => (),
}
}
for (raw, header) in raw_headers.iter().take(header_len).zip(&mut headers) {
header.name = raw.name;
header.val = try!(io_str_utf8(raw.value));
}
}
let headers = &headers[..header_len];
debug!("Parsed field headers: {:?}", headers);
r.consume(consume);
Ok(Self::parse(headers))
}
fn parse(headers: &[StrHeader]) -> Option<FieldHeaders> {
let cont_disp = try_opt!(
ContentDisp::parse(headers),
debug!("Failed to read Content-Disposition")
);
let cont_type = ContentType::parse(headers);
Some(FieldHeaders {
cont_disp: cont_disp,
cont_type: cont_type,
})
}
}
struct ContentDisp {
field_name: String,
filename: Option<String>,
}
impl ContentDisp {
fn parse(headers: &[StrHeader]) -> Option<ContentDisp> {
if headers.is_empty() {
return None;
}
const CONT_DISP: &'static str = "Content-Disposition";
let header = try_opt!(
find_header(headers, CONT_DISP),
error!("Field headers did not contain Content-Disposition header (required)")
);
const NAME: &'static str = "name=";
const FILENAME: &'static str = "filename=";
let after_disp_type = {
let (disp_type, after_disp_type) = try_opt!(
split_once(header.val, ';'),
error!("Expected additional data after Content-Disposition type, got {:?}",
header.val)
);
if disp_type.trim() != "form-data" {
error!("Unexpected Content-Disposition value: {:?}", disp_type);
return None;
};
after_disp_type
};
let (field_name, after_field_name) = try_opt!(
get_str_after(NAME, ';', after_disp_type),
error!("Expected field name and maybe filename, got {:?}", after_disp_type)
);
let field_name = trim_quotes(field_name);
let filename = get_str_after(FILENAME, ';', after_field_name)
.map(|(filename, _)| trim_quotes(filename).to_owned());
Some(ContentDisp { field_name: field_name.to_owned(), filename: filename })
}
}
struct ContentType {
val: Mime,
}
impl ContentType {
fn parse(headers: &[StrHeader]) -> Option<ContentType> {
const CONTENT_TYPE: &'static str = "Content-Type";
let header = try_opt!(
find_header(headers, CONTENT_TYPE),
debug!("Content-Type header not found for field.")
);
debug!("Found Content-Type: {:?}", header.val);
let content_type = read_content_type(header.val.trim());
Some(ContentType { val: content_type })
}
#[allow(dead_code)]
pub fn boundary(&self) -> Option<&str> {
self.val.get_param(Attr::Boundary).map(Value::as_str)
}
}
#[derive(Debug)]
pub struct MultipartField<M> {
pub name: String,
pub data: MultipartData<M>,
}
impl<M: ReadField> MultipartField<M> {
pub fn next_entry(self) -> ReadEntryResult<M> {
self.data.into_inner().read_field()
}
pub fn next_entry_inplace(&mut self) -> io::Result<Option<&mut Self>> where for<'a> &'a mut M: ReadField {
let entry = match try!(self.read_entry()) {
Some(pair) => pair,
None => return Ok(None),
};
let multipart = mem::replace(&mut self.data, MultipartData::_Swapping).into_inner();
*self = entry.set_inner(multipart);
Ok(Some(self))
}
fn read_entry(&mut self) -> io::Result<Option<MultipartField<()>>> where for<'a> &'a mut M: ReadField {
self.data.inner_mut().read_field()
.map_err(|e| e.error)
.map(|entry| entry.map(|entry| entry.set_inner(())))
}
}
impl<M> MultipartField<M> {
fn set_inner<M_>(self, new_inner: M_) -> MultipartField<M_> {
MultipartField {
name: self.name,
data: self.data.set_inner(new_inner).1
}
}
}
pub fn read_field<R: Read, M: BorrowMut<Multipart<R>>>(mut multipart: M) -> ReadEntryResult<M> {
let field_headers = match try_read_entry!(multipart; FieldHeaders::read_from(&mut multipart.borrow_mut().reader)) {
Some(headers) => headers,
None => return Ok(None),
};
let data = match field_headers.cont_type {
Some(content_type) => {
MultipartData::File(
MultipartFile::from_stream(
field_headers.cont_disp.filename,
content_type.val,
multipart,
)
)
},
None => {
let text = try_read_entry!(multipart; multipart.borrow_mut().read_to_string());
MultipartData::Text(MultipartText {
text: text,
multipart: multipart,
})
},
};
Ok(Some(
MultipartField {
name: field_headers.cont_disp.field_name,
data: data,
}
))
}
#[derive(Debug)]
pub enum MultipartData<M> {
Text(MultipartText<M>),
File(MultipartFile<M>),
#[doc(hidden)]
_Swapping,
}
impl<M> MultipartData<M> {
pub fn into_inner(self) -> M {
use self::MultipartData::*;
match self {
Text(text) => text.multipart,
File(file) => file.multipart,
_Swapping => unreachable!("MultipartData::_Swapping was left in-place somehow"),
}
}
fn inner_mut(&mut self) -> &mut M {
use self::MultipartData::*;
match *self {
Text(ref mut text) => &mut text.multipart,
File(ref mut file) => &mut file.multipart,
_Swapping => unreachable!("MultipartData::_Swapping was left in-place somehow"),
}
}
fn set_inner<M_>(self, new_inner: M_) -> (M, MultipartData<M_>) {
use self::MultipartData::*;
match self {
Text(text) => (text.multipart, Text(MultipartText { text: text.text, multipart: new_inner })),
File(file) => (file.multipart, File(MultipartFile {
filename: file.filename,
content_type: file.content_type,
multipart: new_inner
})),
_Swapping => unreachable!("MultipartData::_Swapping was left in-place somehow"),
}
}
pub fn as_text(&self) -> Option<&str> {
match *self {
MultipartData::Text(ref text) => Some(&text.text),
_ => None,
}
}
pub fn as_file(&mut self) -> Option<&mut MultipartFile<M>> {
match *self {
MultipartData::File(ref mut file) => Some(file),
_ => None,
}
}
}
#[derive(Debug)]
pub struct MultipartText<M> {
pub text: String,
pub multipart: M,
}
impl<M> Deref for MultipartText<M> {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.text
}
}
impl<M> Into<String> for MultipartText<M> {
fn into(self) -> String {
self.text
}
}
#[derive(Debug)]
pub struct MultipartFile<M> {
filename: Option<String>,
content_type: Mime,
pub multipart: M,
}
impl<M> MultipartFile<M> {
fn from_stream(filename: Option<String>,
content_type: Mime,
multipart: M) -> MultipartFile<M> {
MultipartFile {
filename: filename,
content_type: content_type,
multipart: multipart,
}
}
pub fn filename(&self) -> Option<&str> {
self.filename.as_ref().map(String::as_ref)
}
pub fn content_type(&self) -> &Mime {
&self.content_type
}
}
impl<M> MultipartFile<M> where MultipartFile<M>: Read {
pub fn save_to<W: Write>(&mut self, mut out: W) -> io::Result<u64> {
retry_on_interrupt(|| io::copy(self, &mut out))
}
pub fn save_to_limited<W: Write>(&mut self, mut out: W, limit: u64) -> io::Result<u64> {
retry_on_interrupt(|| io::copy(&mut self.by_ref().take(limit), &mut out))
}
pub fn save_as<P: Into<PathBuf>>(&mut self, path: P) -> io::Result<SavedFile> {
let path = path.into();
let file = try!(create_full_path(&path));
let size = try!(self.save_to(file));
Ok(SavedFile {
path: path,
filename: self.filename.clone(),
size: size,
})
}
pub fn save_in<P: AsRef<Path>>(&mut self, dir: P) -> io::Result<SavedFile> {
let path = dir.as_ref().join(::random_alphanumeric(RANDOM_FILENAME_LEN));
self.save_as(path)
}
pub fn save_as_limited<P: Into<PathBuf>>(&mut self, path: P, limit: u64) -> io::Result<SavedFile> {
let path = path.into();
let file = try!(create_full_path(&path));
let size = try!(self.save_to_limited(file, limit));
Ok(SavedFile {
path: path,
filename: self.filename.clone(),
size: size,
})
}
pub fn save_in_limited<P: AsRef<Path>>(&mut self, dir: P, limit: u64) -> io::Result<SavedFile> {
let path = dir.as_ref().join(::random_alphanumeric(RANDOM_FILENAME_LEN));
self.save_as_limited(path, limit)
}
}
impl<R: Read> Read for MultipartFile<Multipart<R>> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>{
self.multipart.reader.read(buf)
}
}
impl<R: Read> BufRead for MultipartFile<Multipart<R>> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
self.multipart.reader.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.multipart.reader.consume(amt)
}
}
impl<'a, R: Read + 'a> Read for MultipartFile<&'a mut Multipart<R>> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>{
self.multipart.reader.read(buf)
}
}
impl<'a, R: Read + 'a> BufRead for MultipartFile<&'a mut Multipart<R>> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
self.multipart.reader.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.multipart.borrow_mut().reader.consume(amt)
}
}
#[derive(Debug)]
pub struct SavedFile {
pub path: PathBuf,
pub filename: Option<String>,
pub size: u64,
}
fn read_content_type(cont_type: &str) -> Mime {
cont_type.parse().ok().unwrap_or_else(::mime_guess::octet_stream)
}
fn split_once(s: &str, delim: char) -> Option<(&str, &str)> {
s.find(delim).map(|idx| s.split_at(idx))
}
fn trim_quotes(s: &str) -> &str {
s.trim_matches('"')
}
fn get_str_after<'a>(needle: &str, end_val_delim: char, haystack: &'a str) -> Option<(&'a str, &'a str)> {
let val_start_idx = try_opt!(haystack.find(needle)) + needle.len();
let val_end_idx = haystack[val_start_idx..].find(end_val_delim)
.map_or(haystack.len(), |end_idx| end_idx + val_start_idx);
Some((&haystack[val_start_idx..val_end_idx], &haystack[val_end_idx..]))
}
fn io_str_utf8(buf: &[u8]) -> io::Result<&str> {
str::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
fn find_header<'a, 'b>(headers: &'a [StrHeader<'b>], name: &str) -> Option<&'a StrHeader<'b>> {
headers.iter().find(|header| header.name == name)
}
fn retry_on_interrupt<F, T>(mut do_fn: F) -> io::Result<T> where F: FnMut() -> io::Result<T> {
loop {
match do_fn() {
Ok(val) => return Ok(val),
Err(err) => if err.kind() != io::ErrorKind::Interrupted {
return Err(err);
},
}
}
}
fn create_full_path(path: &Path) -> io::Result<File> {
if let Some(parent) = path.parent() {
try!(fs::create_dir_all(parent));
} else {
warn!("Attempting to save file in what looks like a root directory. File path: {:?}", path);
}
File::create(&path)
}
pub trait ReadField: Sized {
fn read_field(self) -> ReadEntryResult<Self>;
}
impl<R: Read> ReadField for Multipart<R> {
fn read_field(self) -> ReadEntryResult<Self> {
read_field(self)
}
}
impl<'a, R: Read + 'a> ReadField for &'a mut Multipart<R> {
fn read_field(self) -> ReadEntryResult<Self> {
read_field(self)
}
}