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
use std::{collections::HashMap, fs, path::Path, sync::Arc, time::SystemTime};

use rocket::{
    http::ContentType,
    tokio::{fs::File, io::AsyncWriteExt},
    Data,
};

use crate::{
    mime, multer::Multipart, FileField, MultipartFormDataError, MultipartFormDataOptions,
    MultipartFormDataType, RawField, TextField,
};

/// Parsed multipart/form-data.
#[derive(Debug)]
pub struct MultipartFormData {
    pub files: HashMap<Arc<str>, Vec<FileField>>,
    pub raw:   HashMap<Arc<str>, Vec<RawField>>,
    pub texts: HashMap<Arc<str>, Vec<TextField>>,
}

impl MultipartFormData {
    /// Parse multipart/form-data from the HTTP body.
    pub async fn parse(
        content_type: &ContentType,
        data: Data<'_>,
        mut options: MultipartFormDataOptions<'_>,
    ) -> Result<MultipartFormData, MultipartFormDataError> {
        if !content_type.is_form_data() {
            return Err(MultipartFormDataError::NotFormDataError);
        }

        let (_, boundary) = match content_type.params().find(|&(k, _)| k == "boundary") {
            Some(s) => s,
            None => return Err(MultipartFormDataError::BoundaryNotFoundError),
        };

        options.allowed_fields.sort_by_key(|e| e.field_name);

        let stream = data.open(options.max_data_bytes.into());

        let mut multipart = Multipart::new(tokio_util::io::ReaderStream::new(stream), boundary);

        let mut files: HashMap<Arc<str>, Vec<FileField>> = HashMap::new();
        let mut raw: HashMap<Arc<str>, Vec<RawField>> = HashMap::new();
        let mut texts: HashMap<Arc<str>, Vec<TextField>> = HashMap::new();

        let mut output_err: Option<MultipartFormDataError> = None;

        'outer: while let Some(mut entry) = multipart.next_field().await? {
            let field_name = match entry.name() {
                Some(name) => Arc::from(name),
                None => continue,
            };

            if let Ok(vi) =
                options.allowed_fields.binary_search_by(|f| f.field_name.cmp(&field_name))
            {
                // To deal with the weird behavior of web browsers
                // If the client wants to upload an empty file, it should not set the filename to empty string.
                let mut might_be_empty_file_input_in_html = false;

                {
                    let field_ref = &options.allowed_fields[vi];

                    // The HTTP request body of an empty file input in a HTML form sent by web browsers:
                    // Content-Disposition: form-data; name="???"; filename=""
                    // Content-Type: application/octet-stream
                    if let Some(filename) = entry.file_name() {
                        if filename.is_empty() {
                            // No need to check the MIME type. It's not practical.
                            might_be_empty_file_input_in_html = true;
                        }
                    }

                    // Whether to check content type
                    if let Some(content_type_ref) = &field_ref.content_type {
                        let mut mat = false; // Is the content type matching?

                        if let Some(content_type) = entry.content_type().as_ref() {
                            let top = content_type.type_();
                            let sub = content_type.subtype();

                            for content_type_ref in content_type_ref {
                                let top_ref = content_type_ref.type_();

                                if top_ref != mime::STAR && top_ref != top {
                                    continue;
                                }

                                let sub_ref = content_type_ref.subtype();

                                if sub_ref != mime::STAR && sub_ref != sub {
                                    continue;
                                }

                                mat = true;
                                break;
                            }
                        }

                        if !mat {
                            if might_be_empty_file_input_in_html {
                                // Reserve the disciplinary action
                                output_err =
                                    Some(MultipartFormDataError::DataTypeError(field_name.clone()));
                            } else {
                                output_err =
                                    Some(MultipartFormDataError::DataTypeError(field_name));
                                break 'outer;
                            }
                        }

                        // The content type has been checked
                    }
                }

                let drop_field = {
                    let field = unsafe { options.allowed_fields.get_unchecked_mut(vi) };

                    match field.typ {
                        MultipartFormDataType::File => {
                            let target_file_name = format!(
                                "rs-{}",
                                SystemTime::now()
                                    .duration_since(SystemTime::UNIX_EPOCH)
                                    .unwrap()
                                    .as_nanos()
                            );

                            let target_path = {
                                let mut p = Path::join(&options.temporary_dir, &target_file_name);

                                let mut i = 1usize;

                                while p.exists() {
                                    p = Path::join(
                                        &options.temporary_dir,
                                        format!("{}-{}", &target_file_name, i),
                                    );

                                    i += 1;
                                }

                                p
                            };

                            let mut file = match File::create(&target_path).await {
                                Ok(f) => f,
                                Err(err) => {
                                    output_err = Some(err.into());

                                    break 'outer;
                                },
                            };

                            let mut sum_c = 0u64;

                            loop {
                                match entry.chunk().await {
                                    Ok(bytes) => match bytes {
                                        Some(bytes) => {
                                            sum_c += bytes.len() as u64;

                                            if sum_c > field.size_limit {
                                                try_delete(&target_path);

                                                output_err = Some(
                                                    MultipartFormDataError::DataTooLargeError(
                                                        field_name,
                                                    ),
                                                );

                                                break 'outer;
                                            }

                                            match file.write_all(bytes.as_ref()).await {
                                                Ok(_) => (),
                                                Err(err) => {
                                                    try_delete(&target_path);

                                                    output_err = Some(err.into());

                                                    break 'outer;
                                                },
                                            }
                                        },
                                        None => break,
                                    },
                                    Err(err) => {
                                        try_delete(&target_path);

                                        output_err = Some(err.into());

                                        break 'outer;
                                    },
                                }
                            }

                            if might_be_empty_file_input_in_html {
                                if sum_c == 0 {
                                    // This file might be from an empty file input in the HTML form, so ignore it.
                                    try_delete(&target_path);

                                    output_err = None;
                                    continue;
                                } else if output_err.is_some() {
                                    try_delete(&target_path);

                                    break 'outer;
                                }
                            }

                            let file_name = entry.file_name().map(String::from);

                            let f = FileField {
                                content_type: entry.content_type().cloned(),
                                file_name,
                                path: target_path,
                            };

                            if let Some(fields) = files.get_mut(&field_name) {
                                fields.push(f);
                            } else {
                                files.insert(field_name, vec![f]);
                            }
                        },
                        MultipartFormDataType::Raw => {
                            let mut raw_buffer = Vec::new();

                            loop {
                                match entry.chunk().await {
                                    Ok(bytes) => match bytes {
                                        Some(bytes) => {
                                            if raw_buffer.len() as u64 + bytes.len() as u64
                                                > field.size_limit
                                            {
                                                output_err = Some(
                                                    MultipartFormDataError::DataTooLargeError(
                                                        field_name,
                                                    ),
                                                );

                                                break 'outer;
                                            }

                                            raw_buffer.extend_from_slice(bytes.as_ref());
                                        },
                                        None => break,
                                    },
                                    Err(err) => {
                                        output_err = Some(err.into());

                                        break 'outer;
                                    },
                                }
                            }

                            if might_be_empty_file_input_in_html {
                                if raw_buffer.is_empty() {
                                    // This file might be from an empty file input in the HTML form, so ignore it.
                                    output_err = None;
                                    continue;
                                } else if output_err.is_some() {
                                    break 'outer;
                                }
                            }

                            let file_name = entry.file_name().map(String::from);

                            let f = RawField {
                                content_type: entry.content_type().cloned(),
                                file_name,
                                raw: raw_buffer,
                            };

                            if let Some(fields) = raw.get_mut(&field_name) {
                                fields.push(f);
                            } else {
                                raw.insert(field_name, vec![f]);
                            }
                        },
                        MultipartFormDataType::Text => {
                            let mut text_buffer = Vec::new();

                            loop {
                                match entry.chunk().await {
                                    Ok(bytes) => match bytes {
                                        Some(bytes) => {
                                            if text_buffer.len() as u64 + bytes.len() as u64
                                                > field.size_limit
                                            {
                                                output_err = Some(
                                                    MultipartFormDataError::DataTooLargeError(
                                                        field_name,
                                                    ),
                                                );

                                                break 'outer;
                                            }

                                            text_buffer.extend_from_slice(bytes.as_ref());
                                        },
                                        None => break,
                                    },
                                    Err(err) => {
                                        output_err = Some(err.into());

                                        break 'outer;
                                    },
                                }
                            }

                            if might_be_empty_file_input_in_html {
                                if text_buffer.is_empty() {
                                    // This file might be from an empty file input in the HTML form, so ignore it.
                                    output_err = None;
                                    continue;
                                } else if output_err.is_some() {
                                    break 'outer;
                                }
                            }

                            let text = match String::from_utf8(text_buffer) {
                                Ok(s) => s,
                                Err(err) => {
                                    output_err = Some(err.into());

                                    break 'outer;
                                },
                            };

                            let file_name = entry.file_name().map(String::from);

                            let f = TextField {
                                content_type: entry.content_type().cloned(),
                                file_name,
                                text,
                            };

                            if let Some(fields) = texts.get_mut(&field_name) {
                                fields.push(f);
                            } else {
                                texts.insert(field_name, vec![f]);
                            }
                        },
                    }

                    field.repetition.decrease_check_is_over()
                };

                if drop_field {
                    options.allowed_fields.remove(vi);
                }
            }
        }

        if let Some(err) = output_err {
            for (_, fields) in files {
                for f in fields {
                    try_delete(f.path);
                }
            }

            loop {
                if multipart.next_field().await?.is_none() {
                    break;
                }
            }

            Err(err)
        } else {
            Ok(MultipartFormData {
                files,
                raw,
                texts,
            })
        }
    }
}

impl Drop for MultipartFormData {
    #[inline]
    fn drop(&mut self) {
        let files = &self.files;

        for fields in files.values() {
            for f in fields {
                try_delete(&f.path);
            }
        }
    }
}

#[inline]
fn try_delete<P: AsRef<Path>>(path: P) {
    if fs::remove_file(path.as_ref()).is_err() {}
}