Improved decoder results.

This commit is contained in:
Mauro D
2021-11-03 16:15:10 +00:00
parent 514f989e7e
commit bfaeeeb886
8 changed files with 117 additions and 66 deletions
+11
View File
@@ -1,3 +1,14 @@
/*
* Copyright Stalwart Labs, Minter Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
use mail_parser::{Addr, Address, BodyPart, Group, Message, MessagePart, MimeFieldGet};
fn main() {
+14 -7
View File
@@ -9,16 +9,16 @@
* 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, Option<Cow<'x, [u8]>>) {
) -> (usize, DecodeResult) {
let mut success = boundary.is_empty();
let mut chunk: u32 = 0;
@@ -95,16 +95,19 @@ pub fn decode_base64<'x>(
if success { bytes_read } else { 0 },
if !buf.is_empty() {
buf.shrink_to_fit();
Some(buf.into())
DecodeResult::Owned(buf)
} else {
None
DecodeResult::Empty
},
)
}
#[cfg(test)]
mod tests {
use crate::{decoders::base64::decode_base64, parsers::message::MessageStream};
use crate::{
decoders::{base64::decode_base64, DecodeResult},
parsers::message::MessageStream,
};
#[test]
fn decode_base64_strings() {
@@ -172,7 +175,11 @@ mod tests {
);
if !input.1.is_empty() {
let result_str = std::str::from_utf8(result.as_ref().unwrap().as_ref()).unwrap();
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,
+20 -19
View File
@@ -11,7 +11,9 @@
use crate::{decoders::charsets::map::get_charset_decoder, parsers::message::MessageStream};
use super::{base64::decode_base64, quoted_printable::decode_quoted_printable, DecodeFnc};
use super::{
base64::decode_base64, quoted_printable::decode_quoted_printable, DecodeFnc, DecodeResult,
};
enum Rfc2047State {
Init,
@@ -80,26 +82,25 @@ pub fn decode_rfc2047(stream: &MessageStream, start_pos: usize) -> (usize, Optio
}
}
if decode_fnc.is_none() {
return (0, None);
if let Some(decode_fnc) = decode_fnc {
if let (bytes_read @ 1..=usize::MAX, DecodeResult::Owned(bytes)) =
decode_fnc(stream, read_pos, b"?=", true)
{
return (
(read_pos - start_pos) + bytes_read,
if let Some(decoder) = get_charset_decoder(&stream.data[charset_start..charset_end])
{
decoder(&bytes).into()
} else {
String::from_utf8(bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
},
);
}
}
if let (bytes_read @ 1..=usize::MAX, Some(bytes)) =
decode_fnc.unwrap()(stream, read_pos, b"?=", true)
{
(
(read_pos - start_pos) + bytes_read,
if let Some(decoder) = get_charset_decoder(&stream.data[charset_start..charset_end]) {
decoder(bytes.as_ref()).into()
} else {
String::from_utf8(bytes.into_owned())
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
},
)
} else {
(0, None)
}
(0, None)
}
#[cfg(test)]
+9 -6
View File
@@ -1,7 +1,3 @@
use std::borrow::Cow;
use crate::parsers::message::MessageStream;
/*
* Copyright Stalwart Labs, Minter Ltd. See the COPYING
* file at the top-level directory of this distribution.
@@ -13,6 +9,8 @@ use crate::parsers::message::MessageStream;
* except according to those terms.
*/
use crate::parsers::message::MessageStream;
pub mod base64;
pub mod charsets;
pub mod encoded_word;
@@ -20,5 +18,10 @@ pub mod hex;
pub mod html;
pub mod quoted_printable;
pub type DecodeFnc<'x> =
fn(&MessageStream<'x>, usize, &[u8], bool) -> (usize, Option<Cow<'x, [u8]>>);
pub type DecodeFnc<'x> = fn(&MessageStream<'x>, usize, &[u8], bool) -> (usize, DecodeResult);
pub enum DecodeResult {
Owned(Vec<u8>),
Borrowed((usize, usize)),
Empty,
}
+12 -7
View File
@@ -9,10 +9,10 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::parsers::message::MessageStream;
use super::DecodeResult;
#[derive(PartialEq, Debug)]
enum QuotedPrintableState {
None,
@@ -25,7 +25,7 @@ pub fn decode_quoted_printable<'x>(
start_pos: usize,
boundary: &[u8],
is_word: bool,
) -> (usize, Option<Cow<'x, [u8]>>) {
) -> (usize, DecodeResult) {
let mut success = boundary.is_empty();
let mut bytes_read = 0;
@@ -150,9 +150,9 @@ pub fn decode_quoted_printable<'x>(
if success { bytes_read } else { 0 },
if !buf.is_empty() {
buf.shrink_to_fit();
Some(buf.into())
DecodeResult::Owned(buf)
} else {
None
DecodeResult::Empty
},
)
}
@@ -160,7 +160,8 @@ pub fn decode_quoted_printable<'x>(
#[cfg(test)]
mod tests {
use crate::{
decoders::quoted_printable::decode_quoted_printable, parsers::message::MessageStream,
decoders::{quoted_printable::decode_quoted_printable, DecodeResult},
parsers::message::MessageStream,
};
#[test]
@@ -248,7 +249,11 @@ mod tests {
);
if !input.1.is_empty() {
let result_str = std::str::from_utf8(result.as_ref().unwrap()).unwrap();
let bytes = match result {
DecodeResult::Owned(v) => v,
_ => unreachable!(),
};
let result_str = std::str::from_utf8(&bytes).unwrap();
/*println!(
"Decoded '{}'\n -> to ->\n'{}'\n{}",
-1
View File
@@ -256,7 +256,6 @@
//! println!("{}", serde_yaml::to_string(&message).unwrap());
//!```
#[forbid(unsafe_code)]
pub mod decoders;
pub mod parsers;
+33 -19
View File
@@ -17,7 +17,7 @@ use crate::{
charsets::map::get_charset_decoder,
html::{html_to_text, text_to_html},
quoted_printable::decode_quoted_printable,
DecodeFnc,
DecodeFnc, DecodeResult,
},
BinaryPart, ContentType, InlinePart, Message, MessageHeader, MessagePart, MimeHeader, TextPart,
};
@@ -42,19 +42,36 @@ enum MimeType {
Other,
}
#[inline(always)]
fn bytes_to_string<'x>(bytes: Cow<'x, [u8]>, content_type: Option<&ContentType>) -> Cow<'x, str> {
if let Some(content_type) = content_type {
if let Some(charset) = content_type.get_attribute("charset") {
if let Some(decoder_fnc) = get_charset_decoder(charset.as_bytes()) {
return decoder_fnc(bytes.as_ref()).into();
}
}
}
fn result_to_string<'x>(
result: DecodeResult,
data: &'x [u8],
content_type: Option<&ContentType>,
) -> Cow<'x, str> {
let charset_decoder = content_type.and_then(|ct| {
ct.get_attribute("charset").and_then(|c| get_charset_decoder(c.as_bytes()))
});
String::from_utf8(bytes.into_owned())
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
match (result, charset_decoder) {
(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)]
@@ -269,7 +286,7 @@ impl<'x> Message<'x> {
false,
)
} else {
(0, None)
(0, DecodeResult::Empty)
};
if bytes_read == 0 {
@@ -334,10 +351,7 @@ impl<'x> Message<'x> {
if is_text {
let text_part = TextPart {
contents: bytes_to_string(
bytes.unwrap_or_else(|| vec![b'\n'].into()),
header.get_content_type(),
),
contents: result_to_string(bytes, stream.data, header.get_content_type()),
header: if !mime_part_header.is_empty() {
Some(std::mem::take(&mut mime_part_header))
} else {
@@ -373,7 +387,7 @@ impl<'x> Message<'x> {
} else {
None
},
contents: bytes.unwrap_or_else(|| Cow::from(vec![b'?'])),
contents: result_to_bytes(bytes, stream.data),
};
if add_to_html {
+18 -7
View File
@@ -1,4 +1,15 @@
use std::borrow::Cow;
/*
* Copyright Stalwart Labs, Minter Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
use crate::decoders::DecodeResult;
use super::message::MessageStream;
@@ -38,7 +49,7 @@ pub fn get_bytes_to_boundary<'x>(
start_pos: usize,
boundary: &[u8],
_is_word: bool,
) -> (usize, Option<Cow<'x, [u8]>>) {
) -> (usize, DecodeResult) {
let mut read_pos = start_pos;
return if !boundary.is_empty() {
@@ -56,9 +67,9 @@ pub fn get_bytes_to_boundary<'x>(
return (
read_pos - start_pos,
if start_pos < match_pos {
Cow::from(&stream.data[start_pos..match_pos]).into()
DecodeResult::Borrowed((start_pos, match_pos))
} else {
None
DecodeResult::Empty
},
);
} else {
@@ -76,14 +87,14 @@ pub fn get_bytes_to_boundary<'x>(
}
}
(0, None)
(0, DecodeResult::Empty)
} else if start_pos < stream.data.len() {
(
stream.data.len() - start_pos,
Cow::from(&stream.data[start_pos..]).into(),
DecodeResult::Borrowed((start_pos, stream.data.len())),
)
} else {
(0, None)
(0, DecodeResult::Empty)
};
}