Skip to main content

actix_web/http/header/
content_disposition.rs

1//! The `Content-Disposition` header and associated types.
2//!
3//! # References
4//! - "The Content-Disposition Header Field":
5//!   <https://www.rfc-editor.org/info/rfc2183>
6//! - "The Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)":
7//!   <https://www.rfc-editor.org/info/rfc6266>
8//! - "Returning Values from Forms: multipart/form-data":
9//!   <https://www.rfc-editor.org/info/rfc7578>
10//! - Browser conformance tests at: <http://greenbytes.de/tech/tc2231/>
11//! - IANA assignment: <http://www.iana.org/assignments/cont-disp/cont-disp.xhtml>
12
13use std::fmt::{self, Write};
14
15use once_cell::sync::Lazy;
16#[cfg(feature = "unicode")]
17use regex::Regex;
18#[cfg(not(feature = "unicode"))]
19use regex_lite::Regex;
20
21use super::{ExtendedValue, Header, TryIntoHeaderValue, Writer};
22use crate::http::header;
23
24/// Split at the index of the first `needle` if it exists or at the end.
25fn split_once(haystack: &str, needle: char) -> (&str, &str) {
26    haystack.find(needle).map_or_else(
27        || (haystack, ""),
28        |sc| {
29            let (first, last) = haystack.split_at(sc);
30            (first, last.split_at(1).1)
31        },
32    )
33}
34
35/// Split at the index of the first `needle` if it exists or at the end, trim the right of the
36/// first part and the left of the last part.
37fn split_once_and_trim(haystack: &str, needle: char) -> (&str, &str) {
38    let (first, last) = split_once(haystack, needle);
39    (first.trim_end(), last.trim_start())
40}
41
42/// The implied disposition of the content of the HTTP body.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum DispositionType {
45    /// Inline implies default processing.
46    Inline,
47
48    /// Attachment implies that the recipient should prompt the user to save the response locally,
49    /// rather than process it normally (as per its media type).
50    Attachment,
51
52    /// Used in *multipart/form-data* as defined in
53    /// [RFC 7578](https://www.rfc-editor.org/info/rfc7578) to carry the field name and
54    /// optional filename.
55    FormData,
56
57    /// Extension type. Should be handled by recipients the same way as Attachment.
58    Ext(String),
59}
60
61impl_more::impl_display_enum! {
62    DispositionType:
63    Inline => "inline",
64    Attachment => "attachment",
65    FormData => "form-data",
66    Ext(s) => "{s}",
67}
68
69impl<'a> From<&'a str> for DispositionType {
70    fn from(origin: &'a str) -> DispositionType {
71        if origin.eq_ignore_ascii_case("inline") {
72            DispositionType::Inline
73        } else if origin.eq_ignore_ascii_case("attachment") {
74            DispositionType::Attachment
75        } else if origin.eq_ignore_ascii_case("form-data") {
76            DispositionType::FormData
77        } else {
78            DispositionType::Ext(origin.to_owned())
79        }
80    }
81}
82
83/// Parameter in [`ContentDisposition`].
84///
85/// # Examples
86/// ```
87/// use actix_web::http::header::DispositionParam;
88///
89/// let param = DispositionParam::Filename(String::from("sample.txt"));
90/// assert!(param.is_filename());
91/// assert_eq!(param.as_filename().unwrap(), "sample.txt");
92/// ```
93#[derive(Debug, Clone, PartialEq, Eq)]
94#[allow(clippy::large_enum_variant)]
95pub enum DispositionParam {
96    /// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
97    /// the form.
98    Name(String),
99
100    /// A plain file name.
101    ///
102    /// It is [not supposed](https://www.rfc-editor.org/info/rfc6266/#appendix-D) to contain
103    /// any non-ASCII characters when used in a *Content-Disposition* HTTP response header, where
104    /// [`FilenameExt`](DispositionParam::FilenameExt) with charset UTF-8 may be used instead
105    /// in case there are Unicode characters in file names.
106    Filename(String),
107
108    /// An extended file name. It must not exist for `ContentType::Formdata` according to
109    /// [RFC 7578 §4.2](https://www.rfc-editor.org/info/rfc7578/#section-4.2).
110    FilenameExt(ExtendedValue),
111
112    /// An unrecognized regular parameter as defined in
113    /// [RFC 5987 §3.2.1](https://www.rfc-editor.org/info/rfc5987/#section-3.2.1) as
114    /// `reg-parameter`, in
115    /// [RFC 6266 §4.1](https://www.rfc-editor.org/info/rfc6266/#section-4.1) as
116    /// `token "=" value`. Recipients should ignore unrecognizable parameters.
117    Unknown(String, String),
118
119    /// An unrecognized extended parameter as defined in
120    /// [RFC 5987 §3.2.1](https://www.rfc-editor.org/info/rfc5987/#section-3.2.1) as
121    /// `ext-parameter`, in
122    /// [RFC 6266 §4.1](https://www.rfc-editor.org/info/rfc6266/#section-4.1) as
123    /// `ext-token "=" ext-value`. The single trailing asterisk is not included. Recipients should
124    /// ignore unrecognizable parameters.
125    UnknownExt(String, ExtendedValue),
126}
127
128impl DispositionParam {
129    /// Returns `true` if the parameter is [`Name`](DispositionParam::Name).
130    #[inline]
131    pub fn is_name(&self) -> bool {
132        self.as_name().is_some()
133    }
134
135    /// Returns `true` if the parameter is [`Filename`](DispositionParam::Filename).
136    #[inline]
137    pub fn is_filename(&self) -> bool {
138        self.as_filename().is_some()
139    }
140
141    /// Returns `true` if the parameter is [`FilenameExt`](DispositionParam::FilenameExt).
142    #[inline]
143    pub fn is_filename_ext(&self) -> bool {
144        self.as_filename_ext().is_some()
145    }
146
147    /// Returns `true` if the parameter is [`Unknown`](DispositionParam::Unknown) and the `name`
148    #[inline]
149    /// matches.
150    pub fn is_unknown<T: AsRef<str>>(&self, name: T) -> bool {
151        self.as_unknown(name).is_some()
152    }
153
154    /// Returns `true` if the parameter is [`UnknownExt`](DispositionParam::UnknownExt) and the
155    /// `name` matches.
156    #[inline]
157    pub fn is_unknown_ext<T: AsRef<str>>(&self, name: T) -> bool {
158        self.as_unknown_ext(name).is_some()
159    }
160
161    /// Returns the name if applicable.
162    #[inline]
163    pub fn as_name(&self) -> Option<&str> {
164        match self {
165            DispositionParam::Name(name) => Some(name.as_str()),
166            _ => None,
167        }
168    }
169
170    /// Returns the filename if applicable.
171    #[inline]
172    pub fn as_filename(&self) -> Option<&str> {
173        match self {
174            DispositionParam::Filename(filename) => Some(filename.as_str()),
175            _ => None,
176        }
177    }
178
179    /// Returns the filename* if applicable.
180    #[inline]
181    pub fn as_filename_ext(&self) -> Option<&ExtendedValue> {
182        match self {
183            DispositionParam::FilenameExt(value) => Some(value),
184            _ => None,
185        }
186    }
187
188    /// Returns the value of the unrecognized regular parameter if it is
189    /// [`Unknown`](DispositionParam::Unknown) and the `name` matches.
190    #[inline]
191    pub fn as_unknown<T: AsRef<str>>(&self, name: T) -> Option<&str> {
192        match self {
193            DispositionParam::Unknown(ref ext_name, ref value)
194                if ext_name.eq_ignore_ascii_case(name.as_ref()) =>
195            {
196                Some(value.as_str())
197            }
198            _ => None,
199        }
200    }
201
202    /// Returns the value of the unrecognized extended parameter if it is
203    /// [`Unknown`](DispositionParam::Unknown) and the `name` matches.
204    #[inline]
205    pub fn as_unknown_ext<T: AsRef<str>>(&self, name: T) -> Option<&ExtendedValue> {
206        match self {
207            DispositionParam::UnknownExt(ref ext_name, ref value)
208                if ext_name.eq_ignore_ascii_case(name.as_ref()) =>
209            {
210                Some(value)
211            }
212            _ => None,
213        }
214    }
215}
216
217/// `Content-Disposition` header.
218///
219/// It is compatible to be used either as [a response header for the main body][use_main_body]
220/// as (re)defined in [RFC 6266], or as [a header for a multipart body][use_multipart] as
221/// (re)defined in [RFC 7578].
222///
223/// In a regular HTTP response, the *Content-Disposition* response header is a header indicating if
224/// the content is expected to be displayed *inline* in the browser, that is, as a Web page or as
225/// part of a Web page, or as an attachment, that is downloaded and saved locally, and also can be
226/// used to attach additional metadata, such as the filename to use when saving the response payload
227/// locally.
228///
229/// In a *multipart/form-data* body, the HTTP *Content-Disposition* general header is a header that
230/// can be used on the subpart of a multipart body to give information about the field it applies to.
231/// The subpart is delimited by the boundary defined in the *Content-Type* header. Used on the body
232/// itself, *Content-Disposition* has no effect.
233///
234/// # ABNF
235/// ```plain
236/// content-disposition = "Content-Disposition" ":"
237///                       disposition-type *( ";" disposition-parm )
238///
239/// disposition-type    = "inline" | "attachment" | disp-ext-type
240///                       ; case-insensitive
241///
242/// disp-ext-type       = token
243///
244/// disposition-parm    = filename-parm | disp-ext-parm
245///
246/// filename-parm       = "filename" "=" value
247///                     | "filename*" "=" ext-value
248///
249/// disp-ext-parm       = token "=" value
250///                     | ext-token "=" ext-value
251///
252/// ext-token           = <the characters in token, followed by "*">
253/// ```
254///
255/// # Note
256/// *filename* is [not supposed](https://www.rfc-editor.org/info/rfc6266/#appendix-D) to
257/// contain any non-ASCII characters when used in a *Content-Disposition* HTTP response header,
258/// where filename* with charset UTF-8 may be used instead in case there are Unicode characters in
259/// file names. Filename is [acceptable](https://www.rfc-editor.org/info/rfc7578/#section-4.2)
260/// to be UTF-8 encoded directly in a *Content-Disposition* header for
261/// *multipart/form-data*, though.
262///
263/// `filename*` [must not](https://www.rfc-editor.org/info/rfc7578/#section-4.2) be used within
264/// *multipart/form-data*.
265///
266/// # Examples
267/// ```
268/// use actix_web::http::header::{
269///     Charset, ContentDisposition, DispositionParam, DispositionType,
270///     ExtendedValue,
271/// };
272///
273/// let cd1 = ContentDisposition {
274///     disposition: DispositionType::Attachment,
275///     parameters: vec![DispositionParam::FilenameExt(ExtendedValue {
276///         charset: Charset::Iso_8859_1, // The character set for the bytes of the filename
277///         language_tag: None, // The optional language tag (see `language-tag` crate)
278///         value: b"\xA9 Ferris 2011.txt".to_vec(), // the actual bytes of the filename
279///     })],
280/// };
281/// assert!(cd1.is_attachment());
282/// assert!(cd1.get_filename_ext().is_some());
283///
284/// let cd2 = ContentDisposition {
285///     disposition: DispositionType::FormData,
286///     parameters: vec![
287///         DispositionParam::Name(String::from("file")),
288///         DispositionParam::Filename(String::from("bill.odt")),
289///     ],
290/// };
291/// assert_eq!(cd2.get_name(), Some("file")); // field name
292/// assert_eq!(cd2.get_filename(), Some("bill.odt"));
293///
294/// // HTTP response header with Unicode characters in file names
295/// let cd3 = ContentDisposition {
296///     disposition: DispositionType::Attachment,
297///     parameters: vec![
298///         DispositionParam::FilenameExt(ExtendedValue {
299///             charset: Charset::Ext(String::from("UTF-8")),
300///             language_tag: None,
301///             value: String::from("\u{1f600}.svg").into_bytes(),
302///         }),
303///         // fallback for better compatibility
304///         DispositionParam::Filename(String::from("Grinning-Face-Emoji.svg"))
305///     ],
306/// };
307/// assert_eq!(cd3.get_filename_ext().map(|ev| ev.value.as_ref()),
308///            Some("\u{1f600}.svg".as_bytes()));
309/// ```
310///
311/// # Security Note
312/// If "filename" parameter is supplied, do not use the file name blindly, check and possibly
313/// change to match local file system conventions if applicable, and do not use directory path
314/// information that may be present.
315/// See [RFC 2183 §2.3](https://www.rfc-editor.org/info/rfc2183/#section-2.3).
316///
317/// [use_main_body]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_response_header_for_the_main_body
318/// [RFC 6266]: https://www.rfc-editor.org/info/rfc6266
319/// [use_multipart]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_header_for_a_multipart_body
320/// [RFC 7578]: https://www.rfc-editor.org/info/rfc7578
321#[derive(Debug, Clone, PartialEq, Eq)]
322pub struct ContentDisposition {
323    /// The disposition type
324    pub disposition: DispositionType,
325
326    /// Disposition parameters
327    pub parameters: Vec<DispositionParam>,
328}
329
330impl ContentDisposition {
331    /// Constructs a Content-Disposition header suitable for downloads.
332    ///
333    /// Includes a `filename` parameter and adds a UTF-8 encoded `filename*` parameter if the
334    /// filename contains non-ASCII characters.
335    ///
336    /// # Examples
337    /// ```
338    /// use actix_web::http::header::{ContentDisposition, TryIntoHeaderValue as _};
339    ///
340    /// let cd = ContentDisposition::attachment("files.zip");
341    ///
342    /// let cd_val = cd.try_into_value().unwrap();
343    /// assert_eq!(cd_val, "attachment; filename=\"files.zip\"");
344    /// ```
345    pub fn attachment(filename: impl Into<String>) -> Self {
346        let filename = filename.into();
347        let is_ascii = filename.is_ascii();
348
349        let mut parameters = Vec::new();
350
351        if is_ascii {
352            parameters.push(DispositionParam::Filename(filename));
353        } else {
354            parameters.push(DispositionParam::Filename(filename.clone()));
355            parameters.push(DispositionParam::FilenameExt(ExtendedValue {
356                charset: header::Charset::Ext(String::from("UTF-8")),
357                language_tag: None,
358                value: filename.into_bytes(),
359            }));
360        }
361
362        Self {
363            disposition: DispositionType::Attachment,
364            parameters,
365        }
366    }
367
368    /// Parse a raw Content-Disposition header value.
369    pub fn from_raw(hv: &header::HeaderValue) -> Result<Self, crate::error::ParseError> {
370        // `header::from_one_raw_str` invokes `hv.to_str` which assumes `hv` contains only visible
371        //  ASCII characters. So `hv.as_bytes` is necessary here.
372        let hv = String::from_utf8(hv.as_bytes().to_vec())
373            .map_err(|_| crate::error::ParseError::Header)?;
374
375        let (disp_type, mut left) = split_once_and_trim(hv.as_str().trim(), ';');
376        if disp_type.is_empty() {
377            return Err(crate::error::ParseError::Header);
378        }
379
380        let mut cd = ContentDisposition {
381            disposition: disp_type.into(),
382            parameters: Vec::new(),
383        };
384
385        while !left.is_empty() {
386            let (param_name, new_left) = split_once_and_trim(left, '=');
387            if param_name.is_empty() || param_name == "*" || new_left.is_empty() {
388                return Err(crate::error::ParseError::Header);
389            }
390            left = new_left;
391            if let Some(param_name) = param_name.strip_suffix('*') {
392                // extended parameters
393                let (ext_value, new_left) = split_once_and_trim(left, ';');
394                left = new_left;
395                let ext_value = header::parse_extended_value(ext_value)?;
396
397                let param = if param_name.eq_ignore_ascii_case("filename") {
398                    DispositionParam::FilenameExt(ext_value)
399                } else {
400                    DispositionParam::UnknownExt(param_name.to_owned(), ext_value)
401                };
402                cd.parameters.push(param);
403            } else {
404                // regular parameters
405                let value = if left.starts_with('\"') {
406                    // quoted-string: defined in RFC 6266 -> RFC 2616 Section 3.6
407                    let mut escaping = false;
408                    let mut quoted_string = vec![];
409                    let mut end = None;
410                    // search for closing quote
411                    for (i, &c) in left.as_bytes().iter().skip(1).enumerate() {
412                        if escaping {
413                            escaping = false;
414                            quoted_string.push(c);
415                        } else if c == 0x5c {
416                            // backslash
417                            escaping = true;
418                        } else if c == 0x22 {
419                            // double quote
420                            end = Some(i + 1); // cuz skipped 1 for the leading quote
421                            break;
422                        } else {
423                            quoted_string.push(c);
424                        }
425                    }
426                    left = &left[end.ok_or(crate::error::ParseError::Header)? + 1..];
427                    left = split_once(left, ';').1.trim_start();
428                    // In fact, it should not be Err if the above code is correct.
429                    String::from_utf8(quoted_string)
430                        .map_err(|_| crate::error::ParseError::Header)?
431                } else {
432                    // token: won't contains semicolon according to RFC 2616 Section 2.2
433                    let (token, new_left) = split_once_and_trim(left, ';');
434                    left = new_left;
435                    if token.is_empty() {
436                        // quoted-string can be empty, but token cannot be empty
437                        return Err(crate::error::ParseError::Header);
438                    }
439                    token.to_owned()
440                };
441
442                let param = if param_name.eq_ignore_ascii_case("name") {
443                    DispositionParam::Name(value)
444                } else if param_name.eq_ignore_ascii_case("filename") {
445                    // See also comments in test_from_raw_unnecessary_percent_decode.
446                    DispositionParam::Filename(value)
447                } else {
448                    DispositionParam::Unknown(param_name.to_owned(), value)
449                };
450                cd.parameters.push(param);
451            }
452        }
453
454        Ok(cd)
455    }
456
457    /// Returns `true` if type is [`Inline`](DispositionType::Inline).
458    pub fn is_inline(&self) -> bool {
459        matches!(self.disposition, DispositionType::Inline)
460    }
461
462    /// Returns `true` if type is [`Attachment`](DispositionType::Attachment).
463    pub fn is_attachment(&self) -> bool {
464        matches!(self.disposition, DispositionType::Attachment)
465    }
466
467    /// Returns `true` if type is [`FormData`](DispositionType::FormData).
468    pub fn is_form_data(&self) -> bool {
469        matches!(self.disposition, DispositionType::FormData)
470    }
471
472    /// Returns `true` if type is [`Ext`](DispositionType::Ext) and the `disp_type` matches.
473    pub fn is_ext(&self, disp_type: impl AsRef<str>) -> bool {
474        matches!(
475            self.disposition,
476            DispositionType::Ext(ref t) if t.eq_ignore_ascii_case(disp_type.as_ref())
477        )
478    }
479
480    /// Return the value of *name* if exists.
481    pub fn get_name(&self) -> Option<&str> {
482        self.parameters.iter().find_map(DispositionParam::as_name)
483    }
484
485    /// Return the value of *filename* if exists.
486    pub fn get_filename(&self) -> Option<&str> {
487        self.parameters
488            .iter()
489            .find_map(DispositionParam::as_filename)
490    }
491
492    /// Return the value of *filename\** if exists.
493    pub fn get_filename_ext(&self) -> Option<&ExtendedValue> {
494        self.parameters
495            .iter()
496            .find_map(DispositionParam::as_filename_ext)
497    }
498
499    /// Return the value of the parameter which the `name` matches.
500    pub fn get_unknown(&self, name: impl AsRef<str>) -> Option<&str> {
501        let name = name.as_ref();
502        self.parameters.iter().find_map(|p| p.as_unknown(name))
503    }
504
505    /// Return the value of the extended parameter which the `name` matches.
506    pub fn get_unknown_ext(&self, name: impl AsRef<str>) -> Option<&ExtendedValue> {
507        let name = name.as_ref();
508        self.parameters.iter().find_map(|p| p.as_unknown_ext(name))
509    }
510}
511
512impl TryIntoHeaderValue for ContentDisposition {
513    type Error = header::InvalidHeaderValue;
514
515    fn try_into_value(self) -> Result<header::HeaderValue, Self::Error> {
516        let mut writer = Writer::new();
517        let _ = write!(&mut writer, "{}", self);
518        header::HeaderValue::from_maybe_shared(writer.take())
519    }
520}
521
522impl Header for ContentDisposition {
523    fn name() -> header::HeaderName {
524        header::CONTENT_DISPOSITION
525    }
526
527    fn parse<T: crate::HttpMessage>(msg: &T) -> Result<Self, crate::error::ParseError> {
528        if let Some(h) = msg.headers().get(Self::name()) {
529            Self::from_raw(h)
530        } else {
531            Err(crate::error::ParseError::Header)
532        }
533    }
534}
535
536impl fmt::Display for DispositionParam {
537    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538        // All ASCII control characters (0-30, 127) including horizontal tab, double quote, and
539        // backslash should be escaped in quoted-string (i.e. "foobar").
540        //
541        // Ref: RFC 6266 §4.1 -> RFC 2616 §3.6
542        //
543        // filename-parm  = "filename" "=" value
544        // value          = token | quoted-string
545        // quoted-string  = ( <"> *(qdtext | quoted-pair ) <"> )
546        // qdtext         = <any TEXT except <">>
547        // quoted-pair    = "\" CHAR
548        // TEXT           = <any OCTET except CTLs,
549        //                  but including LWS>
550        // LWS            = [CRLF] 1*( SP | HT )
551        // OCTET          = <any 8-bit sequence of data>
552        // CHAR           = <any US-ASCII character (octets 0 - 127)>
553        // CTL            = <any US-ASCII control character
554        //                  (octets 0 - 31) and DEL (127)>
555        //
556        // Ref: RFC 7578 S4.2 -> RFC 2183 S2 -> RFC 2045 S5.1
557        // parameter := attribute "=" value
558        // attribute := token
559        //              ; Matching of attributes
560        //              ; is ALWAYS case-insensitive.
561        // value := token / quoted-string
562        // token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
563        //             or tspecials>
564        // tspecials :=  "(" / ")" / "<" / ">" / "@" /
565        //               "," / ";" / ":" / "\" / <">
566        //               "/" / "[" / "]" / "?" / "="
567        //               ; Must be in quoted-string,
568        //               ; to use within parameter values
569        //
570        //
571        // See also comments in test_from_raw_unnecessary_percent_decode.
572
573        static RE: Lazy<Regex> =
574            Lazy::new(|| Regex::new("[\x00-\x08\x10-\x1F\x7F\"\\\\]").unwrap());
575
576        match self {
577            DispositionParam::Name(ref value) => write!(f, "name={}", value),
578
579            DispositionParam::Filename(ref value) => {
580                write!(f, "filename=\"{}\"", RE.replace_all(value, "\\$0").as_ref())
581            }
582
583            DispositionParam::Unknown(ref name, ref value) => {
584                write!(f, "{name}=\"{}\"", RE.replace_all(value, "\\$0").as_ref())
585            }
586
587            DispositionParam::FilenameExt(ref ext_value) => {
588                write!(f, "filename*={}", ext_value)
589            }
590
591            DispositionParam::UnknownExt(ref name, ref ext_value) => {
592                write!(f, "{}*={}", name, ext_value)
593            }
594        }
595    }
596}
597
598impl fmt::Display for ContentDisposition {
599    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600        write!(f, "{}", self.disposition)?;
601        self.parameters
602            .iter()
603            .try_for_each(|param| write!(f, "; {}", param))
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::{ContentDisposition, DispositionParam, DispositionType};
610    use crate::http::header::{Charset, ExtendedValue, HeaderValue, TryIntoHeaderValue as _};
611
612    #[test]
613    fn test_attachment_ascii() {
614        let header = ContentDisposition::attachment("file name.zip")
615            .try_into_value()
616            .unwrap();
617
618        assert_eq!(header, "attachment; filename=\"file name.zip\"");
619    }
620
621    #[test]
622    fn test_attachment_non_ascii() {
623        let header = ContentDisposition::attachment("café.pdf")
624            .try_into_value()
625            .unwrap();
626
627        assert_eq!(
628            header.as_bytes(),
629            "attachment; filename=\"café.pdf\"; filename*=UTF-8''caf%C3%A9.pdf".as_bytes()
630        );
631    }
632
633    #[test]
634    fn test_from_raw_basic() {
635        assert!(ContentDisposition::from_raw(&HeaderValue::from_static("")).is_err());
636
637        let a =
638            HeaderValue::from_static("form-data; dummy=3; name=upload; filename=\"sample.png\"");
639        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
640        let b = ContentDisposition {
641            disposition: DispositionType::FormData,
642            parameters: vec![
643                DispositionParam::Unknown("dummy".to_owned(), "3".to_owned()),
644                DispositionParam::Name("upload".to_owned()),
645                DispositionParam::Filename("sample.png".to_owned()),
646            ],
647        };
648        assert_eq!(a, b);
649
650        let a = HeaderValue::from_static("attachment; filename=\"image.jpg\"");
651        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
652        let b = ContentDisposition {
653            disposition: DispositionType::Attachment,
654            parameters: vec![DispositionParam::Filename("image.jpg".to_owned())],
655        };
656        assert_eq!(a, b);
657
658        let a = HeaderValue::from_static("inline; filename=image.jpg");
659        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
660        let b = ContentDisposition {
661            disposition: DispositionType::Inline,
662            parameters: vec![DispositionParam::Filename("image.jpg".to_owned())],
663        };
664        assert_eq!(a, b);
665
666        let a = HeaderValue::from_static(
667            "attachment; creation-date=\"Wed, 12 Feb 1997 16:29:51 -0500\"",
668        );
669        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
670        let b = ContentDisposition {
671            disposition: DispositionType::Attachment,
672            parameters: vec![DispositionParam::Unknown(
673                String::from("creation-date"),
674                "Wed, 12 Feb 1997 16:29:51 -0500".to_owned(),
675            )],
676        };
677        assert_eq!(a, b);
678    }
679
680    #[test]
681    fn test_from_raw_extended() {
682        let a = HeaderValue::from_static(
683            "attachment; filename*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates",
684        );
685        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
686        let b = ContentDisposition {
687            disposition: DispositionType::Attachment,
688            parameters: vec![DispositionParam::FilenameExt(ExtendedValue {
689                charset: Charset::Ext(String::from("UTF-8")),
690                language_tag: None,
691                value: vec![
692                    0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r', b'a',
693                    b't', b'e', b's',
694                ],
695            })],
696        };
697        assert_eq!(a, b);
698
699        let a = HeaderValue::from_static(
700            "attachment; filename*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates",
701        );
702        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
703        let b = ContentDisposition {
704            disposition: DispositionType::Attachment,
705            parameters: vec![DispositionParam::FilenameExt(ExtendedValue {
706                charset: Charset::Ext(String::from("UTF-8")),
707                language_tag: None,
708                value: vec![
709                    0xc2, 0xa3, 0x20, b'a', b'n', b'd', 0x20, 0xe2, 0x82, 0xac, 0x20, b'r', b'a',
710                    b't', b'e', b's',
711                ],
712            })],
713        };
714        assert_eq!(a, b);
715    }
716
717    #[test]
718    fn test_from_raw_extra_whitespace() {
719        let a = HeaderValue::from_static(
720            "form-data  ; du-mmy= 3  ; name =upload ; filename =  \"sample.png\"  ; ",
721        );
722        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
723        let b = ContentDisposition {
724            disposition: DispositionType::FormData,
725            parameters: vec![
726                DispositionParam::Unknown("du-mmy".to_owned(), "3".to_owned()),
727                DispositionParam::Name("upload".to_owned()),
728                DispositionParam::Filename("sample.png".to_owned()),
729            ],
730        };
731        assert_eq!(a, b);
732    }
733
734    #[test]
735    fn test_from_raw_unordered() {
736        let a = HeaderValue::from_static(
737            "form-data; dummy=3; filename=\"sample.png\" ; name=upload;",
738            // Actually, a trailing semicolon is not compliant. But it is fine to accept.
739        );
740        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
741        let b = ContentDisposition {
742            disposition: DispositionType::FormData,
743            parameters: vec![
744                DispositionParam::Unknown("dummy".to_owned(), "3".to_owned()),
745                DispositionParam::Filename("sample.png".to_owned()),
746                DispositionParam::Name("upload".to_owned()),
747            ],
748        };
749        assert_eq!(a, b);
750
751        let a = HeaderValue::from_str(
752            "attachment; filename*=iso-8859-1''foo-%E4.html; filename=\"foo-ä.html\"",
753        )
754        .unwrap();
755        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
756        let b = ContentDisposition {
757            disposition: DispositionType::Attachment,
758            parameters: vec![
759                DispositionParam::FilenameExt(ExtendedValue {
760                    charset: Charset::Iso_8859_1,
761                    language_tag: None,
762                    value: b"foo-\xe4.html".to_vec(),
763                }),
764                DispositionParam::Filename("foo-ä.html".to_owned()),
765            ],
766        };
767        assert_eq!(a, b);
768    }
769
770    #[test]
771    fn test_from_raw_only_disp() {
772        let a = ContentDisposition::from_raw(&HeaderValue::from_static("attachment")).unwrap();
773        let b = ContentDisposition {
774            disposition: DispositionType::Attachment,
775            parameters: vec![],
776        };
777        assert_eq!(a, b);
778
779        let a = ContentDisposition::from_raw(&HeaderValue::from_static("inline ;")).unwrap();
780        let b = ContentDisposition {
781            disposition: DispositionType::Inline,
782            parameters: vec![],
783        };
784        assert_eq!(a, b);
785
786        let a =
787            ContentDisposition::from_raw(&HeaderValue::from_static("unknown-disp-param")).unwrap();
788        let b = ContentDisposition {
789            disposition: DispositionType::Ext(String::from("unknown-disp-param")),
790            parameters: vec![],
791        };
792        assert_eq!(a, b);
793    }
794
795    #[test]
796    fn from_raw_with_mixed_case() {
797        let a = HeaderValue::from_str(
798            "InLInE; fIlenAME*=iso-8859-1''foo-%E4.html; filEName=\"foo-ä.html\"",
799        )
800        .unwrap();
801        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
802        let b = ContentDisposition {
803            disposition: DispositionType::Inline,
804            parameters: vec![
805                DispositionParam::FilenameExt(ExtendedValue {
806                    charset: Charset::Iso_8859_1,
807                    language_tag: None,
808                    value: b"foo-\xe4.html".to_vec(),
809                }),
810                DispositionParam::Filename("foo-ä.html".to_owned()),
811            ],
812        };
813        assert_eq!(a, b);
814    }
815
816    #[test]
817    fn from_raw_with_unicode() {
818        /* RFC 7578 Section 4.2:
819        Some commonly deployed systems use multipart/form-data with file names directly encoded
820        including octets outside the US-ASCII range. The encoding used for the file names is
821        typically UTF-8, although HTML forms will use the charset associated with the form.
822
823        Mainstream browsers like Firefox (gecko) and Chrome use UTF-8 directly as above.
824        (And now, only UTF-8 is handled by this implementation.)
825        */
826        let a = HeaderValue::from_str("form-data; name=upload; filename=\"文件.webp\"").unwrap();
827        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
828        let b = ContentDisposition {
829            disposition: DispositionType::FormData,
830            parameters: vec![
831                DispositionParam::Name(String::from("upload")),
832                DispositionParam::Filename(String::from("文件.webp")),
833            ],
834        };
835        assert_eq!(a, b);
836
837        let a = HeaderValue::from_str(
838            "form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"",
839        )
840        .unwrap();
841        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
842        let b = ContentDisposition {
843            disposition: DispositionType::FormData,
844            parameters: vec![
845                DispositionParam::Name(String::from("upload")),
846                DispositionParam::Filename(String::from("余固知謇謇之為患兮,忍而不能舍也.pptx")),
847            ],
848        };
849        assert_eq!(a, b);
850    }
851
852    #[test]
853    fn test_from_raw_escape() {
854        let a = HeaderValue::from_static(
855            "form-data; dummy=3; name=upload; filename=\"s\\amp\\\"le.png\"",
856        );
857        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
858        let b = ContentDisposition {
859            disposition: DispositionType::FormData,
860            parameters: vec![
861                DispositionParam::Unknown("dummy".to_owned(), "3".to_owned()),
862                DispositionParam::Name("upload".to_owned()),
863                DispositionParam::Filename(
864                    ['s', 'a', 'm', 'p', '\"', 'l', 'e', '.', 'p', 'n', 'g']
865                        .iter()
866                        .collect(),
867                ),
868            ],
869        };
870        assert_eq!(a, b);
871    }
872
873    #[test]
874    fn test_from_raw_semicolon() {
875        let a = HeaderValue::from_static("form-data; filename=\"A semicolon here;.pdf\"");
876        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
877        let b = ContentDisposition {
878            disposition: DispositionType::FormData,
879            parameters: vec![DispositionParam::Filename(String::from(
880                "A semicolon here;.pdf",
881            ))],
882        };
883        assert_eq!(a, b);
884    }
885
886    #[test]
887    fn test_from_raw_unnecessary_percent_decode() {
888        // In fact, RFC 7578 (multipart/form-data) Section 2 and 4.2 suggests that filename with
889        // non-ASCII characters MAY be percent-encoded.
890        // On the contrary, RFC 6266 or other RFCs related to Content-Disposition response header
891        // do not mention such percent-encoding.
892        // So, it appears to be undecidable whether to percent-decode or not without
893        // knowing the usage scenario (multipart/form-data v.s. HTTP response header) and
894        // inevitable to unnecessarily percent-decode filename with %XX in the former scenario.
895        // Fortunately, it seems that almost all mainstream browsers just send UTF-8 encoded file
896        // names in quoted-string format (tested on Edge, IE11, Chrome and Firefox) without
897        // percent-encoding. So we do not bother to attempt to percent-decode.
898        let a = HeaderValue::from_static(
899            "form-data; name=photo; filename=\"%74%65%73%74%2e%70%6e%67\"",
900        );
901        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
902        let b = ContentDisposition {
903            disposition: DispositionType::FormData,
904            parameters: vec![
905                DispositionParam::Name("photo".to_owned()),
906                DispositionParam::Filename(String::from("%74%65%73%74%2e%70%6e%67")),
907            ],
908        };
909        assert_eq!(a, b);
910
911        let a = HeaderValue::from_static("form-data; name=photo; filename=\"%74%65%73%74.png\"");
912        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
913        let b = ContentDisposition {
914            disposition: DispositionType::FormData,
915            parameters: vec![
916                DispositionParam::Name("photo".to_owned()),
917                DispositionParam::Filename(String::from("%74%65%73%74.png")),
918            ],
919        };
920        assert_eq!(a, b);
921    }
922
923    #[test]
924    fn test_from_raw_param_value_missing() {
925        let a = HeaderValue::from_static("form-data; name=upload ; filename=");
926        assert!(ContentDisposition::from_raw(&a).is_err());
927
928        let a = HeaderValue::from_static("attachment; dummy=; filename=invoice.pdf");
929        assert!(ContentDisposition::from_raw(&a).is_err());
930
931        let a = HeaderValue::from_static("inline; filename=  ");
932        assert!(ContentDisposition::from_raw(&a).is_err());
933
934        let a = HeaderValue::from_static("inline; filename=\"\"");
935        assert!(ContentDisposition::from_raw(&a)
936            .expect("Parse cd")
937            .get_filename()
938            .expect("Filename")
939            .is_empty());
940    }
941
942    #[test]
943    fn test_from_raw_param_name_missing() {
944        let a = HeaderValue::from_static("inline; =\"test.txt\"");
945        assert!(ContentDisposition::from_raw(&a).is_err());
946
947        let a = HeaderValue::from_static("inline; =diary.odt");
948        assert!(ContentDisposition::from_raw(&a).is_err());
949
950        let a = HeaderValue::from_static("inline; =");
951        assert!(ContentDisposition::from_raw(&a).is_err());
952    }
953
954    #[test]
955    fn test_display_extended() {
956        let as_string = "attachment; filename*=UTF-8'en'%C2%A3%20and%20%E2%82%AC%20rates";
957        let a = HeaderValue::from_static(as_string);
958        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
959        let display_rendered = format!("{}", a);
960        assert_eq!(as_string, display_rendered);
961
962        let a = HeaderValue::from_static("attachment; filename=colourful.csv");
963        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
964        let display_rendered = format!("{}", a);
965        assert_eq!(
966            "attachment; filename=\"colourful.csv\"".to_owned(),
967            display_rendered
968        );
969    }
970
971    #[test]
972    fn test_display_quote() {
973        let as_string = "form-data; name=upload; filename=\"Quote\\\"here.png\"";
974        as_string
975            .find(['\\', '\"'].iter().collect::<String>().as_str())
976            .unwrap(); // ensure `\"` is there
977        let a = HeaderValue::from_static(as_string);
978        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
979        let display_rendered = format!("{}", a);
980        assert_eq!(as_string, display_rendered);
981    }
982
983    #[test]
984    fn test_display_space_tab() {
985        let as_string = "form-data; name=upload; filename=\"Space here.png\"";
986        let a = HeaderValue::from_static(as_string);
987        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
988        let display_rendered = format!("{}", a);
989        assert_eq!(as_string, display_rendered);
990
991        let a: ContentDisposition = ContentDisposition {
992            disposition: DispositionType::Inline,
993            parameters: vec![DispositionParam::Filename(String::from("Tab\there.png"))],
994        };
995        let display_rendered = format!("{}", a);
996        assert_eq!("inline; filename=\"Tab\x09here.png\"", display_rendered);
997    }
998
999    #[test]
1000    fn test_display_control_characters() {
1001        /* let a = "attachment; filename=\"carriage\rreturn.png\"";
1002        let a = HeaderValue::from_static(a);
1003        let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
1004        let display_rendered = format!("{}", a);
1005        assert_eq!(
1006            "attachment; filename=\"carriage\\\rreturn.png\"",
1007            display_rendered
1008        );*/
1009        // No way to create a HeaderValue containing a carriage return.
1010
1011        let a: ContentDisposition = ContentDisposition {
1012            disposition: DispositionType::Inline,
1013            parameters: vec![DispositionParam::Filename(String::from("bell\x07.png"))],
1014        };
1015        let display_rendered = format!("{}", a);
1016        assert_eq!("inline; filename=\"bell\\\x07.png\"", display_rendered);
1017    }
1018
1019    #[test]
1020    fn test_param_methods() {
1021        let param = DispositionParam::Filename(String::from("sample.txt"));
1022        assert!(param.is_filename());
1023        assert_eq!(param.as_filename().unwrap(), "sample.txt");
1024
1025        let param = DispositionParam::Unknown(String::from("foo"), String::from("bar"));
1026        assert!(param.is_unknown("foo"));
1027        assert_eq!(param.as_unknown("fOo"), Some("bar"));
1028    }
1029
1030    #[test]
1031    fn test_disposition_methods() {
1032        let cd = ContentDisposition {
1033            disposition: DispositionType::FormData,
1034            parameters: vec![
1035                DispositionParam::Unknown("dummy".to_owned(), "3".to_owned()),
1036                DispositionParam::Name("upload".to_owned()),
1037                DispositionParam::Filename("sample.png".to_owned()),
1038            ],
1039        };
1040        assert_eq!(cd.get_name(), Some("upload"));
1041        assert_eq!(cd.get_unknown("dummy"), Some("3"));
1042        assert_eq!(cd.get_filename(), Some("sample.png"));
1043        assert_eq!(cd.get_unknown_ext("dummy"), None);
1044        assert_eq!(cd.get_unknown("duMMy"), Some("3"));
1045    }
1046}