mirror of
https://github.com/stalwartlabs/mail-parser.git
synced 2026-11-29 00:01:49 +00:00
Base64/QuotedPrintable decoding optimizations.
This commit is contained in:
@@ -1,18 +0,0 @@
|
||||
stages:
|
||||
- build
|
||||
|
||||
rust-latest:
|
||||
stage: build
|
||||
image: rust:latest
|
||||
script:
|
||||
- cargo build --verbose
|
||||
- cargo test --verbose
|
||||
|
||||
rust-nightly:
|
||||
stage: build
|
||||
image: rustlang/rust:nightly
|
||||
script:
|
||||
- cargo build --verbose
|
||||
- cargo test --verbose
|
||||
allow_failure: true
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
language: rust
|
||||
rust:
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
matrix:
|
||||
allow_failures:
|
||||
- rust: nightly
|
||||
@@ -1,3 +1,7 @@
|
||||
mail-parser 0.6.2
|
||||
================================
|
||||
- Base64/QuotedPrintable decoding optimizations.
|
||||
|
||||
mail-parser 0.6.1
|
||||
================================
|
||||
- Support for malformed unstructured fields containing encoded words (#29).
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "mail-parser"
|
||||
description = "Fast and robust e-mail parsing library for Rust"
|
||||
version = "0.6.1"
|
||||
version = "0.6.2"
|
||||
edition = "2018"
|
||||
authors = [ "Stalwart Labs <hello@stalw.art>"]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
|
||||
Generated
+1
-1
@@ -42,7 +42,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mail-parser"
|
||||
version = "0.5.0"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"serde",
|
||||
|
||||
@@ -3,7 +3,7 @@ use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use mail_parser::{
|
||||
decoders::{
|
||||
base64::decode_base64,
|
||||
base64::{decode_base64, decode_base64_mime, decode_base64_word},
|
||||
charsets::{
|
||||
map::get_charset_decoder,
|
||||
single_byte::decoder_iso_8859_1,
|
||||
@@ -12,7 +12,9 @@ use mail_parser::{
|
||||
encoded_word::decode_rfc2047,
|
||||
hex::decode_hex,
|
||||
html::{add_html_token, html_to_text, text_to_html},
|
||||
quoted_printable::decode_quoted_printable,
|
||||
quoted_printable::{
|
||||
decode_quoted_printable, decode_quoted_printable_mime, decode_quoted_printable_word,
|
||||
},
|
||||
},
|
||||
parsers::{
|
||||
fields::{
|
||||
@@ -32,112 +34,71 @@ use mail_parser::{
|
||||
Message,
|
||||
};
|
||||
|
||||
static RFC822_ALPHABET: &[u8] = b"0123456789abcdefghijklm:=- \r\n";
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
// Fuzz every parsing function
|
||||
for n_fuzz in 1..=24 {
|
||||
let mut stream = MessageStream::new(&data);
|
||||
for data_ in [
|
||||
std::borrow::Cow::from(data),
|
||||
std::borrow::Cow::from(into_alphabet(data, RFC822_ALPHABET)),
|
||||
] {
|
||||
let data = data_.as_ref();
|
||||
|
||||
match n_fuzz {
|
||||
1 => {
|
||||
parse_date(&mut stream);
|
||||
}
|
||||
2 => {
|
||||
parse_address(&mut stream);
|
||||
}
|
||||
3 => {
|
||||
parse_id(&mut stream);
|
||||
}
|
||||
4 => {
|
||||
parse_comma_separared(&mut stream);
|
||||
}
|
||||
5 => {
|
||||
parse_and_ignore(&mut stream);
|
||||
}
|
||||
6 => {
|
||||
parse_raw(&mut stream);
|
||||
}
|
||||
7 => {
|
||||
parse_unstructured(&mut stream);
|
||||
}
|
||||
8 => {
|
||||
parse_content_type(&mut stream);
|
||||
}
|
||||
9 => {
|
||||
parse_header_name(&data);
|
||||
}
|
||||
10 => {
|
||||
decode_rfc2047(&mut stream, 0);
|
||||
}
|
||||
11 => {
|
||||
seek_next_part(&mut stream, b"\n");
|
||||
}
|
||||
12 => {
|
||||
get_bytes_to_boundary(&mut stream, 0, b"\n", false);
|
||||
}
|
||||
13 => {
|
||||
get_bytes_to_boundary(&mut stream, 0, &[], false);
|
||||
}
|
||||
14 => {
|
||||
skip_crlf(&mut stream);
|
||||
}
|
||||
15 => {
|
||||
is_boundary_end(&mut stream, 0);
|
||||
}
|
||||
16 => {
|
||||
skip_multipart_end(&mut stream);
|
||||
}
|
||||
17 => {
|
||||
decode_base64(&mut stream, 0, b"\n", true);
|
||||
}
|
||||
18 => {
|
||||
decode_base64(&mut stream, 0, b"\n", false);
|
||||
}
|
||||
19 => {
|
||||
decode_base64(&mut stream, 0, &[], true);
|
||||
}
|
||||
20 => {
|
||||
decode_base64(&mut stream, 0, &[], false);
|
||||
}
|
||||
21 => {
|
||||
decode_quoted_printable(&mut stream, 0, b"\n\n", true); // QP Boundaries have to be at least 2 bytes long
|
||||
}
|
||||
22 => {
|
||||
decode_quoted_printable(&mut stream, 0, b"\n\n", false); // QP Boundaries have to be at least 2 bytes long
|
||||
}
|
||||
23 => {
|
||||
decode_quoted_printable(&mut stream, 0, &[], true);
|
||||
}
|
||||
24 => {
|
||||
decode_quoted_printable(&mut stream, 0, &[], false);
|
||||
}
|
||||
0 | 25..=u32::MAX => unreachable!(),
|
||||
// Fuzz every parsing function
|
||||
parse_date(&mut MessageStream::new(&data));
|
||||
parse_address(&mut MessageStream::new(&data));
|
||||
parse_id(&mut MessageStream::new(&data));
|
||||
parse_comma_separared(&mut MessageStream::new(&data));
|
||||
parse_and_ignore(&mut MessageStream::new(&data));
|
||||
parse_raw(&mut MessageStream::new(&data));
|
||||
parse_unstructured(&mut MessageStream::new(&data));
|
||||
parse_content_type(&mut MessageStream::new(&data));
|
||||
parse_header_name(&data);
|
||||
decode_rfc2047(&mut MessageStream::new(&data), 0);
|
||||
|
||||
seek_next_part(&mut MessageStream::new(&data), b"\n");
|
||||
get_mime_part(&mut MessageStream::new(&data), b"\n");
|
||||
seek_part_end(&mut MessageStream::new(&data), b"\n"[..].into());
|
||||
skip_crlf(&mut MessageStream::new(&data));
|
||||
skip_multipart_end(&mut MessageStream::new(&data));
|
||||
|
||||
decode_base64(&data);
|
||||
decode_base64_word(&data);
|
||||
decode_base64_mime(&mut MessageStream::new(&data), b"\n");
|
||||
decode_quoted_printable(&data);
|
||||
decode_quoted_printable_word(&data);
|
||||
decode_quoted_printable_mime(&mut MessageStream::new(&data), b"\n");
|
||||
|
||||
// Fuzz text functions
|
||||
let mut html_str = String::with_capacity(data.len());
|
||||
let str_data = String::from_utf8_lossy(data);
|
||||
add_html_token(&mut html_str, str_data.as_ref().as_bytes(), false);
|
||||
html_to_text(&str_data);
|
||||
text_to_html(&str_data);
|
||||
thread_name(&str_data);
|
||||
trim_trailing_fwd(&str_data);
|
||||
|
||||
// Fuzz decoding functions
|
||||
decode_hex(data);
|
||||
get_charset_decoder(data);
|
||||
|
||||
for decoder in &[
|
||||
decoder_utf7,
|
||||
decoder_utf16_le,
|
||||
decoder_utf16_be,
|
||||
decoder_utf16,
|
||||
decoder_iso_8859_1,
|
||||
] as &[for<'x> fn(&'x [u8]) -> String]
|
||||
{
|
||||
decoder(data);
|
||||
}
|
||||
|
||||
// Fuzz the entire library
|
||||
Message::parse(&data[..]);
|
||||
}
|
||||
|
||||
// Fuzz text functions
|
||||
let mut html_str = String::with_capacity(data.len());
|
||||
let str_data = String::from_utf8_lossy(data);
|
||||
add_html_token(&mut html_str, str_data.as_ref().as_bytes(), false);
|
||||
html_to_text(&str_data);
|
||||
text_to_html(&str_data);
|
||||
thread_name(&str_data);
|
||||
trim_trailing_fwd(&str_data);
|
||||
|
||||
// Fuzz decoding functions
|
||||
decode_hex(data);
|
||||
get_charset_decoder(data);
|
||||
|
||||
for decoder in &[
|
||||
decoder_utf7,
|
||||
decoder_utf16_le,
|
||||
decoder_utf16_be,
|
||||
decoder_utf16,
|
||||
decoder_iso_8859_1,
|
||||
] as &[for<'x> fn(&'x [u8]) -> String]
|
||||
{
|
||||
decoder(data);
|
||||
}
|
||||
|
||||
// Fuzz the entire library
|
||||
Message::parse(&data[..]);
|
||||
});
|
||||
|
||||
fn into_alphabet(data: &[u8], alphabet: &[u8]) -> Vec<u8> {
|
||||
data.iter()
|
||||
.map(|&byte| alphabet[byte as usize % alphabet.len()])
|
||||
.collect()
|
||||
}
|
||||
|
||||
+233
-121
@@ -9,56 +9,89 @@
|
||||
* except according to those terms.
|
||||
*/
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
use super::DecodeResult;
|
||||
|
||||
pub fn decode_base64<'x>(
|
||||
stream: &MessageStream<'x>,
|
||||
start_pos: usize,
|
||||
boundary: &[u8],
|
||||
is_word: bool,
|
||||
) -> (usize, DecodeResult) {
|
||||
let mut success = boundary.is_empty();
|
||||
|
||||
pub fn decode_base64(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut chunk: u32 = 0;
|
||||
let mut byte_count: u8 = 0;
|
||||
let mut match_count: usize = 0;
|
||||
|
||||
let mut bytes_read = 0;
|
||||
let mut buf = Vec::with_capacity(bytes.len() / 4 * 3);
|
||||
|
||||
let mut buf = Vec::with_capacity(stream.data.len() - start_pos);
|
||||
for &ch in bytes {
|
||||
let val = BASE64_MAP[byte_count as usize][ch as usize];
|
||||
|
||||
for ch in stream.data[start_pos..].iter() {
|
||||
bytes_read += 1;
|
||||
if val < 0x01ffffff {
|
||||
byte_count = (byte_count + 1) & 3;
|
||||
|
||||
if !success {
|
||||
if *ch == boundary[match_count] {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
success = true;
|
||||
break;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else if match_count > 0 {
|
||||
if *ch == boundary[0] {
|
||||
match_count = 1;
|
||||
continue;
|
||||
} else {
|
||||
match_count = 0;
|
||||
if byte_count == 1 {
|
||||
chunk = val;
|
||||
} else {
|
||||
chunk |= val;
|
||||
|
||||
if byte_count == 0 {
|
||||
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
|
||||
}
|
||||
}
|
||||
} else if ch == b'=' {
|
||||
match byte_count {
|
||||
1 | 2 => {
|
||||
buf.push(chunk.to_le_bytes()[0]);
|
||||
byte_count = 0;
|
||||
}
|
||||
3 => {
|
||||
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
|
||||
byte_count = 0;
|
||||
}
|
||||
0 => (),
|
||||
_ => {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
} else if !ch.is_ascii_whitespace() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
let val = BASE64_MAP[byte_count as usize][*ch as usize];
|
||||
buf.into()
|
||||
}
|
||||
|
||||
if val >= 0x01ffffff {
|
||||
if *ch == b'=' {
|
||||
match byte_count {
|
||||
pub fn decode_base64_mime<'x>(
|
||||
stream: &mut MessageStream<'x>,
|
||||
boundary: &[u8],
|
||||
) -> (usize, Cow<'x, [u8]>) {
|
||||
let mut chunk: u32 = 0;
|
||||
let mut byte_count: u8 = 0;
|
||||
|
||||
let mut buf = Vec::with_capacity((stream.data.len() - stream.pos) / 4 * 3);
|
||||
let mut pos = stream.pos;
|
||||
|
||||
let mut last_ch = b'\n';
|
||||
let mut end_pos = stream.pos;
|
||||
let mut iter = stream.data[stream.pos..].iter();
|
||||
|
||||
while let Some(&ch) = iter.next() {
|
||||
pos += 1;
|
||||
|
||||
let val = BASE64_MAP[byte_count as usize][ch as usize];
|
||||
if val < 0x01ffffff {
|
||||
byte_count = (byte_count + 1) & 3;
|
||||
|
||||
if byte_count == 1 {
|
||||
chunk = val;
|
||||
} else {
|
||||
chunk |= val;
|
||||
|
||||
if byte_count == 0 {
|
||||
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match ch {
|
||||
b'=' => match byte_count {
|
||||
1 | 2 => {
|
||||
buf.push(chunk.to_le_bytes()[0]);
|
||||
|
||||
byte_count = 0;
|
||||
}
|
||||
3 => {
|
||||
@@ -67,131 +100,210 @@ pub fn decode_base64<'x>(
|
||||
}
|
||||
0 => (),
|
||||
_ => {
|
||||
success = false;
|
||||
return (usize::MAX, b""[..].into());
|
||||
}
|
||||
},
|
||||
b'\n' => end_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 },
|
||||
b' ' | b'\t' | b'\r' => (),
|
||||
b'-' => {
|
||||
return if !boundary.is_empty()
|
||||
&& matches!(iter.next(), Some(b'-'))
|
||||
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
|
||||
&& matches!(
|
||||
stream.data.get(pos + 1 + boundary.len()..),
|
||||
Some([b'\n' | b'\r' | b' ' | b'\t', ..])
|
||||
| Some([b'-', b'-', ..])
|
||||
| Some([])
|
||||
| None
|
||||
) {
|
||||
stream.pos = pos + boundary.len() + 1;
|
||||
buf.shrink_to_fit();
|
||||
(if last_ch == b'\n' { end_pos } else { pos - 1 }, buf.into())
|
||||
} else {
|
||||
(usize::MAX, b""[..].into())
|
||||
};
|
||||
}
|
||||
_ => {
|
||||
return (usize::MAX, b""[..].into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
last_ch = ch;
|
||||
}
|
||||
|
||||
buf.shrink_to_fit();
|
||||
(
|
||||
if boundary.is_empty() {
|
||||
stream.pos = pos;
|
||||
pos
|
||||
} else {
|
||||
usize::MAX
|
||||
},
|
||||
buf.into(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn decode_base64_word(bytes: &[u8]) -> (usize, Vec<u8>) {
|
||||
let mut chunk: u32 = 0;
|
||||
let mut byte_count: u8 = 0;
|
||||
|
||||
let mut bytes_read = 0;
|
||||
|
||||
let mut buf = Vec::with_capacity(64);
|
||||
let mut iter = bytes.iter();
|
||||
|
||||
while let Some(&ch) = iter.next() {
|
||||
bytes_read += 1;
|
||||
|
||||
match ch {
|
||||
b'=' => {
|
||||
match byte_count {
|
||||
1 | 2 => {
|
||||
buf.push(chunk.to_le_bytes()[0]);
|
||||
byte_count = 0;
|
||||
}
|
||||
3 => {
|
||||
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
|
||||
byte_count = 0;
|
||||
}
|
||||
0 => (),
|
||||
_ => {
|
||||
// Invalid
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if !ch.is_ascii_whitespace()
|
||||
|| (is_word
|
||||
&& ch == &b'\n'
|
||||
&& !matches!(stream.data.get(start_pos + bytes_read), Some(ch) if [b' ', b'\t'].contains(ch)))
|
||||
{
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'?' => {
|
||||
if let Some(b'=') = iter.next() {
|
||||
return (bytes_read + 1, buf);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
b'\n' => {
|
||||
if let Some(b' ' | b'\t') = iter.next() {
|
||||
bytes_read += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
b' ' | b'\t' | b'\r' => (),
|
||||
_ => {
|
||||
let val = BASE64_MAP[byte_count as usize][ch as usize];
|
||||
|
||||
byte_count = (byte_count + 1) & 3;
|
||||
if val < 0x01ffffff {
|
||||
byte_count = (byte_count + 1) & 3;
|
||||
|
||||
if byte_count == 1 {
|
||||
chunk = val;
|
||||
} else {
|
||||
chunk |= val;
|
||||
if byte_count == 1 {
|
||||
chunk = val;
|
||||
} else {
|
||||
chunk |= val;
|
||||
|
||||
if byte_count == 0 {
|
||||
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
|
||||
if byte_count == 0 {
|
||||
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(
|
||||
if success { bytes_read } else { 0 },
|
||||
if !buf.is_empty() {
|
||||
buf.shrink_to_fit();
|
||||
DecodeResult::Owned(buf)
|
||||
} else {
|
||||
DecodeResult::Empty
|
||||
},
|
||||
)
|
||||
(usize::MAX, buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
decoders::{base64::decode_base64, DecodeResult},
|
||||
parsers::message::MessageStream,
|
||||
};
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
#[test]
|
||||
fn decode_base64_strings() {
|
||||
let inputs = [
|
||||
("VGVzdA==", "Test", "", true),
|
||||
("WWU=", "Ye", "", true),
|
||||
("QQ==", "A", "", true),
|
||||
("cm8=", "ro", "", true),
|
||||
fn decode_base64() {
|
||||
for (encoded_str, expected_result) in [
|
||||
("VGVzdA==", "Test"),
|
||||
("WWU=", "Ye"),
|
||||
("QQ==", "A"),
|
||||
("cm8=", "ro"),
|
||||
(
|
||||
"QXJlIHlvdSBhIFNoaW1hbm8gb3IgQ2FtcGFnbm9sbyBwZXJzb24/",
|
||||
"Are you a Shimano or Campagnolo person?",
|
||||
"",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPgo8Ym9keT4KPC9ib2R5Pgo8L2h0bWw+Cg==",
|
||||
"<!DOCTYPE html>\n<html>\n<body>\n</body>\n</html>\n",
|
||||
"",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPg\no8Ym9ke\nT4KPC 9ib2R5Pg\n o8L2h0bWw+Cg==",
|
||||
"<!DOCTYPE html>\n<html>\n<body>\n</body>\n</html>\n",
|
||||
"",
|
||||
false,
|
||||
),
|
||||
("w6HDqcOtw7PDug==", "áéíóú"),
|
||||
("====", ""),
|
||||
("w6HDq!cOtw7PDug=", ""),
|
||||
("w6 HD qcOt", "áéí"),
|
||||
("cmáé", ""),
|
||||
("áé", ""),
|
||||
("w\n6\nH\nD\nq\nc\nO\nt\nw\n7\n P\tD u g\n==", "áéíóú"),
|
||||
("w6HDqcOtw7PDug==", "áéíóú"),
|
||||
] {
|
||||
assert_eq!(
|
||||
super::decode_base64(encoded_str.as_bytes()).unwrap_or_default(),
|
||||
expected_result.as_bytes(),
|
||||
"Failed for {:?}",
|
||||
encoded_str
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_base64_mime() {
|
||||
for (encoded_str, expected_result) in [
|
||||
("VGVzdA==\r\n--boundary\n", "Test"),
|
||||
(
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPg\no8Ym9ke\nT4KPC 9ib2R5Pg\n o8L2h0bWw+Cg==",
|
||||
"",
|
||||
"",
|
||||
true,
|
||||
"PCFET0NUWVBFIGh0bWw+CjxodG1sPg\no8Ym9ke\nT4KPC 9ib2R5Pg\n o8L2h0bWw+Cg==\r\n--boundary--\r\n",
|
||||
"<!DOCTYPE html>\n<html>\n<body>\n</body>\n</html>\n",
|
||||
),
|
||||
("w6HDqcOtw7PDug==\r\n--boundary \n", "áéíóú"),
|
||||
("w\n6\nH\nD\nq\nc\nO\nt\nw\n7\n P\tD u g\n==\r\n--boundary\n", "áéíóú"),
|
||||
("w6HDqcOtw7PDug==--boundary", "áéíóú"),
|
||||
(
|
||||
"w6HDqcOtw7PDug==\n--boundary--",
|
||||
"áéíóú",
|
||||
),
|
||||
("w6HDqcOtw7PDug==", "áéíóú", "", true),
|
||||
("====", "", "\n--boundary", true),
|
||||
("w6HDq!cOtw7PDug=", "", "", true),
|
||||
("w6 HD qcOt", "áéí", "", true),
|
||||
("cmáé", "", "", true),
|
||||
("áé", "", "", true),
|
||||
("w6HDqcOtw7PDug==?=", "áéíóú", "?=", true),
|
||||
(
|
||||
"w\n6\nH\nD\nq\nc\nO\nt\nw\n7\n P\tD u g\n==\n--boundary",
|
||||
"áéíóú",
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
("w6HDqcOtw7PDug================?=", "áéíóú", "?=", false),
|
||||
(
|
||||
"w6HDqcOtw7PDug==\n--\n--boundary",
|
||||
"áéíóú",
|
||||
"\n--boundary",
|
||||
false,
|
||||
),
|
||||
];
|
||||
] {
|
||||
let mut s = MessageStream::new(encoded_str.as_bytes());
|
||||
let (_, result) = super::decode_base64_mime(&mut s, b"boundary");
|
||||
|
||||
for input in inputs {
|
||||
let str = input.0.to_string();
|
||||
let stream = MessageStream::new(str.as_bytes());
|
||||
|
||||
let (bytes_read, result) = decode_base64(&stream, 0, input.2.as_bytes(), input.3);
|
||||
assert_eq!(
|
||||
bytes_read > 0,
|
||||
!input.1.is_empty(),
|
||||
"Failed for '{:?}'",
|
||||
input.0
|
||||
result,
|
||||
expected_result.as_bytes(),
|
||||
"Failed for {:?}",
|
||||
encoded_str
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if !input.1.is_empty() {
|
||||
let bytes = match result {
|
||||
DecodeResult::Owned(v) => v,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let result_str = std::str::from_utf8(&bytes).unwrap();
|
||||
//println!("'{}' -> '{}'", input.0.escape_debug(), result_str.escape_debug());
|
||||
assert_eq!(
|
||||
result_str,
|
||||
input.1,
|
||||
"Failed for '{}'",
|
||||
input.0.escape_debug()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn decode_base64_word() {
|
||||
for (encoded_str, expected_result) in [
|
||||
("w 6 H D q c O t w 7 P D u g== ?=", "áéíóú"),
|
||||
("w6HDqcOtw7PDug==?=", "áéíóú"),
|
||||
("w6HDqc\n Otw7PDug==?=", "áéíóú"),
|
||||
("w6HDqcOtw7PDug================?=", "áéíóú"),
|
||||
("?=", ""),
|
||||
] {
|
||||
let (bytes, result) = super::decode_base64_word(encoded_str.as_bytes());
|
||||
assert!(bytes != usize::MAX);
|
||||
assert_eq!(
|
||||
result,
|
||||
expected_result.as_bytes(),
|
||||
"Failed for {:?}",
|
||||
encoded_str
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
use crate::{decoders::charsets::map::get_charset_decoder, parsers::message::MessageStream};
|
||||
|
||||
use super::{
|
||||
base64::decode_base64, quoted_printable::decode_quoted_printable, DecodeFnc, DecodeResult,
|
||||
base64::decode_base64_word, quoted_printable::decode_quoted_printable_word, DecodeWordFnc,
|
||||
};
|
||||
|
||||
enum Rfc2047State {
|
||||
@@ -28,7 +28,7 @@ pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Optio
|
||||
|
||||
let mut charset_start = 0;
|
||||
let mut charset_end = 0;
|
||||
let mut decode_fnc: Option<DecodeFnc> = None;
|
||||
let mut decode_fnc: Option<DecodeWordFnc> = None;
|
||||
|
||||
for ch in stream.data[start_pos..].iter() {
|
||||
read_pos += 1;
|
||||
@@ -64,8 +64,8 @@ pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Optio
|
||||
},
|
||||
Rfc2047State::Encoding => {
|
||||
match ch {
|
||||
b'q' | b'Q' => decode_fnc = Some(decode_quoted_printable),
|
||||
b'b' | b'B' => decode_fnc = Some(decode_base64),
|
||||
b'q' | b'Q' => decode_fnc = Some(decode_quoted_printable_word),
|
||||
b'b' | b'B' => decode_fnc = Some(decode_base64_word),
|
||||
_ => {
|
||||
return (0, None);
|
||||
}
|
||||
@@ -82,10 +82,9 @@ pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Optio
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(decode_fnc) = decode_fnc {
|
||||
if let (bytes_read @ 1..=usize::MAX, DecodeResult::Owned(bytes)) =
|
||||
decode_fnc(stream, read_pos, b"?=", true)
|
||||
{
|
||||
if let (Some(decode_fnc), Some(enc_bytes)) = (decode_fnc, stream.data.get(read_pos..)) {
|
||||
let (bytes_read, bytes) = decode_fnc(enc_bytes);
|
||||
if bytes_read != usize::MAX {
|
||||
return (
|
||||
(read_pos - start_pos) + bytes_read,
|
||||
if let Some(decoder) = get_charset_decoder(&stream.data[charset_start..charset_end])
|
||||
@@ -97,8 +96,6 @@ pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Optio
|
||||
.into()
|
||||
},
|
||||
);
|
||||
} else if let Some(b"?=") = stream.data.get(read_pos..read_pos + 2) {
|
||||
return ((read_pos - start_pos) + 2, Some(String::new()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,96 +104,84 @@ pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Optio
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{decoders::encoded_word::decode_rfc2047, parsers::message::MessageStream};
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
#[test]
|
||||
fn decode_rfc2047_string() {
|
||||
let inputs = [
|
||||
fn decode_rfc2047() {
|
||||
for (input, expected_result, _) in [
|
||||
(
|
||||
"?iso-8859-1?q?this=20is=20some=20text?=".to_string(),
|
||||
"?iso-8859-1?q?this=20is=20some=20text?=",
|
||||
"this is some text",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"?iso-8859-1?q?this is some text?=".to_string(),
|
||||
"?iso-8859-1?q?this is some text?=",
|
||||
"this is some text",
|
||||
true,
|
||||
),
|
||||
("?US-ASCII?Q?Keith_Moore?=", "Keith Moore", false),
|
||||
(
|
||||
"?US-ASCII?Q?Keith_Moore?=".to_string(),
|
||||
"Keith Moore",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"?iso_8859-1:1987?Q?Keld_J=F8rn_Simonsen?=".to_string(),
|
||||
"?iso_8859-1:1987?Q?Keld_J=F8rn_Simonsen?=",
|
||||
"Keld Jørn Simonsen",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=".to_string(),
|
||||
"?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=",
|
||||
"If you can read this yo",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=".to_string(),
|
||||
"?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=",
|
||||
"u understand the example.",
|
||||
true,
|
||||
),
|
||||
("?ISO-8859-1?Q?Olle_J=E4rnefors?=", "Olle Järnefors", true),
|
||||
(
|
||||
"?ISO-8859-1?Q?Olle_J=E4rnefors?=".to_string(),
|
||||
"Olle Järnefors",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?=".to_string(),
|
||||
"?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?=",
|
||||
"Patrik Fältström",
|
||||
true,
|
||||
),
|
||||
("?ISO-8859-1*?Q?a?=".to_string(), "a", true),
|
||||
("?ISO-8859-1**?Q?a_b?=".to_string(), "a b", true),
|
||||
("?ISO-8859-1*?Q?a?=", "a", true),
|
||||
("?ISO-8859-1**?Q?a_b?=", "a b", true),
|
||||
(
|
||||
"?utf-8?b?VGjDrXMgw61zIHbDoWzDrWQgw5pURjg=?=".to_string(),
|
||||
"?utf-8?b?VGjDrXMgw61zIHbDoWzDrWQgw5pURjg=?=",
|
||||
"Thís ís válíd ÚTF8",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"?utf-8*unknown?q?Th=C3=ADs_=C3=ADs_v=C3=A1l=C3=ADd_=C3=9ATF8?=".to_string(),
|
||||
"?utf-8*unknown?q?Th=C3=ADs_=C3=ADs_v=C3=A1l=C3=ADd_=C3=9ATF8?=",
|
||||
"Thís ís válíd ÚTF8",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"?Iso-8859-6?Q?=E5=D1=CD=C8=C7 =C8=C7=E4=D9=C7=E4=E5?=".to_string(),
|
||||
"?Iso-8859-6?Q?=E5=D1=CD=C8=C7 =C8=C7=E4=D9=C7=E4=E5?=",
|
||||
"مرحبا بالعالم",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"?Iso-8859-6*arabic?b?5dHNyMcgyMfk2cfk5Q==?=".to_string(),
|
||||
"?Iso-8859-6*arabic?b?5dHNyMcgyMfk2cfk5Q==?=",
|
||||
"مرحبا بالعالم",
|
||||
true,
|
||||
),
|
||||
#[cfg(feature = "full_encoding")]
|
||||
(
|
||||
"?shift_jis?B?g26DjYFbgUWDj4Fbg4uDaA==?=".to_string(),
|
||||
"?shift_jis?B?g26DjYFbgUWDj4Fbg4uDaA==?=",
|
||||
"ハロー・ワールド",
|
||||
true,
|
||||
),
|
||||
#[cfg(feature = "full_encoding")]
|
||||
(
|
||||
"?iso-2022-jp?q?=1B$B%O%m!<!&%o!<%k%I=1B(B?=".to_string(),
|
||||
"?iso-2022-jp?q?=1B$B%O%m!<!&%o!<%k%I=1B(B?=",
|
||||
"ハロー・ワールド",
|
||||
true,
|
||||
),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let str = input.0.to_string();
|
||||
|
||||
match decode_rfc2047(&MessageStream::new(str.as_bytes()), 0) {
|
||||
(_, Some(string)) => {
|
||||
] {
|
||||
match super::decode_rfc2047(&MessageStream::new(input.as_bytes()), 0) {
|
||||
(_, Some(result)) => {
|
||||
//println!("Decoded '{}'", string);
|
||||
assert_eq!(string, input.1);
|
||||
assert_eq!(result, expected_result);
|
||||
}
|
||||
_ => panic!("Failed to decode '{}'", input.0),
|
||||
_ => panic!("Failed to decode '{}'", input),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-8
@@ -9,6 +9,8 @@
|
||||
* except according to those terms.
|
||||
*/
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
pub mod base64;
|
||||
@@ -18,11 +20,5 @@ pub mod hex;
|
||||
pub mod html;
|
||||
pub mod quoted_printable;
|
||||
|
||||
pub type DecodeFnc<'x> = fn(&MessageStream<'x>, usize, &[u8], bool) -> (usize, DecodeResult);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DecodeResult {
|
||||
Owned(Vec<u8>),
|
||||
Borrowed((usize, usize)),
|
||||
Empty,
|
||||
}
|
||||
pub type DecodeFnc<'x> = fn(&mut MessageStream<'x>, &[u8]) -> (usize, Cow<'x, [u8]>);
|
||||
pub type DecodeWordFnc<'x> = fn(&[u8]) -> (usize, Vec<u8>);
|
||||
|
||||
+273
-183
@@ -9,9 +9,9 @@
|
||||
* except according to those terms.
|
||||
*/
|
||||
|
||||
use crate::parsers::message::MessageStream;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::DecodeResult;
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
enum QuotedPrintableState {
|
||||
@@ -20,141 +20,218 @@ enum QuotedPrintableState {
|
||||
Hex1,
|
||||
}
|
||||
|
||||
pub fn decode_quoted_printable<'x>(
|
||||
stream: &MessageStream<'x>,
|
||||
start_pos: usize,
|
||||
boundary: &[u8],
|
||||
is_word: bool,
|
||||
) -> (usize, DecodeResult) {
|
||||
let mut success = boundary.is_empty();
|
||||
|
||||
let mut bytes_read = 0;
|
||||
|
||||
let mut buf = Vec::with_capacity(stream.data.len() - start_pos);
|
||||
pub fn decode_quoted_printable(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut buf = Vec::with_capacity(bytes.len());
|
||||
|
||||
let mut state = QuotedPrintableState::None;
|
||||
let mut match_count = 0;
|
||||
let mut hex1 = 0;
|
||||
let mut lf_pos = 0;
|
||||
|
||||
debug_assert!(boundary.is_empty() || boundary.len() >= 2);
|
||||
let mut iter = stream.data[start_pos..].iter().peekable();
|
||||
|
||||
while let Some(ch) = iter.next() {
|
||||
bytes_read += 1;
|
||||
|
||||
// if success is false, a boundary was provided
|
||||
if !success {
|
||||
let mut is_boundary_end = true;
|
||||
|
||||
if *ch == boundary[match_count] {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
let done = if is_word {
|
||||
true
|
||||
} else {
|
||||
is_boundary_end =
|
||||
crate::parsers::mime::is_boundary_end(stream, start_pos + bytes_read);
|
||||
if is_boundary_end && bytes_read - boundary.len() == lf_pos {
|
||||
buf.pop();
|
||||
}
|
||||
is_boundary_end
|
||||
};
|
||||
|
||||
if done {
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
for &ch in bytes {
|
||||
match ch {
|
||||
b'=' => {
|
||||
if let QuotedPrintableState::None = state {
|
||||
state = QuotedPrintableState::Eq
|
||||
} else {
|
||||
continue;
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
if match_count > 0 {
|
||||
if QuotedPrintableState::Eq != state {
|
||||
for ch in boundary[..match_count].iter() {
|
||||
buf.push(*ch);
|
||||
}
|
||||
}
|
||||
state = QuotedPrintableState::None;
|
||||
|
||||
// is_boundary_end is always true except in the rare event
|
||||
// that a boundary was found without a proper MIME ending (-- or \r\n)
|
||||
if is_boundary_end {
|
||||
if *ch == boundary[0] {
|
||||
// Char matched beginning of boundary, get next char.
|
||||
match_count = 1;
|
||||
continue;
|
||||
} else {
|
||||
// Reset match count and decode character
|
||||
match_count = 0;
|
||||
}
|
||||
b'\n' => {
|
||||
if QuotedPrintableState::Eq == state {
|
||||
state = QuotedPrintableState::None;
|
||||
} else {
|
||||
// There was a full boundary match but without a proper MIME
|
||||
// ending, reset match count and continue.
|
||||
match_count = 0;
|
||||
continue;
|
||||
buf.push(b'\n');
|
||||
}
|
||||
}
|
||||
b'\r' => (),
|
||||
_ => match state {
|
||||
QuotedPrintableState::None => {
|
||||
buf.push(ch);
|
||||
}
|
||||
QuotedPrintableState::Eq => {
|
||||
hex1 = HEX_MAP[ch as usize];
|
||||
if hex1 != -1 {
|
||||
state = QuotedPrintableState::Hex1;
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Hex1 => {
|
||||
let hex2 = HEX_MAP[ch as usize];
|
||||
|
||||
state = QuotedPrintableState::None;
|
||||
if hex2 != -1 {
|
||||
buf.push(((hex1 as u8) << 4) | hex2 as u8);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
buf.into()
|
||||
}
|
||||
|
||||
pub fn decode_quoted_printable_mime<'x>(
|
||||
stream: &mut MessageStream<'x>,
|
||||
boundary: &[u8],
|
||||
) -> (usize, Cow<'x, [u8]>) {
|
||||
let mut buf = Vec::with_capacity(stream.data.len() - stream.pos);
|
||||
|
||||
let mut state = QuotedPrintableState::None;
|
||||
let mut hex1 = 0;
|
||||
|
||||
let mut iter = stream.data[stream.pos..].iter().peekable();
|
||||
let mut last_ch = 0;
|
||||
let mut pos = stream.pos;
|
||||
let mut end_pos = stream.pos;
|
||||
|
||||
while let Some(&ch) = iter.next() {
|
||||
pos += 1;
|
||||
|
||||
match ch {
|
||||
b'=' => {
|
||||
if let QuotedPrintableState::None = state {
|
||||
state = QuotedPrintableState::Eq
|
||||
} else {
|
||||
success = false;
|
||||
break;
|
||||
return (usize::MAX, b""[..].into());
|
||||
}
|
||||
}
|
||||
b'\n' => {
|
||||
if is_word {
|
||||
if !matches!(iter.peek(), Some(ch) if [b' ', b'\t'].contains(ch)) {
|
||||
success = false;
|
||||
break;
|
||||
} else {
|
||||
loop {
|
||||
iter.next();
|
||||
bytes_read += 1;
|
||||
if !matches!(iter.peek(), Some(ch) if [b' ', b'\t'].contains(ch)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if QuotedPrintableState::Eq == state {
|
||||
end_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 };
|
||||
if QuotedPrintableState::Eq == state {
|
||||
state = QuotedPrintableState::None;
|
||||
} else {
|
||||
buf.push(b'\n');
|
||||
lf_pos = bytes_read;
|
||||
}
|
||||
}
|
||||
b'_' if is_word => {
|
||||
b'\r' => (),
|
||||
b'-' if !boundary.is_empty()
|
||||
&& matches!(iter.peek(), Some(b'-'))
|
||||
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
|
||||
&& matches!(
|
||||
stream.data.get(pos + 1 + boundary.len()..),
|
||||
Some([b'\n' | b'\r' | b' ' | b'\t', ..])
|
||||
| Some([b'-', b'-', ..])
|
||||
| Some([])
|
||||
| None
|
||||
) =>
|
||||
{
|
||||
if last_ch == b'\n' {
|
||||
buf.pop();
|
||||
} else {
|
||||
end_pos = pos - 1;
|
||||
}
|
||||
stream.pos = pos + boundary.len() + 1;
|
||||
buf.shrink_to_fit();
|
||||
return (end_pos, buf.into());
|
||||
}
|
||||
_ => match state {
|
||||
QuotedPrintableState::None => {
|
||||
buf.push(ch);
|
||||
}
|
||||
QuotedPrintableState::Eq => {
|
||||
hex1 = HEX_MAP[ch as usize];
|
||||
if hex1 != -1 {
|
||||
state = QuotedPrintableState::Hex1;
|
||||
} else {
|
||||
return (usize::MAX, b""[..].into());
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Hex1 => {
|
||||
let hex2 = HEX_MAP[ch as usize];
|
||||
|
||||
state = QuotedPrintableState::None;
|
||||
if hex2 != -1 {
|
||||
buf.push(((hex1 as u8) << 4) | hex2 as u8);
|
||||
} else {
|
||||
return (usize::MAX, b""[..].into());
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
last_ch = ch;
|
||||
}
|
||||
|
||||
buf.shrink_to_fit();
|
||||
(
|
||||
if boundary.is_empty() {
|
||||
stream.pos = pos;
|
||||
pos
|
||||
} else {
|
||||
usize::MAX
|
||||
},
|
||||
buf.into(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn decode_quoted_printable_word(bytes: &[u8]) -> (usize, Vec<u8>) {
|
||||
let mut bytes_read = 0;
|
||||
|
||||
let mut buf = Vec::with_capacity(64);
|
||||
|
||||
let mut state = QuotedPrintableState::None;
|
||||
let mut hex1 = 0;
|
||||
|
||||
let mut iter = bytes.iter().peekable();
|
||||
|
||||
while let Some(&ch) = iter.next() {
|
||||
bytes_read += 1;
|
||||
|
||||
match ch {
|
||||
b'=' => {
|
||||
if let QuotedPrintableState::None = state {
|
||||
state = QuotedPrintableState::Eq
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
b'?' => {
|
||||
if let Some(b'=') = iter.peek() {
|
||||
return (bytes_read + 1, buf);
|
||||
} else {
|
||||
buf.push(b'?');
|
||||
}
|
||||
}
|
||||
b'\n' => {
|
||||
if let Some(b' ' | b'\t') = iter.peek() {
|
||||
loop {
|
||||
iter.next();
|
||||
bytes_read += 1;
|
||||
if !matches!(iter.peek(), Some(b' ' | b'\t')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
b'_' => {
|
||||
buf.push(b' ');
|
||||
}
|
||||
b'\r' => (),
|
||||
_ => match state {
|
||||
QuotedPrintableState::None => {
|
||||
buf.push(*ch);
|
||||
buf.push(ch);
|
||||
}
|
||||
QuotedPrintableState::Eq => {
|
||||
hex1 = HEX_MAP[*ch as usize];
|
||||
hex1 = HEX_MAP[ch as usize];
|
||||
if hex1 != -1 {
|
||||
state = QuotedPrintableState::Hex1;
|
||||
} else {
|
||||
success = false;
|
||||
// Failed
|
||||
break;
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Hex1 => {
|
||||
let hex2 = HEX_MAP[*ch as usize];
|
||||
let hex2 = HEX_MAP[ch as usize];
|
||||
|
||||
state = QuotedPrintableState::None;
|
||||
if hex2 != -1 {
|
||||
let ch = ((hex1 as u8) << 4) | hex2 as u8;
|
||||
|
||||
buf.push(ch);
|
||||
buf.push(((hex1 as u8) << 4) | hex2 as u8);
|
||||
} else {
|
||||
success = false;
|
||||
// Failed
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -162,27 +239,16 @@ pub fn decode_quoted_printable<'x>(
|
||||
}
|
||||
}
|
||||
|
||||
(
|
||||
if success { bytes_read } else { 0 },
|
||||
if !buf.is_empty() {
|
||||
buf.shrink_to_fit();
|
||||
DecodeResult::Owned(buf)
|
||||
} else {
|
||||
DecodeResult::Empty
|
||||
},
|
||||
)
|
||||
(usize::MAX, buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
decoders::{quoted_printable::decode_quoted_printable, DecodeResult},
|
||||
parsers::message::MessageStream,
|
||||
};
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
#[test]
|
||||
fn decode_quoted_printable_string() {
|
||||
let inputs = [
|
||||
fn decode_quoted_printable() {
|
||||
for (encoded_str, expected_result) in [
|
||||
(
|
||||
concat!(
|
||||
"J'interdis aux marchands de vanter trop leurs marchandises. ",
|
||||
@@ -201,26 +267,10 @@ mod tests {
|
||||
"est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.\n",
|
||||
"— Antoine de Saint-Exupéry, Citadelle (1948)"
|
||||
),
|
||||
"",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--boundary",
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry",
|
||||
"— Antoine de Saint-Exupéry",
|
||||
"--boundary",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry\n--",
|
||||
"--boundary",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry=\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry--",
|
||||
"--boundary",
|
||||
false,
|
||||
),
|
||||
(
|
||||
concat!(
|
||||
@@ -233,70 +283,110 @@ mod tests {
|
||||
"sprach ein Redner, \"in steter Furcht vor Menschen und ",
|
||||
"Tieren, eine Beute der Hunde, der\n"
|
||||
),
|
||||
"",
|
||||
false,
|
||||
),
|
||||
("this=20is=20some=20text?=", "this is some text", "?=", true),
|
||||
("this is some text?=", "this is some text", "?=", true),
|
||||
("Keith_Moore?=", "Keith Moore", "?=", true),
|
||||
("=2=123?=", "", "?=", true),
|
||||
("= 20?=", "", "?=", true),
|
||||
("=====?=", "", "?=", true),
|
||||
("=20=20=XX?=", "", "?=", true),
|
||||
("=AX?=", "", "?=", true),
|
||||
("=\n=\n==?=", "", "?=", true),
|
||||
("=\r=1z?=", "", "?=", true),
|
||||
("=|?=", "", "?=", true),
|
||||
("????????=", "???????", "?=", true),
|
||||
];
|
||||
("\n\n", "\n\n"),
|
||||
] {
|
||||
assert_eq!(
|
||||
super::decode_quoted_printable(encoded_str.as_bytes()).unwrap_or_default(),
|
||||
expected_result.as_bytes(),
|
||||
"Failed for {:?}",
|
||||
encoded_str
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for input in inputs {
|
||||
let str = input.0.to_string();
|
||||
let stream = MessageStream::new(str.as_bytes());
|
||||
|
||||
let (bytes_read, result) =
|
||||
decode_quoted_printable(&stream, 0, input.2.as_bytes(), input.3);
|
||||
#[test]
|
||||
fn decode_quoted_printable_mime() {
|
||||
for (encoded_str, expected_result) in [
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--boundary",
|
||||
"— Antoine de Saint-Exupéry",
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry\n--",
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry=\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry--",
|
||||
),
|
||||
(
|
||||
concat!(
|
||||
"J'interdis aux marchands de vanter trop leurs marchandises. ",
|
||||
"Car ils se font=\nvite p=C3=A9dagogues et t'enseignent comme but ce ",
|
||||
"qui n'est par essence qu=\n'un moyen, et te trompant ainsi sur la route ",
|
||||
"=C3=A0 suivre les voil=C3=\n=A0 bient=C3=B4t qui te d=C3=A9gradent, car ",
|
||||
"si leur musique est vulgaire il=\ns te fabriquent pour te la vendre une ",
|
||||
"=C3=A2me vulgaire.\n=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry, ",
|
||||
"Citadelle (1948)\r\n--boundary--"
|
||||
),
|
||||
concat!(
|
||||
"J'interdis aux marchands de vanter trop leurs marchandises. ",
|
||||
"Car ils se fontvite pédagogues et t'enseignent comme but ce qui ",
|
||||
"n'est par essence qu'un moyen, et te trompant ainsi sur la route ",
|
||||
"à suivre les voilà bientôt qui te dégradent, car si leur musique ",
|
||||
"est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.\n",
|
||||
"— Antoine de Saint-Exupéry, Citadelle (1948)"
|
||||
),
|
||||
),
|
||||
(
|
||||
"=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--\n--boundary",
|
||||
"— Antoine de Saint-Exupéry\n--",
|
||||
),
|
||||
(
|
||||
concat!(
|
||||
"Die Hasen klagten einst uber ihre Lage; \"wir ",
|
||||
"leben\", sprach ein=\r\n Redner, \"in steter Furcht vor Menschen",
|
||||
" und Tieren, eine Beute der Hunde,=\r\n der\n\r\n--boundary \n"
|
||||
),
|
||||
concat!(
|
||||
"Die Hasen klagten einst uber ihre Lage; \"wir leben\", ",
|
||||
"sprach ein Redner, \"in steter Furcht vor Menschen und ",
|
||||
"Tieren, eine Beute der Hunde, der\n"
|
||||
),
|
||||
),
|
||||
] {
|
||||
let mut s = MessageStream::new(encoded_str.as_bytes());
|
||||
let (_, result) = super::decode_quoted_printable_mime(&mut s, b"boundary");
|
||||
|
||||
assert_eq!(
|
||||
bytes_read > 0,
|
||||
!input.1.is_empty(),
|
||||
"Failed for '{:?}'",
|
||||
input.0
|
||||
result,
|
||||
expected_result.as_bytes(),
|
||||
"Failed for {:?}",
|
||||
encoded_str
|
||||
);
|
||||
|
||||
if !input.1.is_empty() {
|
||||
let bytes = match result {
|
||||
DecodeResult::Owned(v) => v,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let result_str = std::str::from_utf8(&bytes).unwrap();
|
||||
|
||||
/*println!(
|
||||
"Decoded '{}'\n -> to ->\n'{}'\n{}",
|
||||
input.0.escape_debug(),
|
||||
result_str.escape_debug(),
|
||||
"-".repeat(50)
|
||||
);*/
|
||||
|
||||
assert_eq!(
|
||||
input.1,
|
||||
result_str,
|
||||
"Failed for '{}'",
|
||||
input.0.escape_debug()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MIRI overflow tests
|
||||
for input in [b"\x0a\x0a\x00\x0b".to_vec(), b":B\x0a%".to_vec()] {
|
||||
let stream = MessageStream::new(&input[..]);
|
||||
decode_quoted_printable(&stream, 0, b"\n\n", true);
|
||||
let stream = MessageStream::new(&input[..]);
|
||||
decode_quoted_printable(&stream, 0, b"\n\n", false);
|
||||
let stream = MessageStream::new(&input[..]);
|
||||
decode_quoted_printable(&stream, 0, &[], true);
|
||||
let stream = MessageStream::new(&input[..]);
|
||||
decode_quoted_printable(&stream, 0, &[], false);
|
||||
#[test]
|
||||
fn decode_quoted_printable_word() {
|
||||
for (encoded_str, expected_result) in [
|
||||
("this=20is=20some=20text?=", "this is some text"),
|
||||
("this=20is=20\n some=20text?=", "this is some text"),
|
||||
("this is some text?=", "this is some text"),
|
||||
("Keith_Moore?=", "Keith Moore"),
|
||||
("=2=123?=", ""),
|
||||
("= 20?=", ""),
|
||||
("=====?=", ""),
|
||||
("=20=20=XX?=", ""),
|
||||
("=AX?=", ""),
|
||||
("=\n=\n==?=", ""),
|
||||
("=\r=1z?=", ""),
|
||||
("=|?=", ""),
|
||||
("????????=", "???????"),
|
||||
("\n\n", ""),
|
||||
] {
|
||||
let (bytes, mut result) = super::decode_quoted_printable_word(encoded_str.as_bytes());
|
||||
if bytes == usize::MAX {
|
||||
result.clear();
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
expected_result.as_bytes(),
|
||||
"Failed for {:?}",
|
||||
encoded_str
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -1377,8 +1377,8 @@ impl<'x> MessagePart<'x> {
|
||||
}
|
||||
|
||||
/// Get the raw body end offset of this part
|
||||
pub fn offset_end_offset(&self) -> usize {
|
||||
self.offset_header
|
||||
pub fn raw_end_offset(&self) -> usize {
|
||||
self.offset_end
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -93,8 +93,7 @@ pub fn parse_unstructured<'x>(stream: &mut MessageStream<'x>) -> HeaderValue<'x>
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn parse_unstructured_text() {
|
||||
use crate::parsers::fields::unstructured::parse_unstructured;
|
||||
fn parse_unstructured() {
|
||||
use crate::parsers::message::MessageStream;
|
||||
|
||||
let inputs = [
|
||||
@@ -196,7 +195,7 @@ mod tests {
|
||||
|
||||
for (input, expected_result, _) in inputs {
|
||||
assert_eq!(
|
||||
parse_unstructured(&mut MessageStream::new(input.as_bytes()),).unwrap_text(),
|
||||
super::parse_unstructured(&mut MessageStream::new(input.as_bytes()),).unwrap_text(),
|
||||
expected_result,
|
||||
"Failed to parse '{:?}'",
|
||||
input
|
||||
|
||||
+54
-161
@@ -13,8 +13,8 @@ use std::borrow::Cow;
|
||||
|
||||
use crate::{
|
||||
decoders::{
|
||||
base64::decode_base64, charsets::map::get_charset_decoder,
|
||||
quoted_printable::decode_quoted_printable, DecodeFnc, DecodeResult,
|
||||
base64::decode_base64_mime, charsets::map::get_charset_decoder,
|
||||
quoted_printable::decode_quoted_printable_mime, DecodeFnc,
|
||||
},
|
||||
ContentType, Encoding, GetHeader, HeaderValue, Message, MessageAttachment, MessagePart,
|
||||
MessagePartId, PartType, RfcHeader,
|
||||
@@ -22,7 +22,9 @@ use crate::{
|
||||
|
||||
use super::{
|
||||
header::parse_headers,
|
||||
mime::{get_bytes_to_boundary, seek_crlf, seek_next_part, skip_crlf, skip_multipart_end},
|
||||
mime::{
|
||||
get_mime_part, seek_crlf, seek_next_part, seek_part_end, skip_crlf, skip_multipart_end,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
@@ -45,38 +47,6 @@ impl Default for MimeType {
|
||||
}
|
||||
}
|
||||
|
||||
fn result_to_string<'x>(
|
||||
result: DecodeResult,
|
||||
data: &'x [u8],
|
||||
content_type: Option<&ContentType>,
|
||||
) -> Cow<'x, str> {
|
||||
match (
|
||||
result,
|
||||
content_type.and_then(|ct| {
|
||||
ct.get_attribute("charset")
|
||||
.and_then(|c| get_charset_decoder(c.as_bytes()))
|
||||
}),
|
||||
) {
|
||||
(DecodeResult::Owned(vec), Some(charset_decoder)) => charset_decoder(&vec).into(),
|
||||
(DecodeResult::Owned(vec), None) => String::from_utf8(vec)
|
||||
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
|
||||
.into(),
|
||||
(DecodeResult::Borrowed((from, to)), Some(charset_decoder)) => {
|
||||
charset_decoder(&data[from..to]).into()
|
||||
}
|
||||
(DecodeResult::Borrowed((from, to)), None) => String::from_utf8_lossy(&data[from..to]),
|
||||
(DecodeResult::Empty, _) => "\n".to_string().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn result_to_bytes(result: DecodeResult, data: &[u8]) -> Cow<[u8]> {
|
||||
match result {
|
||||
DecodeResult::Owned(vec) => Cow::Owned(vec),
|
||||
DecodeResult::Borrowed((from, to)) => Cow::Borrowed(&data[from..to]),
|
||||
DecodeResult::Empty => Cow::from(vec![b'?']),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn get_mime_type(
|
||||
content_type: Option<&ContentType>,
|
||||
@@ -114,24 +84,6 @@ fn get_mime_type(
|
||||
}
|
||||
}
|
||||
|
||||
/*#[inline(always)]
|
||||
fn add_missing_type<'x>(
|
||||
headers: &mut Vec<Header<'x>>,
|
||||
c_type: Cow<'x, str>,
|
||||
c_subtype: Cow<'x, str>,
|
||||
) {
|
||||
if headers.is_empty() {
|
||||
headers.insert(
|
||||
RfcHeader::ContentType,
|
||||
HeaderValue::ContentType(ContentType {
|
||||
c_type,
|
||||
c_subtype: Some(c_subtype),
|
||||
attributes: None,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}*/
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct MessageParserState {
|
||||
mime_type: MimeType,
|
||||
@@ -225,17 +177,15 @@ impl<'x> Message<'x> {
|
||||
if let Some(mime_boundary) =
|
||||
content_type.map_or_else(|| None, |f| f.get_attribute("boundary"))
|
||||
{
|
||||
//let mime_boundary = format!("\n--{}", mime_boundary).into_bytes();
|
||||
let mime_boundary = format!("--{}", mime_boundary).into_bytes();
|
||||
state.offset_body = seek_crlf(&stream, stream.pos);
|
||||
|
||||
if seek_next_part(&mut stream, mime_boundary.as_ref()) {
|
||||
if seek_next_part(&mut stream, mime_boundary.as_bytes()) {
|
||||
let part_id = message.parts.len();
|
||||
let new_state = MessageParserState {
|
||||
in_alternative: state.in_alternative
|
||||
|| mime_type == MimeType::MultipartAlernative,
|
||||
mime_type,
|
||||
mime_boundary: mime_boundary.into(),
|
||||
mime_boundary: mime_boundary.as_bytes().to_vec().into(),
|
||||
html_parts: message.html_body.len(),
|
||||
text_parts: message.text_body.len(),
|
||||
need_html_body: state.need_html_body,
|
||||
@@ -267,22 +217,21 @@ impl<'x> Message<'x> {
|
||||
skip_crlf(&mut stream);
|
||||
state.offset_body = stream.pos;
|
||||
|
||||
let (is_binary, mut encoding, decode_fnc): (bool, Encoding, DecodeFnc) =
|
||||
match part_headers.get_rfc(&RfcHeader::ContentTransferEncoding) {
|
||||
Some(HeaderValue::Text(encoding))
|
||||
if encoding.eq_ignore_ascii_case("base64") =>
|
||||
{
|
||||
(false, Encoding::Base64, decode_base64)
|
||||
}
|
||||
Some(HeaderValue::Text(encoding))
|
||||
if encoding.eq_ignore_ascii_case("quoted-printable") =>
|
||||
{
|
||||
(false, Encoding::QuotedPrintable, decode_quoted_printable)
|
||||
}
|
||||
_ => (true, Encoding::None, get_bytes_to_boundary),
|
||||
};
|
||||
let (mut encoding, decode_fnc): (Encoding, DecodeFnc) = match part_headers
|
||||
.get_rfc(&RfcHeader::ContentTransferEncoding)
|
||||
{
|
||||
Some(HeaderValue::Text(encoding)) if encoding.eq_ignore_ascii_case("base64") => {
|
||||
(Encoding::Base64, decode_base64_mime)
|
||||
}
|
||||
Some(HeaderValue::Text(encoding))
|
||||
if encoding.eq_ignore_ascii_case("quoted-printable") =>
|
||||
{
|
||||
(Encoding::QuotedPrintable, decode_quoted_printable_mime)
|
||||
}
|
||||
_ => (Encoding::None, get_mime_part),
|
||||
};
|
||||
|
||||
if is_binary && mime_type == MimeType::Message {
|
||||
if mime_type == MimeType::Message && encoding == Encoding::None {
|
||||
let new_state = MessageParserState {
|
||||
mime_type: MimeType::Message,
|
||||
mime_boundary: state.mime_boundary.take(),
|
||||
@@ -307,102 +256,31 @@ impl<'x> Message<'x> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (bytes_read, mut bytes) = decode_fnc(
|
||||
&stream,
|
||||
stream.pos,
|
||||
state
|
||||
.mime_boundary
|
||||
.as_ref()
|
||||
.map_or_else(|| &[][..], |b| &b[..]),
|
||||
false,
|
||||
let (offset_end, mut bytes) = decode_fnc(
|
||||
&mut stream,
|
||||
state.mime_boundary.as_deref().unwrap_or(&b""[..]),
|
||||
);
|
||||
|
||||
// Attempt to recover contents of an invalid message
|
||||
let is_encoding_problem = bytes_read == 0;
|
||||
let is_encoding_problem = offset_end == usize::MAX;
|
||||
if is_encoding_problem {
|
||||
encoding = Encoding::None;
|
||||
mime_type = MimeType::TextOther;
|
||||
is_inline = false;
|
||||
is_text = true;
|
||||
|
||||
let did_recover = if !(stream.pos >= stream.data.len()
|
||||
|| (is_binary && state.mime_boundary.is_none()))
|
||||
{
|
||||
// Get raw MIME part
|
||||
let (bytes_read, r_bytes) = if !is_binary {
|
||||
get_bytes_to_boundary(
|
||||
&stream,
|
||||
stream.pos,
|
||||
state
|
||||
.mime_boundary
|
||||
.as_ref()
|
||||
.map_or_else(|| &[][..], |b| &b[..]),
|
||||
false,
|
||||
)
|
||||
} else {
|
||||
(0, DecodeResult::Empty)
|
||||
};
|
||||
let (offset_end, boundary_found) =
|
||||
seek_part_end(&mut stream, state.mime_boundary.as_deref());
|
||||
state.offset_end = offset_end;
|
||||
bytes = stream.data[state.offset_body..state.offset_end].into();
|
||||
|
||||
if bytes_read == 0 {
|
||||
// If there is a MIME boundary, ignore it and get raw message
|
||||
if state.mime_boundary.is_some() {
|
||||
let (bytes_read, r_bytes) =
|
||||
get_bytes_to_boundary(&stream, stream.pos, &[][..], false);
|
||||
if bytes_read > 0 {
|
||||
bytes = r_bytes;
|
||||
stream.pos += bytes_read;
|
||||
state.mime_boundary = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
bytes = r_bytes;
|
||||
stream.pos += bytes_read;
|
||||
true
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if did_recover {
|
||||
mime_type = MimeType::TextOther;
|
||||
is_inline = false;
|
||||
is_text = true;
|
||||
} else {
|
||||
// Could not recover error, add part and abort
|
||||
message.parts.push(MessagePart {
|
||||
headers: std::mem::take(&mut part_headers),
|
||||
encoding: Encoding::None,
|
||||
is_encoding_problem: true,
|
||||
body: PartType::Binary((&[][..]).into()),
|
||||
offset_header: state.offset_header,
|
||||
offset_body: state.offset_body,
|
||||
offset_end: stream.pos,
|
||||
});
|
||||
break;
|
||||
if !boundary_found {
|
||||
state.mime_boundary = None;
|
||||
}
|
||||
} else {
|
||||
stream.pos += bytes_read;
|
||||
state.offset_end = offset_end;
|
||||
}
|
||||
|
||||
// Obtain offset end
|
||||
state.offset_end = if let Some(mime_boundary) = &state.mime_boundary {
|
||||
let pos = stream.pos.saturating_sub(mime_boundary.len());
|
||||
std::cmp::max(
|
||||
stream.data.get(pos - 2).map_or(pos - 1, |&ch| {
|
||||
if ch == b'\r' {
|
||||
pos - 2
|
||||
} else {
|
||||
pos - 1
|
||||
}
|
||||
}),
|
||||
state.offset_body,
|
||||
)
|
||||
} else {
|
||||
stream.pos
|
||||
};
|
||||
|
||||
let body_part = if mime_type != MimeType::Message {
|
||||
let is_inline = is_inline
|
||||
&& part_headers
|
||||
@@ -439,7 +317,23 @@ impl<'x> Message<'x> {
|
||||
};
|
||||
|
||||
if is_text {
|
||||
let text = result_to_string(bytes, stream.data, content_type);
|
||||
let text = match (
|
||||
bytes,
|
||||
content_type.and_then(|ct| {
|
||||
ct.get_attribute("charset")
|
||||
.and_then(|c| get_charset_decoder(c.as_bytes()))
|
||||
}),
|
||||
) {
|
||||
(Cow::Owned(vec), Some(charset_decoder)) => charset_decoder(&vec).into(),
|
||||
(Cow::Owned(vec), None) => String::from_utf8(vec)
|
||||
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
|
||||
.into(),
|
||||
(Cow::Borrowed(bytes), Some(charset_decoder)) => {
|
||||
charset_decoder(bytes).into()
|
||||
}
|
||||
(Cow::Borrowed(bytes), None) => String::from_utf8_lossy(bytes),
|
||||
};
|
||||
|
||||
let is_html = mime_type == MimeType::TextHtml;
|
||||
|
||||
if add_to_html && !is_html {
|
||||
@@ -471,7 +365,6 @@ impl<'x> Message<'x> {
|
||||
|
||||
message.attachments.push(message.parts.len());
|
||||
|
||||
let bytes = result_to_bytes(bytes, stream.data);
|
||||
if !is_inline {
|
||||
PartType::Binary(bytes)
|
||||
} else {
|
||||
@@ -480,7 +373,7 @@ impl<'x> Message<'x> {
|
||||
}
|
||||
} else {
|
||||
message.attachments.push(message.parts.len());
|
||||
PartType::Message(MessageAttachment::Raw(result_to_bytes(bytes, stream.data)))
|
||||
PartType::Message(MessageAttachment::Raw(bytes))
|
||||
};
|
||||
|
||||
// Add part
|
||||
@@ -504,7 +397,7 @@ impl<'x> Message<'x> {
|
||||
.mime_boundary
|
||||
.as_ref()
|
||||
.map(|b| {
|
||||
let pos = stream.pos.saturating_sub(b.len());
|
||||
let pos = stream.pos.saturating_sub(b.len() + 2);
|
||||
stream.data.get(pos - 2).map_or(pos - 1, |&ch| {
|
||||
if ch == b'\r' {
|
||||
pos - 2
|
||||
|
||||
+93
-90
@@ -9,34 +9,24 @@
|
||||
* except according to those terms.
|
||||
*/
|
||||
|
||||
use crate::decoders::DecodeResult;
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::message::MessageStream;
|
||||
|
||||
pub(crate) fn seek_next_part(stream: &mut MessageStream, boundary: &[u8]) -> bool {
|
||||
pub fn seek_next_part(stream: &mut MessageStream, boundary: &[u8]) -> bool {
|
||||
if !boundary.is_empty() {
|
||||
let mut pos = stream.pos;
|
||||
|
||||
let mut match_count = 0;
|
||||
|
||||
for ch in &stream.data[pos..] {
|
||||
let mut iter = stream.data[stream.pos..].iter().peekable();
|
||||
while let Some(&ch) = iter.next() {
|
||||
pos += 1;
|
||||
|
||||
if ch == &boundary[match_count] {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
stream.pos = pos;
|
||||
return true;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else if match_count > 0 {
|
||||
if ch == &boundary[0] {
|
||||
match_count = 1;
|
||||
continue;
|
||||
} else {
|
||||
match_count = 0;
|
||||
}
|
||||
if ch == b'-'
|
||||
&& matches!(iter.peek(), Some(b'-'))
|
||||
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
|
||||
{
|
||||
stream.pos = pos + boundary.len() + 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,85 +34,98 @@ pub(crate) fn seek_next_part(stream: &mut MessageStream, boundary: &[u8]) -> boo
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn get_bytes_to_boundary<'x>(
|
||||
stream: &MessageStream<'x>,
|
||||
start_pos: usize,
|
||||
pub fn get_mime_part<'x>(
|
||||
stream: &mut MessageStream<'x>,
|
||||
boundary: &[u8],
|
||||
_is_word: bool,
|
||||
) -> (usize, DecodeResult) {
|
||||
let mut read_pos = start_pos;
|
||||
) -> (usize, Cow<'x, [u8]>) {
|
||||
let mut last_ch = b'\n';
|
||||
let start_pos = stream.pos;
|
||||
let mut end_pos = stream.pos;
|
||||
let mut pos = stream.pos;
|
||||
|
||||
if !boundary.is_empty() {
|
||||
let mut match_count = 0;
|
||||
let mut cr_pos = 0;
|
||||
let mut lf_pos = 0;
|
||||
let mut iter = stream.data[stream.pos..].iter().peekable();
|
||||
while let Some(&ch) = iter.next() {
|
||||
pos += 1;
|
||||
|
||||
for ch in &stream.data[read_pos..] {
|
||||
read_pos += 1;
|
||||
|
||||
if ch == &boundary[match_count] {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
if is_boundary_end(stream, read_pos) {
|
||||
let mut match_pos = read_pos - match_count;
|
||||
|
||||
if match_pos > 0 && match_pos == lf_pos {
|
||||
if lf_pos == cr_pos + 1 {
|
||||
match_pos -= 2;
|
||||
} else {
|
||||
match_pos -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
read_pos - start_pos,
|
||||
if start_pos < match_pos {
|
||||
DecodeResult::Borrowed((start_pos, match_pos))
|
||||
} else {
|
||||
DecodeResult::Empty
|
||||
},
|
||||
);
|
||||
} else {
|
||||
match_count = 0;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
} else if match_count > 0 {
|
||||
if ch == &boundary[0] {
|
||||
match_count = 1;
|
||||
continue;
|
||||
} else {
|
||||
match_count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if ch == &b'\r' {
|
||||
cr_pos = read_pos;
|
||||
} else if ch == &b'\n' {
|
||||
lf_pos = read_pos;
|
||||
if ch == b'\n' {
|
||||
end_pos = if last_ch == b'\r' { pos - 2 } else { pos - 1 };
|
||||
} else if ch == b'-'
|
||||
&& !boundary.is_empty()
|
||||
&& matches!(iter.peek(), Some(b'-'))
|
||||
&& stream.data.get(pos + 1..pos + 1 + boundary.len()) == Some(boundary)
|
||||
&& matches!(
|
||||
stream.data.get(pos + 1 + boundary.len()..),
|
||||
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
|
||||
)
|
||||
{
|
||||
stream.pos = pos + boundary.len() + 1;
|
||||
if last_ch != b'\n' {
|
||||
end_pos = pos - 1;
|
||||
}
|
||||
return (end_pos, stream.data[start_pos..end_pos].into());
|
||||
}
|
||||
|
||||
(0, DecodeResult::Empty)
|
||||
} else if start_pos < stream.data.len() {
|
||||
(
|
||||
stream.data.len() - start_pos,
|
||||
DecodeResult::Borrowed((start_pos, stream.data.len())),
|
||||
)
|
||||
} else {
|
||||
(0, DecodeResult::Empty)
|
||||
last_ch = ch;
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn is_boundary_end(stream: &MessageStream, pos: usize) -> bool {
|
||||
matches!(
|
||||
stream.data.get(pos..),
|
||||
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
|
||||
(
|
||||
if boundary.is_empty() {
|
||||
stream.pos = pos;
|
||||
stream.pos
|
||||
} else {
|
||||
usize::MAX
|
||||
},
|
||||
stream.data[start_pos..pos].into(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn skip_multipart_end(stream: &mut MessageStream) -> bool {
|
||||
pub fn seek_part_end<'x>(stream: &mut MessageStream<'x>, boundary: Option<&[u8]>) -> (usize, bool) {
|
||||
let mut last_ch = b'\n';
|
||||
let mut end_pos = stream.pos;
|
||||
|
||||
if let Some(boundary) = boundary {
|
||||
let mut iter = stream.data[stream.pos..].iter().peekable();
|
||||
while let Some(&ch) = iter.next() {
|
||||
stream.pos += 1;
|
||||
|
||||
if ch == b'\n' {
|
||||
end_pos = if last_ch == b'\r' {
|
||||
stream.pos - 2
|
||||
} else {
|
||||
stream.pos - 1
|
||||
};
|
||||
} else if ch == b'-'
|
||||
&& matches!(iter.peek(), Some(b'-'))
|
||||
&& stream
|
||||
.data
|
||||
.get(stream.pos + 1..stream.pos + 1 + boundary.len())
|
||||
== Some(boundary)
|
||||
&& matches!(
|
||||
stream.data.get(stream.pos + 1 + boundary.len()..),
|
||||
Some([b'\n' | b'\r' | b' ' | b'\t', ..])
|
||||
| Some([b'-', b'-', ..])
|
||||
| Some([])
|
||||
| None
|
||||
)
|
||||
{
|
||||
if last_ch != b'\n' {
|
||||
end_pos = stream.pos - 1;
|
||||
}
|
||||
stream.pos += boundary.len() + 1;
|
||||
return (end_pos, true);
|
||||
}
|
||||
|
||||
last_ch = ch;
|
||||
}
|
||||
|
||||
(stream.pos, false)
|
||||
} else {
|
||||
stream.pos = stream.data.len();
|
||||
(stream.pos, true)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn skip_multipart_end(stream: &mut MessageStream) -> bool {
|
||||
match stream.data.get(stream.pos..stream.pos + 2) {
|
||||
Some(b"--") => {
|
||||
if let Some(byte) = stream.data.get(stream.pos + 2) {
|
||||
@@ -138,7 +141,7 @@ pub(crate) fn skip_multipart_end(stream: &mut MessageStream) -> bool {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn skip_crlf(stream: &mut MessageStream) {
|
||||
pub fn skip_crlf(stream: &mut MessageStream) {
|
||||
for ch in &stream.data[stream.pos..] {
|
||||
match ch {
|
||||
b'\r' | b' ' | b'\t' => stream.pos += 1,
|
||||
@@ -152,7 +155,7 @@ pub(crate) fn skip_crlf(stream: &mut MessageStream) {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn seek_crlf(stream: &MessageStream, mut start_pos: usize) -> usize {
|
||||
pub fn seek_crlf(stream: &MessageStream, mut start_pos: usize) -> usize {
|
||||
for ch in &stream.data[start_pos..] {
|
||||
match ch {
|
||||
b'\r' | b' ' | b'\t' => start_pos += 1,
|
||||
|
||||
@@ -142,7 +142,7 @@
|
||||
],
|
||||
"is_encoding_problem": false,
|
||||
"body": {
|
||||
"Text": "\n"
|
||||
"Text": ""
|
||||
},
|
||||
"offset_header": 610,
|
||||
"offset_body": 656,
|
||||
|
||||
@@ -148,7 +148,7 @@
|
||||
],
|
||||
"is_encoding_problem": false,
|
||||
"body": {
|
||||
"Text": "\n"
|
||||
"Text": ""
|
||||
},
|
||||
"offset_header": 678,
|
||||
"offset_body": 724,
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
"text_body": [
|
||||
2
|
||||
],
|
||||
"attachments": [],
|
||||
"attachments": [
|
||||
3
|
||||
],
|
||||
"parts": [
|
||||
{
|
||||
"headers": [
|
||||
@@ -86,7 +88,7 @@
|
||||
"headers": [],
|
||||
"is_encoding_problem": true,
|
||||
"body": {
|
||||
"Binary": []
|
||||
"Text": ""
|
||||
},
|
||||
"offset_header": 131,
|
||||
"offset_body": 132,
|
||||
|
||||
Vendored
+1
-1
@@ -259,7 +259,7 @@
|
||||
},
|
||||
"offset_header": 522,
|
||||
"offset_body": 597,
|
||||
"offset_end": 603
|
||||
"offset_end": 604
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+1
-1
@@ -206,7 +206,7 @@
|
||||
],
|
||||
"is_encoding_problem": false,
|
||||
"body": {
|
||||
"Text": "\n"
|
||||
"Text": ""
|
||||
},
|
||||
"offset_header": 794,
|
||||
"offset_body": 882,
|
||||
|
||||
Reference in New Issue
Block a user