Skip to main content

actix_http/header/shared/
extended.rs

1//! Originally taken from `hyper::header::parsing`.
2
3use std::{fmt, str::FromStr};
4
5use language_tags::LanguageTag;
6
7use crate::header::{Charset, HTTP_VALUE};
8
9/// The value part of an extended parameter consisting of three parts:
10/// - The REQUIRED character set name (`charset`).
11/// - The OPTIONAL language information (`language_tag`).
12/// - A character sequence representing the actual value (`value`), separated by single quotes.
13///
14/// It is defined in [RFC 5987 §3.2](https://www.rfc-editor.org/info/rfc5987/#section-3.2).
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct ExtendedValue {
17    /// The character set that is used to encode the `value` to a string.
18    pub charset: Charset,
19
20    /// The human language details of the `value`, if available.
21    pub language_tag: Option<LanguageTag>,
22
23    /// The parameter value, as expressed in octets.
24    pub value: Vec<u8>,
25}
26
27/// Parses extended header parameter values (`ext-value`), as defined
28/// in [RFC 5987 §3.2](https://www.rfc-editor.org/info/rfc5987/#section-3.2).
29///
30/// Extended values are denoted by parameter names that end with `*`.
31///
32/// ## ABNF
33///
34/// ```plain
35/// ext-value     = charset  "'" [ language ] "'" value-chars
36///               ; like RFC 2231's <extended-initial-value>
37///               ; (see [RFC 2231 §7])
38///
39/// charset       = "UTF-8" / "ISO-8859-1" / mime-charset
40///
41/// mime-charset  = 1*mime-charsetc
42/// mime-charsetc = ALPHA / DIGIT
43///               / "!" / "#" / "$" / "%" / "&"
44///               / "+" / "-" / "^" / "_" / "`"
45///               / "{" / "}" / "~"
46///               ; as <mime-charset> in [RFC 2978 §2.3]
47///               ; except that the single quote is not included
48///               ; SHOULD be registered in the IANA charset registry
49///
50/// language      = <Language-Tag, defined in [RFC 5646 §2.1]>
51///
52/// value-chars   = *( pct-encoded / attr-char )
53///
54/// pct-encoded   = "%" HEXDIG HEXDIG
55///               ; see [RFC 3986 §2.1]
56///
57/// attr-char     = ALPHA / DIGIT
58///               / "!" / "#" / "$" / "&" / "+" / "-" / "."
59///               / "^" / "_" / "`" / "|" / "~"
60///               ; token except ( "*" / "'" / "%" )
61/// ```
62///
63/// [RFC 2231 §7]: https://www.rfc-editor.org/info/rfc2231/#section-7
64/// [RFC 2978 §2.3]: https://www.rfc-editor.org/info/rfc2978/#section-2.3
65/// [RFC 3986 §2.1]: https://www.rfc-editor.org/info/rfc3986/#section-2.1
66/// [RFC 5646 §2.1]: https://www.rfc-editor.org/info/rfc5646/#section-2.1
67pub fn parse_extended_value(val: &str) -> Result<ExtendedValue, crate::error::ParseError> {
68    // Break into three pieces separated by the single-quote character
69    let mut parts = val.splitn(3, '\'');
70
71    // Interpret the first piece as a Charset
72    let charset: Charset = match parts.next() {
73        None => return Err(crate::error::ParseError::Header),
74        Some(n) => FromStr::from_str(n).map_err(|_| crate::error::ParseError::Header)?,
75    };
76
77    // Interpret the second piece as a language tag
78    let language_tag: Option<LanguageTag> = match parts.next() {
79        None => return Err(crate::error::ParseError::Header),
80        Some("") => None,
81        Some(s) => match s.parse() {
82            Ok(lt) => Some(lt),
83            Err(_) => return Err(crate::error::ParseError::Header),
84        },
85    };
86
87    // Interpret the third piece as a sequence of value characters
88    let value: Vec<u8> = match parts.next() {
89        None => return Err(crate::error::ParseError::Header),
90        Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
91    };
92
93    Ok(ExtendedValue {
94        charset,
95        language_tag,
96        value,
97    })
98}
99
100impl fmt::Display for ExtendedValue {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        let encoded_value = percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
103
104        if let Some(ref lang) = self.language_tag {
105            write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
106        } else {
107            write!(f, "{}''{}", self.charset, encoded_value)
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn test_parse_extended_value_with_encoding_and_language_tag() {
118        let expected_language_tag = "en".parse::<LanguageTag>().unwrap();
119        // RFC 5987, Section 3.2.2
120        // Extended notation, using the Unicode character U+00A3 (POUND SIGN)
121        let result = parse_extended_value("iso-8859-1'en'%A3%20rates");
122        assert!(result.is_ok());
123        let extended_value = result.unwrap();
124        assert_eq!(Charset::Iso_8859_1, extended_value.charset);
125        assert!(extended_value.language_tag.is_some());
126        assert_eq!(expected_language_tag, extended_value.language_tag.unwrap());
127        assert_eq!(
128            vec![163, b' ', b'r', b'a', b't', b'e', b's'],
129            extended_value.value
130        );
131    }
132
133    #[test]
134    fn test_parse_extended_value_with_encoding() {
135        // RFC 5987, Section 3.2.2
136        // Extended notation, using the Unicode characters U+00A3 (POUND SIGN)
137        // and U+20AC (EURO SIGN)
138        let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates");
139        assert!(result.is_ok());
140        let extended_value = result.unwrap();
141        assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset);
142        assert!(extended_value.language_tag.is_none());
143        assert_eq!(
144            vec![
145                194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't',
146                b'e', b's',
147            ],
148            extended_value.value
149        );
150    }
151
152    #[test]
153    fn test_parse_extended_value_missing_language_tag_and_encoding() {
154        // From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2
155        let result = parse_extended_value("foo%20bar.html");
156        assert!(result.is_err());
157    }
158
159    #[test]
160    fn test_parse_extended_value_partially_formatted() {
161        let result = parse_extended_value("UTF-8'missing third part");
162        assert!(result.is_err());
163    }
164
165    #[test]
166    fn test_parse_extended_value_partially_formatted_blank() {
167        let result = parse_extended_value("blank second part'");
168        assert!(result.is_err());
169    }
170
171    #[test]
172    fn test_fmt_extended_value_with_encoding_and_language_tag() {
173        let extended_value = ExtendedValue {
174            charset: Charset::Iso_8859_1,
175            language_tag: Some("en".parse().expect("Could not parse language tag")),
176            value: vec![163, b' ', b'r', b'a', b't', b'e', b's'],
177        };
178        assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_value));
179    }
180
181    #[test]
182    fn test_fmt_extended_value_with_encoding() {
183        let extended_value = ExtendedValue {
184            charset: Charset::Ext("UTF-8".to_string()),
185            language_tag: None,
186            value: vec![
187                194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't',
188                b'e', b's',
189            ],
190        };
191        assert_eq!(
192            "UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
193            format!("{}", extended_value)
194        );
195    }
196}