rfc2047_decoder/
decoder.rs

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
use std::result;
use thiserror::Error;

use crate::{evaluator, lexer, parser};

/// The possible errors which can occur while parsing the string.
#[derive(Error, Debug, PartialEq)]
pub enum Error {
    /// Symbolises that an error occured in the lexer.
    #[error(transparent)]
    Lexer(#[from] lexer::Error),

    /// Symbolises that an error occured in the parser.
    #[error(transparent)]
    Parser(#[from] parser::Error),

    /// Symbolises that an error occured in the evaluator.
    #[error(transparent)]
    Evaluator(#[from] evaluator::Error),
}

/// Determines which strategy should be used if an encoded word isn't encoded as
/// described in the RFC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RecoverStrategy {
    /// Decode the encoded word although it's incorrectly encoded.
    ///
    /// # Example
    /// Take a look to [Decoder#RecoveryStrategy::Decode](Decoder#recoverstrategydecode).
    Decode,

    /// Skip the incorrectly encoded encoded word.
    ///
    /// # Example
    /// Take a look to [Decoder#RecoveryStrategy::Skip](Decoder#recoverstrategyskip).
    Skip,

    /// Abort the string-parsing and return an error.
    ///
    /// # Example
    /// Take a look to [Decoder#RecoveryStrategy::Abort](Decoder#recoverstrategyabort-default).
    Abort,
}

type Result<T> = result::Result<T, Error>;

/// Represents the decoder builder.
///
/// # Example
/// ```
/// use rfc2047_decoder::{Decoder, RecoverStrategy};
///
/// let decoder = Decoder::new()
///                 .too_long_encoded_word_strategy(RecoverStrategy::Skip);
/// let decoded_str = decoder.decode("=?UTF-8?B?c3Ry?=").unwrap();
///
/// assert_eq!(decoded_str, "str");
/// ```
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Decoder {
    /// Determines which strategy should be used, if the parser encounters
    /// encoded words which are longer than allowed in the RFC (it's longer than 75 chars).
    pub too_long_encoded_word: RecoverStrategy,
}

impl Decoder {
    /// Equals [Decoder::default].
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the strategy if the decoder finds an encoded word which is too long.
    ///
    /// # Examples
    ///
    /// Each example uses the same encoded message:
    /// ```txt
    /// =?utf-8?B?TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgaW50ZXJkdW0gcXVhbSBldSBmYWNpbGlzaXMgb3JuYXJlLg==?=
    /// ```
    /// which exceeds the maximum length of 75 chars so it's actually invalid.
    ///
    /// ## RecoverStrategy::Skip
    /// Skips the invalid encoded word and parses it as clear text.
    ///
    /// ```rust
    /// use rfc2047_decoder::{Decoder, RecoverStrategy};
    ///
    /// let message = "=?utf-8?B?TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgaW50ZXJkdW0gcXVhbSBldSBmYWNpbGlzaXMgb3JuYXJlLg==?=";
    /// let decoder = Decoder::new()
    ///                 .too_long_encoded_word_strategy(RecoverStrategy::Skip);
    ///
    /// let parsed = decoder.decode(message).unwrap();
    ///
    /// // nothing changed!
    /// assert_eq!(parsed, message);
    /// ```
    ///
    /// ## RecoverStrategy::Decode
    /// Although the encoded word is invalid, keep decoding it.
    ///
    /// ```rust
    /// use rfc2047_decoder::{Decoder, RecoverStrategy};
    ///
    /// let message = "=?utf-8?B?TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgaW50ZXJkdW0gcXVhbSBldSBmYWNpbGlzaXMgb3JuYXJlLg==?=";
    /// let decoder = Decoder::new()
    ///                 .too_long_encoded_word_strategy(RecoverStrategy::Decode);
    ///
    /// let parsed = decoder.decode(message).unwrap();
    ///
    /// // could you decode it? ;)
    /// let expected_result = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut interdum quam eu facilisis ornare.";
    ///
    /// assert_eq!(parsed, expected_result);
    /// ```
    ///
    /// ## RecoverStrategy::Abort (default)
    /// The parser will return an `Err` and collects all encoded words which are
    /// too long. You can use them afterwards for error messages for example.
    ///
    /// ```rust
    /// use rfc2047_decoder::{Decoder, RecoverStrategy, Error::{self, Lexer}};
    /// use rfc2047_decoder::LexerError::ParseEncodedWordTooLongError;
    /// use rfc2047_decoder::TooLongEncodedWords;
    ///
    /// let message = "=?utf-8?B?TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgaW50ZXJkdW0gcXVhbSBldSBmYWNpbGlzaXMgb3JuYXJlLg==?=";
    /// // `RecoverStrategy::Abort` is the default strategy
    /// let decoder = Decoder::new();
    ///
    /// let parsed = decoder.decode(message);
    ///
    /// assert_eq!(parsed, Err(Lexer(ParseEncodedWordTooLongError(TooLongEncodedWords(vec!["=?utf-8?B?TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gVXQgaW50ZXJkdW0gcXVhbSBldSBmYWNpbGlzaXMgb3JuYXJlLg==?=".to_string()])))));
    /// ```
    pub fn too_long_encoded_word_strategy(mut self, strategy: RecoverStrategy) -> Self {
        self.too_long_encoded_word = strategy;
        self
    }

    /// Decodes the given RFC 2047 MIME Message Header encoded string.
    pub fn decode<T: AsRef<[u8]>>(self, encoded_str: T) -> Result<String> {
        let text_tokens = lexer::run(encoded_str.as_ref(), self)?;
        let parsed_text = parser::run(text_tokens)?;
        let evaluated_string = evaluator::run(parsed_text)?;

        Ok(evaluated_string)
    }
}

impl Default for Decoder {
    /// Returns the decoder with the following default "settings":
    ///
    /// - `too_long_encoded_word`: [RecoverStrategy::Abort]
    fn default() -> Self {
        Self {
            too_long_encoded_word: RecoverStrategy::Abort,
        }
    }
}

#[cfg(test)]
mod tests {
    /// Here are the main-tests which are listed here:
    /// https://datatracker.ietf.org/doc/html/rfc2047#section-8
    /// Scroll down until you see the table.
    mod rfc_tests {
        use crate::decode;

        #[test]
        fn decode_encoded_word_single_char() {
            assert_eq!(decode("=?ISO-8859-1?Q?a?=").unwrap(), "a");
        }

        #[test]
        fn decode_encoded_word_separated_by_whitespace() {
            assert_eq!(decode("=?ISO-8859-1?Q?a?= b").unwrap(), "a b");
        }

        #[test]
        fn decode_two_encoded_chars() {
            assert_eq!(
                decode("=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=").unwrap(),
                "ab"
            );
        }

        #[test]
        fn whitespace_between_two_encoded_words_should_be_ignored() {
            assert_eq!(
                decode("=?ISO-8859-1?Q?a?=  =?ISO-8859-1?Q?b?=").unwrap(),
                "ab"
            );
        }

        #[test]
        fn whitespace_chars_between_two_encoded_words_should_be_ignored() {
            assert_eq!(
                decode(
                    "=?ISO-8859-1?Q?a?=               
                     =?ISO-8859-1?Q?b?="
                )
                .unwrap(),
                "ab"
            );
        }

        #[test]
        fn whitespace_encoded_in_encoded_word() {
            assert_eq!(decode("=?ISO-8859-1?Q?a_b?=").unwrap(), "a b");
        }

        #[test]
        fn ignore_whitespace_between_two_encoded_words_but_not_the_encoded_whitespace() {
            assert_eq!(
                decode("=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=").unwrap(),
                "a b"
            );
        }
    }

    /// Those are some custom tests
    mod custom_tests {
        use crate::decode;

        #[test]
        fn clear_empty() {
            assert_eq!(decode("").unwrap(), "");
        }

        #[test]
        fn clear_with_spaces() {
            assert_eq!(decode("str with spaces").unwrap(), "str with spaces");
        }

        #[test]
        fn utf8_qs_empty() {
            assert_eq!(decode("").unwrap(), "");
        }

        #[test]
        fn utf8_qs_with_str() {
            assert_eq!(decode("=?UTF-8?Q?str?=").unwrap(), "str");
        }

        #[test]
        fn utf8_qs_with_spaces() {
            assert_eq!(
                decode("=?utf8?q?str_with_spaces?=").unwrap(),
                "str with spaces"
            );
        }

        #[test]
        fn utf8_qs_with_spec_chars() {
            assert_eq!(
                decode("=?utf8?q?str_with_special_=C3=A7h=C3=A0r=C3=9F?=").unwrap(),
                "str with special çhàrß"
            );
        }

        #[test]
        fn utf8_qs_double() {
            assert_eq!(
                decode("=?UTF-8?Q?str?=\r\n =?UTF-8?Q?str?=").unwrap(),
                "strstr"
            );
            assert_eq!(
                decode("=?UTF-8?Q?str?=\n =?UTF-8?Q?str?=").unwrap(),
                "strstr"
            );
            assert_eq!(decode("=?UTF-8?Q?str?= =?UTF-8?Q?str?=").unwrap(), "strstr");
            assert_eq!(decode("=?UTF-8?Q?str?==?UTF-8?Q?str?=").unwrap(), "strstr");
        }

        #[test]
        fn utf8_b64_empty() {
            assert_eq!(decode("=?UTF-8?B??=").unwrap(), "");
        }

        #[test]
        fn utf8_b64_with_str() {
            assert_eq!(decode("=?UTF-8?B?c3Ry?=").unwrap(), "str");
        }

        #[test]
        fn utf8_b64_with_spaces() {
            assert_eq!(
                decode("=?utf8?b?c3RyIHdpdGggc3BhY2Vz?=").unwrap(),
                "str with spaces"
            );
        }

        #[test]
        fn utf8_b64_with_spec_chars() {
            assert_eq!(
                decode("=?utf8?b?c3RyIHdpdGggc3BlY2lhbCDDp2jDoHLDnw==?=").unwrap(),
                "str with special çhàrß"
            );
        }

        #[test]
        fn utf8_b64_trailing_bit() {
            assert_eq!(
                decode("=?utf-8?B?UG9ydGFsZSBIYWNraW5nVGVhbW==?=").unwrap(),
                "Portale HackingTeam",
            );
        }
    }
}