ntex-files 3.2.0

Static files support for ntex web.
Documentation
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
// # References
//
// "The Content-Disposition Header Field" https://www.ietf.org/rfc/rfc2183.txt
// "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)" https://www.ietf.org/rfc/rfc6266.txt
// "Returning Values from Forms: multipart/form-data" https://www.ietf.org/rfc/rfc2388.txt
// Browser conformance tests at: http://greenbytes.de/tech/tc2231/
// IANA assignment: http://www.iana.org/assignments/cont-disp/cont-disp.xhtml

use super::error;
use super::parsing::{self, ExtendedValue};
use super::{Header, RawLike};
use crate::standard_header;
use regex::Regex;
use std::fmt;
use std::sync::LazyLock;

/// The implied disposition of the content of the HTTP body.
#[derive(Clone, Debug, PartialEq)]
pub enum DispositionType {
    /// Inline implies default processing
    Inline,

    /// Attachment implies that the recipient should prompt the user to save the response locally,
    /// rather than process it normally (as per its media type).
    Attachment,

    /// Used in *multipart/form-data* as defined in
    /// [RFC 7578](https://datatracker.ietf.org/doc/html/rfc7578) to carry the field name and
    /// optional filename.
    FormData,

    /// Extension type.  Should be handled by recipients the same way as Attachment
    Ext(String),
}

impl<'a> From<&'a str> for DispositionType {
    fn from(origin: &'a str) -> DispositionType {
        if unicase::eq_ascii(origin, "inline") {
            DispositionType::Inline
        } else if unicase::eq_ascii(origin, "attachment") {
            DispositionType::Attachment
        } else if unicase::eq_ascii(origin, "form-data") {
            DispositionType::FormData
        } else {
            DispositionType::Ext(origin.to_owned())
        }
    }
}

/// A parameter to the disposition type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DispositionParam {
    /// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
    /// the form.
    Name(String),

    /// A plain file name.
    ///
    /// It is [not supposed](https://datatracker.ietf.org/doc/html/rfc6266#appendix-D) to contain
    /// any non-ASCII characters when used in a *Content-Disposition* HTTP response header, where
    /// [`FilenameExt`](DispositionParam::FilenameExt) with charset UTF-8 may be used instead
    /// in case there are Unicode characters in file names.
    Filename(String),

    /// An extended file name. It must not exist for `ContentType::Formdata` according to
    /// [RFC 7578 §4.2](https://datatracker.ietf.org/doc/html/rfc7578#section-4.2).
    FilenameExt(ExtendedValue),

    /// An unrecognized regular parameter as defined in
    /// [RFC 5987 §3.2.1](https://datatracker.ietf.org/doc/html/rfc5987#section-3.2.1) as
    /// `reg-parameter`, in
    /// [RFC 6266 §4.1](https://datatracker.ietf.org/doc/html/rfc6266#section-4.1) as
    /// `token "=" value`. Recipients should ignore unrecognizable parameters.
    Unknown(String, String),

    /// An unrecognized extended parameter as defined in
    /// [RFC 5987 §3.2.1](https://datatracker.ietf.org/doc/html/rfc5987#section-3.2.1) as
    /// `ext-parameter`, in
    /// [RFC 6266 §4.1](https://datatracker.ietf.org/doc/html/rfc6266#section-4.1) as
    /// `ext-token "=" ext-value`. The single trailing asterisk is not included. Recipients should
    /// ignore unrecognizable parameters.
    UnknownExt(String, ExtendedValue),
}

impl DispositionParam {
    /// Returns `true` if the parameter is [`Name`](DispositionParam::Name).
    #[inline]
    pub fn is_name(&self) -> bool {
        self.as_name().is_some()
    }

    /// Returns `true` if the parameter is [`Filename`](DispositionParam::Filename).
    #[inline]
    pub fn is_filename(&self) -> bool {
        self.as_filename().is_some()
    }

    /// Returns `true` if the parameter is [`FilenameExt`](DispositionParam::FilenameExt).
    #[inline]
    pub fn is_filename_ext(&self) -> bool {
        self.as_filename_ext().is_some()
    }

    /// Returns `true` if the parameter is [`Unknown`](DispositionParam::Unknown) and the `name`
    #[inline]
    /// matches.
    pub fn is_unknown<T: AsRef<str>>(&self, name: T) -> bool {
        self.as_unknown(name).is_some()
    }

    /// Returns `true` if the parameter is [`UnknownExt`](DispositionParam::UnknownExt) and the
    /// `name` matches.
    #[inline]
    pub fn is_unknown_ext<T: AsRef<str>>(&self, name: T) -> bool {
        self.as_unknown_ext(name).is_some()
    }

    /// Returns the name if applicable.
    #[inline]
    pub fn as_name(&self) -> Option<&str> {
        match self {
            DispositionParam::Name(name) => Some(name.as_str()),
            _ => None,
        }
    }

    /// Returns the filename if applicable.
    #[inline]
    pub fn as_filename(&self) -> Option<&str> {
        match self {
            DispositionParam::Filename(filename) => Some(filename.as_str()),
            _ => None,
        }
    }

    /// Returns the filename* if applicable.
    #[inline]
    pub fn as_filename_ext(&self) -> Option<&ExtendedValue> {
        match self {
            DispositionParam::FilenameExt(value) => Some(value),
            _ => None,
        }
    }

    /// Returns the value of the unrecognized regular parameter if it is
    /// [`Unknown`](DispositionParam::Unknown) and the `name` matches.
    #[inline]
    pub fn as_unknown<T: AsRef<str>>(&self, name: T) -> Option<&str> {
        match self {
            DispositionParam::Unknown(ext_name, value)
                if ext_name.eq_ignore_ascii_case(name.as_ref()) =>
            {
                Some(value.as_str())
            }
            _ => None,
        }
    }

    /// Returns the value of the unrecognized extended parameter if it is
    /// [`Unknown`](DispositionParam::Unknown) and the `name` matches.
    #[inline]
    pub fn as_unknown_ext<T: AsRef<str>>(&self, name: T) -> Option<&ExtendedValue> {
        match self {
            DispositionParam::UnknownExt(ext_name, value)
                if ext_name.eq_ignore_ascii_case(name.as_ref()) =>
            {
                Some(value)
            }
            _ => None,
        }
    }
}

/// A `Content-Disposition` header, (re)defined in [RFC6266](https://tools.ietf.org/html/rfc6266).
///
/// The Content-Disposition response header field is used to convey
/// additional information about how to process the response payload, and
/// also can be used to attach additional metadata, such as the filename
/// to use when saving the response payload locally.
///
/// # ABNF
///
/// ```text
/// content-disposition = "Content-Disposition" ":"
///                       disposition-type *( ";" disposition-parm )
///
/// disposition-type    = "inline" | "attachment" | disp-ext-type
///                       ; case-insensitive
///
/// disp-ext-type       = token
///
/// disposition-parm    = filename-parm | disp-ext-parm
///
/// filename-parm       = "filename" "=" value
///                     | "filename*" "=" ext-value
///
/// disp-ext-parm       = token "=" value
///                     | ext-token "=" ext-value
///
/// ext-token           = <the characters in token, followed by "*">
/// ```
///
#[derive(Clone, Debug, PartialEq)]
pub struct ContentDisposition {
    /// The disposition
    pub disposition: DispositionType,
    /// Disposition parameters
    pub parameters: Vec<DispositionParam>,
}

impl ContentDisposition {
    /// Returns `true` if type is [`Inline`](DispositionType::Inline).
    pub fn is_inline(&self) -> bool {
        matches!(self.disposition, DispositionType::Inline)
    }

    /// Returns `true` if type is [`Attachment`](DispositionType::Attachment).
    pub fn is_attachment(&self) -> bool {
        matches!(self.disposition, DispositionType::Attachment)
    }

    /// Returns `true` if type is [`FormData`](DispositionType::FormData).
    pub fn is_form_data(&self) -> bool {
        matches!(self.disposition, DispositionType::FormData)
    }

    /// Returns `true` if type is [`Ext`](DispositionType::Ext) and the `disp_type` matches.
    pub fn is_ext(&self, disp_type: impl AsRef<str>) -> bool {
        matches!(
            self.disposition,
            DispositionType::Ext(ref t) if t.eq_ignore_ascii_case(disp_type.as_ref())
        )
    }

    /// Return the value of *name* if exists.
    pub fn get_name(&self) -> Option<&str> {
        self.parameters.iter().find_map(DispositionParam::as_name)
    }

    /// Return the value of *filename* if exists.
    pub fn get_filename(&self) -> Option<&str> {
        self.parameters.iter().find_map(DispositionParam::as_filename)
    }

    /// Return the value of *filename\** if exists.
    pub fn get_filename_ext(&self) -> Option<&ExtendedValue> {
        self.parameters.iter().find_map(DispositionParam::as_filename_ext)
    }

    /// Return the value of the parameter which the `name` matches.
    pub fn get_unknown(&self, name: impl AsRef<str>) -> Option<&str> {
        let name = name.as_ref();
        self.parameters.iter().find_map(|p| p.as_unknown(name))
    }

    /// Return the value of the extended parameter which the `name` matches.
    pub fn get_unknown_ext(&self, name: impl AsRef<str>) -> Option<&ExtendedValue> {
        let name = name.as_ref();
        self.parameters.iter().find_map(|p| p.as_unknown_ext(name))
    }
}

impl Header for ContentDisposition {
    fn header_name() -> &'static str {
        static NAME: &str = "Content-Disposition";
        NAME
    }

    fn parse_header<'a, T>(raw: &'a T) -> error::Result<ContentDisposition>
    where
        T: RawLike<'a>,
    {
        parsing::from_one_raw_str(raw).and_then(|s: String| {
            let mut sections = s.split(';');
            let disposition = match sections.next() {
                Some(s) => s.trim(),
                None => return Err(error::Error::Header),
            };

            let mut cd =
                ContentDisposition { disposition: disposition.into(), parameters: Vec::new() };

            for section in sections {
                let mut parts = section.splitn(2, '=');

                let key = if let Some(key) = parts.next() {
                    let key_trimmed = key.trim();

                    if key_trimmed.is_empty() || key_trimmed == "*" {
                        return Err(error::Error::Header);
                    }

                    key_trimmed
                } else {
                    return Err(error::Error::Header);
                };

                let val = if let Some(val) = parts.next() {
                    val.trim()
                } else {
                    return Err(error::Error::Header);
                };

                if let Some(key) = key.strip_suffix('*') {
                    let ext_val = parsing::parse_extended_value(val)?;

                    cd.parameters.push(if unicase::eq_ascii(key, "filename") {
                        DispositionParam::FilenameExt(ext_val)
                    } else {
                        DispositionParam::UnknownExt(key.to_owned(), ext_val)
                    });
                } else {
                    let val = if val.starts_with('\"') {
                        // quoted-string: defined in RFC 6266 -> RFC 2616 Section 3.6
                        let mut escaping = false;
                        let mut quoted_string = vec![];

                        // search for closing quote
                        for &c in val.as_bytes().iter().skip(1) {
                            if escaping {
                                escaping = false;
                                quoted_string.push(c);
                            } else if c == 0x5c {
                                // backslash
                                escaping = true;
                            } else if c == 0x22 {
                                // double quote
                                break;
                            } else {
                                quoted_string.push(c);
                            }
                        }

                        // In fact, it should not be Err if the above code is correct.
                        String::from_utf8(quoted_string).map_err(|_| error::Error::Header)?
                    } else {
                        if val.is_empty() {
                            // quoted-string can be empty, but token cannot be empty
                            return Err(error::Error::Header);
                        }

                        val.to_owned()
                    };

                    cd.parameters.push(if unicase::eq_ascii(key, "name") {
                        DispositionParam::Name(val)
                    } else if unicase::eq_ascii(key, "filename") {
                        // See also comments in test_from_raw_unnecessary_percent_decode.
                        DispositionParam::Filename(val)
                    } else {
                        DispositionParam::Unknown(key.to_owned(), val)
                    });
                }
            }

            Ok(cd)
        })
    }

    #[inline]
    fn fmt_header(&self, f: &mut super::Formatter) -> fmt::Result {
        f.fmt_line(self)
    }
}

impl fmt::Display for DispositionType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DispositionType::Inline => write!(f, "inline"),
            DispositionType::Attachment => write!(f, "attachment"),
            DispositionType::FormData => write!(f, "form-data"),
            DispositionType::Ext(s) => write!(f, "{}", s),
        }
    }
}

impl fmt::Display for DispositionParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // All ASCII control characters (0-30, 127) including horizontal tab, double quote, and
        // backslash should be escaped in quoted-string (i.e. "foobar").
        //
        // Ref: RFC 6266 §4.1 -> RFC 2616 §3.6
        //
        // filename-parm  = "filename" "=" value
        // value          = token | quoted-string
        // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
        // qdtext         = <any TEXT except <">>
        // quoted-pair    = "\" CHAR
        // TEXT           = <any OCTET except CTLs,
        //                  but including LWS>
        // LWS            = [CRLF] 1*( SP | HT )
        // OCTET          = <any 8-bit sequence of data>
        // CHAR           = <any US-ASCII character (octets 0 - 127)>
        // CTL            = <any US-ASCII control character
        //                  (octets 0 - 31) and DEL (127)>
        //
        // Ref: RFC 7578 S4.2 -> RFC 2183 S2 -> RFC 2045 S5.1
        // parameter := attribute "=" value
        // attribute := token
        //              ; Matching of attributes
        //              ; is ALWAYS case-insensitive.
        // value := token / quoted-string
        // token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
        //             or tspecials>
        // tspecials :=  "(" / ")" / "<" / ">" / "@" /
        //               "," / ";" / ":" / "\" / <">
        //               "/" / "[" / "]" / "?" / "="
        //               ; Must be in quoted-string,
        //               ; to use within parameter values
        //
        //
        // See also comments in test_from_raw_unnecessary_percent_decode.

        static RE: LazyLock<Regex> =
            LazyLock::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap());

        match self {
            DispositionParam::Name(value) => write!(f, "name={}", value),

            DispositionParam::Filename(value) => {
                write!(f, "filename=\"{}\"", RE.replace_all(value, "\\$0").as_ref())
            }

            DispositionParam::Unknown(name, value) => {
                write!(f, "{}=\"{}\"", name, &RE.replace_all(value, "\\$0").as_ref())
            }

            DispositionParam::FilenameExt(ext_value) => {
                write!(f, "filename*={}", ext_value)
            }

            DispositionParam::UnknownExt(name, ext_value) => {
                write!(f, "{}*={}", name, ext_value)
            }
        }
    }
}

impl fmt::Display for ContentDisposition {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.disposition)?;

        for param in &self.parameters {
            write!(f, "; {}", param)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{ContentDisposition, DispositionParam, DispositionType, Header};
    use crate::header::parsing::ExtendedValue;
    use crate::header::{Charset, Raw};

    #[test]
    fn test_parse_header() {
        let a: Raw = "".into();
        assert!(ContentDisposition::parse_header(&a).is_err());

        let a: Raw = "form-data; dummy=3; name=upload;\r\n filename=\"sample.png\"".into();
        let a: ContentDisposition = ContentDisposition::parse_header(&a).unwrap();
        let b = ContentDisposition {
            disposition: DispositionType::FormData,
            parameters: vec![
                DispositionParam::Unknown("dummy".to_owned(), "3".to_owned()),
                DispositionParam::Name("upload".to_owned()),
                DispositionParam::Filename("sample.png".to_owned()),
            ],
        };
        assert_eq!(a, b);

        let a: Raw = "attachment; filename=\"image.jpg\"".into();
        let a: ContentDisposition = ContentDisposition::parse_header(&a).unwrap();
        let b = ContentDisposition {
            disposition: DispositionType::Attachment,
            parameters: vec![DispositionParam::Filename("image.jpg".to_owned())],
        };
        assert_eq!(a, b);

        let a: Raw = "attachment; filename*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates".into();
        let a: ContentDisposition = ContentDisposition::parse_header(&a).unwrap();
        let b = ContentDisposition {
            disposition: DispositionType::Attachment,
            parameters: vec![DispositionParam::FilenameExt(ExtendedValue {
                charset: Charset::Ext(String::from("UTF-8")),
                language_tag: None,
                value: vec![
                    0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r',
                    b'a', b't', b'e', b's',
                ],
            })],
        };
        assert_eq!(a, b);
    }

    #[test]
    fn test_display() {
        let as_string = "attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
        let a: Raw = as_string.into();
        let a: ContentDisposition = ContentDisposition::parse_header(&a).unwrap();
        let display_rendered = format!("{}", a);
        assert_eq!(as_string, display_rendered);

        // TODO Fix this test
        // let a: Raw = "attachment; filename*=UTF-8''black%20and%20white.csv".into();
        // let a: ContentDisposition = ContentDisposition::parse_header(&a).unwrap();
        // let display_rendered = format!("{}", a);
        // assert_eq!("attachment; filename=\"black and white.csv\"".to_owned(), display_rendered);

        let a: Raw = "attachment; filename=colourful.csv".into();
        let a: ContentDisposition = ContentDisposition::parse_header(&a).unwrap();
        let display_rendered = format!("{}", a);
        assert_eq!("attachment; filename=\"colourful.csv\"".to_owned(), display_rendered);
    }
}

standard_header!(ContentDisposition, CONTENT_DISPOSITION);