Compare commits

..
7 Commits
Author SHA1 Message Date
Mauro D 41de06fd4e Thread name parsing. 2021-12-22 15:26:30 +00:00
Mauro D 7792452a88 Thread name parsing support. 2021-12-18 10:55:52 +00:00
Mauro D fdf7075e37 MessageAttachment is now an enum. 2021-12-17 18:20:03 +00:00
Mauro D bbb2979e4b Added get_attachment_name() 2021-12-17 11:58:12 +00:00
Mauro D c29fcdc8bf Nested message parsing improvements. 2021-12-17 11:47:44 +00:00
Mauro D 715fbbab46 Lazy decoding of nested messages. 2021-12-16 15:54:18 +00:00
Mauro D 09ae0216ca Lazy decoding of nested messages. 2021-12-16 15:53:03 +00:00
23 changed files with 1103 additions and 348 deletions
+10
View File
@@ -1,3 +1,13 @@
mail-parser 0.4.2
================================
- Added `Message::get_thread_name()` to obtain the base subject of a message as defined in [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1).
- Added `MimeHeader::get_attachment_name` for simplified access to a MIME attachment file name.
mail-parser 0.4.1
================================
- Lazy parsing of nested e-mail messages.
- Support for base64/quoted-printable nested messages.
mail-parser 0.4.0
================================
- Lazy conversion to/from HTML an plain text parts.
Generated
+1 -1
View File
@@ -59,7 +59,7 @@ checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]]
name = "mail-parser"
version = "0.4.0"
version = "0.4.2"
dependencies = [
"encoding_rs",
"serde",
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust"
version = "0.4.0"
version = "0.4.2"
edition = "2018"
authors = [ "Stalwart Labs <hello@stalw.art>"]
license = "Apache-2.0 OR MIT"
+3 -7
View File
@@ -146,8 +146,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
let nested_message = message
.get_attachment(0)
.unwrap()
.unwrap_message()
.get_body();
.unwrap_message();
assert_eq!(
nested_message.get_subject().unwrap(),
@@ -170,11 +169,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment
.get_content_type()
.unwrap()
.get_attribute("name")
.unwrap(),
nested_attachment.get_attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
@@ -229,6 +224,7 @@ and, to run the benchmarks:
- [RFC 2919 - List-Id: A Structured Field and Namespace for the Identification of Mailing Lists](https://datatracker.ietf.org/doc/html/rfc2919)
- [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339)
- [RFC 8621 - The JSON Meta Application Protocol (JMAP) for Mail (Section 4.1.4)](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4)
- [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1)
## Supported Character Sets
+2 -10
View File
@@ -120,11 +120,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
// Supports nested messages as well as multipart/digest
let nested_message = message
.get_attachment(0)
.unwrap()
.unwrap_message()
.get_body();
let nested_message = message.get_attachment(0).unwrap().unwrap_message();
assert_eq!(
nested_message.get_subject().unwrap(),
@@ -147,11 +143,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment
.get_content_type()
.unwrap()
.get_attribute("name")
.unwrap(),
nested_attachment.get_attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
+12 -10
View File
@@ -63,9 +63,17 @@ fn write_attachments(message: &Message) {
match attachment {
MessagePart::Text(text) | MessagePart::Html(text) => write_part(text),
MessagePart::Binary(blob) | MessagePart::InlineBinary(blob) => write_part(blob),
MessagePart::Message(message) => {
write_part(message);
write_attachments(message.get_body());
MessagePart::Message(attached_message) => {
// Write attachments of nested messages
match &attached_message.body {
MessageAttachment::Parsed(message) => write_attachments(message.as_ref()),
MessageAttachment::Raw(_) => {
write_attachments(&attached_message.parse_raw().unwrap())
}
}
// Write raw message
write_part(attached_message);
}
_ => (),
}
@@ -74,13 +82,7 @@ fn write_attachments(message: &Message) {
fn write_part<'x>(part: &'x impl BodyPart<'x>) {
std::fs::write(
part.get_content_disposition()
.and_then(|cd| cd.get_attribute("filename"))
.unwrap_or_else(|| {
part.get_content_type()
.and_then(|ct| ct.get_attribute("name"))
.unwrap_or("Untitled")
}),
part.get_attachment_name().unwrap_or("Untitled"),
part.get_contents(),
)
.unwrap();
+1 -1
View File
@@ -42,7 +42,7 @@ dependencies = [
[[package]]
name = "mail-parser"
version = "0.2.1"
version = "0.4.2"
dependencies = [
"encoding_rs",
"serde",
+9 -7
View File
@@ -22,11 +22,12 @@ use mail_parser::{
id::parse_id,
list::parse_comma_separared,
raw::{parse_and_ignore, parse_raw},
thread::{thread_name, trim_trailing_fwd},
unstructured::parse_unstructured,
},
mime::*,
header::parse_header_name,
message::MessageStream,
mime::*,
},
Message,
};
@@ -62,7 +63,7 @@ fuzz_target!(|data: &[u8]| {
parse_content_type(&mut stream);
}
9 => {
parse_header_name(&mut stream);
parse_header_name(&data);
}
10 => {
decode_rfc2047(&mut stream, 0);
@@ -113,26 +114,27 @@ fuzz_target!(|data: &[u8]| {
}
}
// Fuzz HTML functions
// 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);
let decoders: &[for<'x> fn(&'x [u8]) -> String] = &[
for decoder in &[
decoder_utf7,
decoder_utf16_le,
decoder_utf16_be,
decoder_utf16,
decoder_iso_8859_1,
];
for decoder in decoders {
] as &[for<'x> fn(&'x [u8]) -> String]
{
decoder(data);
}
+140 -17
View File
@@ -59,6 +59,7 @@
//! - [RFC 2919 - List-Id: A Structured Field and Namespace for the Identification of Mailing Lists](https://datatracker.ietf.org/doc/html/rfc2919)
//! - [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339)
//! - [RFC 8621 - The JSON Meta Application Protocol (JMAP) for Mail (Section 4.1.4)](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4)
//! - [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1)
//!
//! ## Supported Character Sets
//!
@@ -223,8 +224,7 @@
//! let nested_message = message
//! .get_attachment(0)
//! .unwrap()
//! .unwrap_message()
//! .get_body();
//! .unwrap_message();
//!
//! assert_eq!(
//! nested_message.get_subject().unwrap(),
@@ -247,11 +247,7 @@
//!
//! // Full RFC2231 support for continuations and character sets
//! assert_eq!(
//! nested_attachment
//! .get_content_type()
//! .unwrap()
//! .get_attribute("name")
//! .unwrap(),
//! nested_attachment.get_attachment_name().unwrap(),
//! "Book about ☕ tables.gif"
//! );
//!
@@ -266,6 +262,7 @@ pub mod parsers;
use std::{borrow::Cow, collections::HashMap, fmt};
use decoders::html::{html_to_text, text_to_html};
use parsers::fields::thread::thread_name;
#[cfg(feature = "serde_support")]
use serde::{Deserialize, Serialize};
@@ -326,7 +323,7 @@ pub struct Message<'x> {
pub offset_body: usize,
pub offset_end: usize,
#[cfg_attr(feature = "serde_support", serde(skip))]
pub raw_message: &'x [u8],
pub raw_message: Cow<'x, [u8]>,
}
/// Body structure.
@@ -396,7 +393,7 @@ pub enum MessagePart<'x> {
InlineBinary(Part<'x, Cow<'x, [u8]>>),
/// Nested RFC5322 message.
Message(Part<'x, Box<Message<'x>>>),
Message(Part<'x, MessageAttachment<'x>>),
/// Multipart part
Multipart(RfcHeaders<'x>),
@@ -419,9 +416,24 @@ impl<'x> MessagePart<'x> {
}
}
pub fn unwrap_message(&self) -> &Part<'x, Box<Message<'x>>> {
pub fn unwrap_message(&self) -> &Message {
match self {
MessagePart::Message(part) => part,
MessagePart::Message(part) => match &part.body {
MessageAttachment::Parsed(message) => message.as_ref(),
MessageAttachment::Raw(_) => panic!(
"This message part has not been parsed yet, use parse_message() instead."
),
},
_ => panic!("Expected message part."),
}
}
pub fn parse_message(&'x self) -> Option<Message<'x>> {
match self {
MessagePart::Message(part) => match &part.body {
MessageAttachment::Parsed(_) => None,
MessageAttachment::Raw(raw_message) => Message::parse(raw_message.as_ref()),
},
_ => panic!("Expected message part."),
}
}
@@ -873,6 +885,11 @@ impl<'x> Message<'x> {
.and_then(|header| header.as_text_ref())
}
/// Returns the message thread name
pub fn get_thread_name(&self) -> Option<&str> {
thread_name(self.get_subject()?).into()
}
/// Returns the To header field
pub fn get_to(&self) -> &HeaderValue<'x> {
self.headers_rfc
@@ -986,6 +1003,15 @@ pub trait MimeHeaders<'x> {
fn get_content_language(&self) -> &HeaderValue<'x>;
/// Returns the Content-Location field
fn get_content_location(&self) -> Option<&str>;
/// Returns the attachment name, if any.
fn get_attachment_name(&self) -> Option<&str> {
self.get_content_disposition()
.and_then(|cd| cd.get_attribute("filename"))
.or_else(|| {
self.get_content_type()
.and_then(|ct| ct.get_attribute("name"))
})
}
}
impl<'x> MimeHeaders<'x> for Message<'x> {
@@ -1111,13 +1137,16 @@ impl<'x> fmt::Display for Part<'x, Cow<'x, [u8]>> {
}
}
impl<'x> BodyPart<'x> for Part<'x, Box<Message<'x>>> {
impl<'x> BodyPart<'x> for Part<'x, MessageAttachment<'x>> {
fn get_contents(&'x self) -> &'x [u8] {
self.body.raw_message
match &self.body {
MessageAttachment::Parsed(msg) => msg.raw_message.as_ref(),
MessageAttachment::Raw(raw) => raw.as_ref(),
}
}
fn get_text_contents(&'x self) -> &'x str {
std::str::from_utf8(self.body.raw_message).unwrap_or("")
std::str::from_utf8(self.get_contents()).unwrap_or("")
}
fn is_text(&self) -> bool {
@@ -1129,13 +1158,16 @@ impl<'x> BodyPart<'x> for Part<'x, Box<Message<'x>>> {
}
fn len(&self) -> usize {
self.body.raw_message.len()
match &self.body {
MessageAttachment::Parsed(msg) => msg.raw_message.len(),
MessageAttachment::Raw(raw) => raw.len(),
}
}
}
impl<'x> fmt::Display for Part<'x, Box<Message<'x>>> {
impl<'x> fmt::Display for Part<'x, MessageAttachment<'x>> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(String::from_utf8_lossy(self.body.raw_message).as_ref())
fmt.write_str(self.get_text_contents())
}
}
@@ -1264,3 +1296,94 @@ impl<'x> ContentType<'x> {
self.c_type.eq_ignore_ascii_case("inline")
}
}
/// Contents of an e-mail message attachment.
#[derive(Debug, PartialEq)]
pub enum MessageAttachment<'x> {
Parsed(Box<Message<'x>>),
Raw(Cow<'x, [u8]>),
}
impl<'x> Default for MessageAttachment<'x> {
fn default() -> Self {
MessageAttachment::Raw((&[] as &[u8]).into())
}
}
impl<'x> MessageAttachment<'x> {
/// Parse the message attachment and return a `Message` object.
pub fn parse_raw(&'x self) -> Option<Message<'x>> {
if let MessageAttachment::Raw(raw) = self {
Message::parse(raw.as_ref())
} else {
None
}
}
/// Returns a reference to the parsed `Message` object.
pub fn as_ref(&self) -> Option<&Message> {
if let MessageAttachment::Parsed(message) = self {
message.as_ref().into()
} else {
None
}
}
/// Returns ```true``` is the message has been parsed.
/// Call `MessageAttachment::parse_raw` when this method returns ```false```,
/// otherwise use `MessageAttachment::as_ref`.
pub fn is_parsed(&self) -> bool {
matches!(self, MessageAttachment::Parsed(_))
}
/*/// Returns the parsed message if available, otherwise
/// parses the raw message and returns the results.
pub fn unwrap(&'x mut self) -> Option<Message<'x>> {
match self {
MessageAttachment::Parsed(message) => (*std::mem::take(&mut message).unwrap()).into(),
MessageAttachment::Raw(raw) => Message::parse(raw.as_ref()),
}
}*/
}
impl<'x> Part<'x, MessageAttachment<'x>> {
/// Parse the message attachment and return a `Message` object.
pub fn parse_raw(&'x self) -> Option<Message<'x>> {
self.body.parse_raw()
}
/// Returns a reference to the parsed `Message` object.
pub fn as_ref(&self) -> Option<&Message> {
self.body.as_ref()
}
/// Returns ```true``` is the message has been parsed.
/// Call `MessageAttachment::parse_raw` when this method returns ```false```,
/// otherwise use `MessageAttachment::as_ref`.
pub fn is_parsed(&self) -> bool {
self.body.is_parsed()
}
}
impl<'x> Serialize for MessageAttachment<'x> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
MessageAttachment::Parsed(message) => message.serialize(serializer),
MessageAttachment::Raw(raw) => Message::parse(raw.as_ref())
.ok_or_else(|| serde::ser::Error::custom("Failed to parse message attachment."))?
.serialize(serializer),
}
}
}
impl<'x, 'de> Deserialize<'de> for MessageAttachment<'x> {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
panic!("Deserializing message attachments is not supported at this time.")
}
}
+1
View File
@@ -15,4 +15,5 @@ pub mod date;
pub mod id;
pub mod list;
pub mod raw;
pub mod thread;
pub mod unstructured;
+308
View File
@@ -0,0 +1,308 @@
/*
* 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.
*/
static RE_PREFIXES: &[&str] = &[
"re", "res", "sv", "antw", "ref", "aw", "απ", "השב", "vá", "r", "rif", "bls", "odp", "ynt",
"atb", "رد", "回复", "转发",
];
static FWD_PREFIXES: &[&str] = &[
"fwd",
"fw",
"rv",
"enc",
"vs",
"doorst",
"vl",
"tr",
"wg",
"πρθ",
"הועבר",
"továbbítás",
"i",
"fs",
"trs",
"vb",
"pd",
"i̇lt",
"yml",
"إعادة توجيه",
"回覆",
"轉寄",
];
pub fn thread_name(text: &str) -> &str {
let mut token_start = 0;
let mut token_end = 0;
let mut thread_name_start = 0;
let mut fwd_start = 0;
let mut fwd_end = 0;
let mut last_blob_end = 0;
let mut in_blob = false;
let mut in_blob_ignore = false;
let mut seen_header = false;
let mut seen_blob_header = false;
let mut token_found = false;
for (pos, ch) in text.char_indices() {
match ch {
'[' => {
if !in_blob {
if token_found {
if token_end == 0 {
token_end = pos;
}
let prefix = text[token_start..token_end].to_lowercase();
if RE_PREFIXES.contains(&prefix.as_ref())
|| FWD_PREFIXES.contains(&prefix.as_ref())
{
seen_header = true;
} else {
break;
}
}
token_found = false;
in_blob = true;
} else {
break;
}
}
']' if in_blob => {
if seen_blob_header && token_found {
fwd_start = token_start;
fwd_end = pos;
}
if !seen_header {
last_blob_end = pos + 1;
}
in_blob = false;
token_found = false;
seen_blob_header = false;
in_blob_ignore = false;
}
':' if !in_blob => {
if (seen_header && token_found) || (!seen_header && !token_found) {
break;
} else if !seen_header {
if token_end == 0 {
token_end = pos;
}
let prefix = text[token_start..token_end].to_lowercase();
if !RE_PREFIXES.contains(&prefix.as_ref())
&& !FWD_PREFIXES.contains(&prefix.as_ref())
{
break;
}
} else {
seen_header = false;
}
thread_name_start = pos + 1;
token_found = false;
}
':' if in_blob && !in_blob_ignore => {
if token_end == 0 {
token_end = pos;
}
let prefix = text[token_start..token_end].to_lowercase();
if FWD_PREFIXES.contains(&prefix.as_ref()) {
token_found = false;
seen_blob_header = true;
} else if seen_blob_header && RE_PREFIXES.contains(&prefix.as_ref()) {
token_found = false;
} else {
in_blob_ignore = true;
}
}
_ if ch.is_whitespace() => {
if token_end == 0 {
token_end = pos;
}
}
_ => {
if !token_found {
token_start = pos;
token_end = 0;
token_found = true;
} else if !in_blob && pos - token_start > 21 {
break;
}
}
}
}
if last_blob_end > thread_name_start
|| (fwd_start > 0 && last_blob_end > fwd_start && fwd_start > thread_name_start)
{
let result = trim_trailing_fwd(&text[last_blob_end..]);
if !result.is_empty() {
return result;
}
}
if fwd_start > 0 && thread_name_start < fwd_start {
let result = trim_trailing_fwd(&text[fwd_start..fwd_end]);
if !result.is_empty() {
return result;
}
}
trim_trailing_fwd(&text[thread_name_start..])
}
pub fn trim_trailing_fwd(text: &str) -> &str {
let mut in_parentheses = false;
let mut trim_end = true;
let mut end_found = false;
let mut text_start = 0;
let mut text_end = text.len();
let mut fwd_end = 0;
for (pos, ch) in text.char_indices().rev() {
match ch {
'(' if !end_found => {
if in_parentheses {
in_parentheses = false;
if fwd_end - pos > 2
&& FWD_PREFIXES.contains(&text[pos + 1..fwd_end].to_lowercase().as_ref())
{
text_end = pos;
trim_end = true;
continue;
}
}
end_found = true;
}
')' if !end_found => {
if !in_parentheses {
in_parentheses = true;
fwd_end = pos;
} else {
end_found = true;
}
}
_ if ch.is_whitespace() => {
if trim_end {
text_end = pos;
}
continue;
}
_ => {
if !in_parentheses && !end_found {
end_found = true;
}
}
}
if trim_end {
trim_end = false;
}
text_start = pos;
}
if text_end >= text_start {
&text[text_start..text_end]
} else {
""
}
}
#[cfg(test)]
mod tests {
use crate::parsers::fields::thread::{thread_name, trim_trailing_fwd};
#[test]
fn parse_thread_name() {
let tests = [
("re: hello", "hello"),
("re:re: hello", "hello"),
("re:fwd: hello", "hello"),
("fwd[5]:re[5]: hello", "hello"),
("fwd[99]: re[40]: hello", "hello"),
(": hello", ": hello"),
("z: hello", "z: hello"),
("re:: hello", ": hello"),
("[10] hello", "hello"),
("fwd[a]: hello", "hello"),
("re:", ""),
("re::", ":"),
("", ""),
(" ", ""),
("回复: 轉寄: 轉寄", "轉寄"),
("aw[50]: wg: aw[1]: hallo", "hallo"),
("res: rv: enc: továbbítás: ", ""),
("[fwd: hello world]", "hello world"),
("re: enc: re[5]: [fwd: hello world]", "hello world"),
("[fwd: re: fw: hello world]", "hello world"),
("[fwd: hello world]: another text", ": another text"),
("[fwd: re: fwd:] another text", "another text"),
("[hello world]", "[hello world]"),
("re: fwd[9]: [hello world]", "[hello world]"),
("[mailing-list] hello world", "hello world"),
("[mailing-list] re: hello world", "hello world"),
("[mailing-list] wg[8]:re: hello world", "hello world"),
("hello [world]", "hello [world]"),
(" [hello] [world] ", "[hello] [world]"),
("[mailing-list] hello [world]", "hello [world]"),
("[hello [world]", "[hello [world]"),
("[]hello [world]", "hello [world]"),
("[fwd: re: re:] fwd[6]:re: fw:", ""),
("[fwd hello] world hello", "world hello"),
("[fwd: مرحبا بالعالم]", "مرحبا بالعالم"),
("[fwd: hello world] مرحبا بالعالم", "مرحبا بالعالم"),
(" hello world ", "hello world"),
(
"[mailing-list] wg[8]:re: hello world (fwd)(fwd)",
"hello world",
),
("[fwd: re: fw: hello world (fwd)]", "hello world"),
(
"res: rv: enc: továbbítás: hello world (doorst)",
"hello world",
),
("[fwd: re: re: (fwd)] fwd[6]:re: fw: (fwd)", ""),
];
for (input, expected) in tests {
assert_eq!(thread_name(input), expected, "{:?}", input);
}
}
#[test]
fn parse_trail_fwd() {
let tests = [
("hello (fwd)", "hello"),
(" hello (fwd)(fwd)", "hello"),
("hello (wg) (fwd) (fwd)", "hello"),
("(fwd)(fwd)", ""),
("(fwd)hello(fwd)", "(fwd)hello"),
(" hello ", "hello"),
(" hello world ", "hello world"),
("", ""),
(" ", ""),
("hello ()(fwd)", "hello ()"),
("(hello)", "(hello)"),
("hello () (fwd) ()(fwd)", "hello () (fwd) ()"),
(")(", ")("),
(" 你好世界(fwd) ", "你好世界"),
("你好世界 (回覆)", "你好世界"),
("hello(fwd", "hello(fwd"),
("hello(fwd))", "hello(fwd))"),
];
for (input, expected) in tests {
assert_eq!(trim_trailing_fwd(input), expected, "{:?}", input);
}
}
}
-1
View File
@@ -106,7 +106,6 @@ 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;
+144 -141
View File
@@ -16,8 +16,8 @@ use crate::{
base64::decode_base64, charsets::map::get_charset_decoder,
quoted_printable::decode_quoted_printable, DecodeFnc, DecodeResult,
},
ContentType, HeaderName, HeaderValue, Message, MessagePart, MessagePartId, MessageStructure,
Part, RfcHeaders,
ContentType, HeaderName, HeaderValue, Message, MessageAttachment, MessagePart, MessagePartId,
MessageStructure, Part, RfcHeaders,
};
use super::{
@@ -114,6 +114,24 @@ fn get_mime_type(
}
}
#[inline(always)]
fn add_missing_type<'x>(
headers: &mut RfcHeaders<'x>,
c_type: Cow<'x, str>,
c_subtype: Cow<'x, str>,
) {
if headers.is_empty() {
headers.insert(
HeaderName::ContentType,
HeaderValue::ContentType(ContentType {
c_type,
c_subtype: Some(c_subtype),
attributes: None,
}),
);
}
}
#[derive(Default)]
struct MessageParserState {
mime_type: MimeType,
@@ -190,15 +208,12 @@ impl<'x> Message<'x> {
let mut message = Message::new();
let mut message_stack = Vec::new();
let mut message_header_stack = Vec::new();
let mut state = MessageParserState::new();
let mut state_stack = Vec::new();
let mut mime_part_header = RfcHeaders::new();
message.raw_message = raw_message;
'outer: loop {
// Parse headers
let (is_message, header) = if let MimeType::Message = state.mime_type {
@@ -253,16 +268,7 @@ impl<'x> Message<'x> {
..Default::default()
};
if !is_message {
if mime_part_header.is_empty() {
mime_part_header.insert(
HeaderName::ContentType,
HeaderValue::ContentType(ContentType {
c_type: "text".into(),
c_subtype: Some("plain".into()),
attributes: None,
}),
);
}
add_missing_type(&mut mime_part_header, "text".into(), "plain".into());
message.parts.push(MessagePart::Multipart(std::mem::take(
&mut mime_part_header,
)));
@@ -276,31 +282,6 @@ impl<'x> Message<'x> {
is_text = true;
}
}
} else if mime_type == MimeType::Message {
let new_state = MessageParserState {
mime_type: MimeType::Message,
mime_boundary: state.mime_boundary.take(),
need_html_body: true,
need_text_body: true,
..Default::default()
};
if mime_part_header.is_empty() {
mime_part_header.insert(
HeaderName::ContentType,
HeaderValue::ContentType(ContentType {
c_type: "message".into(),
c_subtype: Some("rfc822".into()),
attributes: None,
}),
);
}
message_header_stack.push(std::mem::take(&mut mime_part_header));
message_stack.push(message);
state_stack.push(state);
message = Message::new();
state = new_state;
skip_crlf(&mut stream);
continue;
}
skip_crlf(&mut stream);
@@ -319,6 +300,26 @@ impl<'x> Message<'x> {
_ => (true, get_bytes_to_boundary),
};
state
.structure
.push(MessageStructure::Part(message.parts.len()));
if is_binary && mime_type == MimeType::Message {
let new_state = MessageParserState {
mime_type: MimeType::Message,
mime_boundary: state.mime_boundary.take(),
need_html_body: true,
need_text_body: true,
..Default::default()
};
add_missing_type(&mut mime_part_header, "message".into(), "rfc822".into());
message_stack.push((message, std::mem::take(&mut mime_part_header)));
state_stack.push(state);
message = Message::new();
state = new_state;
continue;
}
let (bytes_read, mut bytes) = decode_fnc(
&stream,
stream.pos,
@@ -332,6 +333,7 @@ impl<'x> Message<'x> {
// Attempt to recover contents of an invalid message
if bytes_read == 0 {
if stream.pos >= stream.data.len() || (is_binary && state.mime_boundary.is_none()) {
state.structure.pop();
break;
}
@@ -359,9 +361,11 @@ impl<'x> Message<'x> {
bytes = r_bytes;
stream.pos += bytes_read;
} else {
state.structure.pop();
break;
}
} else {
state.structure.pop();
break;
}
} else {
@@ -375,92 +379,96 @@ impl<'x> Message<'x> {
stream.pos += bytes_read;
}
let is_inline = is_inline
&& header
.get(&HeaderName::ContentDisposition)
.map_or_else(|| true, |d| !d.get_content_type().is_attachment())
&& (state.parts == 1
|| (state.mime_type != MimeType::MultipartRelated
&& (mime_type == MimeType::Inline
|| content_type.map_or_else(|| true, |c| !c.has_attribute("name")))));
if mime_type != MimeType::Message {
let is_inline = is_inline
&& header
.get(&HeaderName::ContentDisposition)
.map_or_else(|| true, |d| !d.get_content_type().is_attachment())
&& (state.parts == 1
|| (state.mime_type != MimeType::MultipartRelated
&& (mime_type == MimeType::Inline
|| content_type
.map_or_else(|| true, |c| !c.has_attribute("name")))));
let (add_to_html, add_to_text) = if let MimeType::MultipartAlernative = state.mime_type
{
match mime_type {
MimeType::TextHtml => (true, false),
MimeType::TextPlain => (false, true),
_ => (false, false),
}
} else if is_inline {
if state.in_alternative && (state.need_text_body || state.need_html_body) {
match mime_type {
MimeType::TextHtml => {
state.need_text_body = false;
let (add_to_html, add_to_text) =
if let MimeType::MultipartAlernative = state.mime_type {
match mime_type {
MimeType::TextHtml => (true, false),
MimeType::TextPlain => (false, true),
_ => (false, false),
}
MimeType::TextPlain => {
state.need_html_body = false;
} else if is_inline {
if state.in_alternative && (state.need_text_body || state.need_html_body) {
match mime_type {
MimeType::TextHtml => {
state.need_text_body = false;
}
MimeType::TextPlain => {
state.need_html_body = false;
}
_ => (),
}
}
_ => (),
(state.need_html_body, state.need_text_body)
} else {
(false, false)
};
if is_text {
let is_html = mime_type == MimeType::TextHtml;
let text_part = Part {
body: result_to_string(bytes, stream.data, content_type),
headers: std::mem::take(&mut mime_part_header),
};
if add_to_html && !is_html {
message.html_body.push(message.parts.len());
} else if add_to_text && is_html {
message.text_body.push(message.parts.len());
}
}
(state.need_html_body, state.need_text_body)
} else {
(false, false)
};
if is_text {
let is_html = mime_type == MimeType::TextHtml;
let text_part = Part {
body: result_to_string(bytes, stream.data, content_type),
headers: std::mem::take(&mut mime_part_header),
};
if add_to_html && is_html {
message.html_body.push(message.parts.len());
} else if add_to_text && !is_html {
message.text_body.push(message.parts.len());
} else {
message.attachments.push(message.parts.len());
}
if add_to_html && !is_html {
message.html_body.push(message.parts.len());
} else if add_to_text && is_html {
message.text_body.push(message.parts.len());
}
if add_to_html && is_html {
message.html_body.push(message.parts.len());
} else if add_to_text && !is_html {
message.text_body.push(message.parts.len());
message.parts.push(if is_html {
MessagePart::Html(text_part)
} else {
MessagePart::Text(text_part)
});
} else {
if add_to_html {
message.html_body.push(message.parts.len());
}
if add_to_text {
message.text_body.push(message.parts.len());
}
message.attachments.push(message.parts.len());
}
state
.structure
.push(MessageStructure::Part(message.parts.len()));
message.parts.push(if is_html {
MessagePart::Html(text_part)
} else {
MessagePart::Text(text_part)
});
let binary_part = Part::new(
std::mem::take(&mut mime_part_header),
result_to_bytes(bytes, stream.data),
);
message.parts.push(if !is_inline {
MessagePart::Binary(binary_part)
} else {
MessagePart::InlineBinary(binary_part)
});
};
} else {
if add_to_html {
message.html_body.push(message.parts.len());
}
if add_to_text {
message.text_body.push(message.parts.len());
}
add_missing_type(&mut mime_part_header, "message".into(), "rfc822".into());
message.attachments.push(message.parts.len());
state
.structure
.push(MessageStructure::Part(message.parts.len()));
let binary_part = Part::new(
message.parts.push(MessagePart::Message(Part::new(
std::mem::take(&mut mime_part_header),
result_to_bytes(bytes, stream.data),
);
message.parts.push(if !is_inline {
MessagePart::Binary(binary_part)
} else {
MessagePart::InlineBinary(binary_part)
});
};
MessageAttachment::Raw(result_to_bytes(bytes, stream.data)),
)));
}
if state.mime_boundary.is_some() {
// Currently processing a MIME part
@@ -469,17 +477,17 @@ impl<'x> Message<'x> {
'inner: loop {
if let MimeType::Message = state.mime_type {
// Finished processing nested message, restore parent message from stack
if let (Some(mut prev_message), Some(mut prev_state)) =
if let (Some((mut prev_message, headers)), Some(mut prev_state)) =
(message_stack.pop(), state_stack.pop())
{
message.structure = state.get_structure();
message.offset_end = seek_crlf_end(&stream, last_part_offset);
message.raw_message =
&raw_message[message.offset_header..message.offset_end];
raw_message[message.offset_header..message.offset_end].into();
prev_message.attachments.push(prev_message.parts.len());
prev_message.parts.push(MessagePart::Message(Part::new(
message_header_stack.pop().unwrap(),
Box::new(message),
headers,
MessageAttachment::Parsed(Box::new(message)),
)));
message = prev_message;
prev_state.mime_boundary = state.mime_boundary;
@@ -543,22 +551,24 @@ impl<'x> Message<'x> {
}
}
while let (Some(mut prev_message), Some(prev_state)) =
while let (Some((mut prev_message, headers)), Some(prev_state)) =
(message_stack.pop(), state_stack.pop())
{
message.offset_end = stream.pos;
if !message.is_empty() {
message.structure = state.get_structure();
message.raw_message = raw_message[message.offset_header..message.offset_end].into();
prev_message.attachments.push(prev_message.parts.len());
prev_message.parts.push(MessagePart::Message(Part::new(
message_header_stack.pop().unwrap(),
Box::new(message),
headers,
MessageAttachment::Parsed(Box::new(message)),
)));
}
message = prev_message;
state = prev_state;
}
message.raw_message = raw_message.into();
message.structure = state.get_structure();
message.offset_end = stream.pos;
@@ -573,7 +583,9 @@ impl<'x> Message<'x> {
mod tests {
use std::{fs, path::PathBuf};
use crate::{parsers::message::Message, MessagePart};
use serde_json::Value;
use crate::parsers::message::Message;
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----\n".as_bytes();
@@ -608,27 +620,18 @@ mod tests {
tests_run += 1;
let input = input.split_at_mut(pos);
let mut message = Message::parse(input.0).unwrap();
// Remove raw message references before comparing
message.raw_message = &[];
for parts in &mut message.parts {
if let MessagePart::Message(part) = parts {
part.body.raw_message = &[];
for parts in &mut part.body.parts {
if let MessagePart::Message(part) = parts {
part.body.raw_message = &[];
}
}
}
}
let message = Message::parse(input.0).unwrap();
let json_message = serde_json::to_string_pretty(&message).unwrap();
assert_eq!(
message,
serde_json::from_slice::<Message>(&input.1[SEPARATOR.len()..]).unwrap(),
serde_json::from_str::<Value>(&json_message).unwrap(),
serde_json::from_str::<Value>(
std::str::from_utf8(&input.1[SEPARATOR.len()..]).unwrap()
)
.unwrap(),
"Test failed for '{}', result was:\n{}",
file_name.display(),
serde_json::to_string_pretty(&message).unwrap()
json_message
);
}
}
@@ -646,7 +649,7 @@ mod tests {
let mut file_name = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
file_name.push("tests");
file_name.push("rfc");
file_name.push("007.txt");
file_name.push("003.txt");
let mut input = fs::read(&file_name).unwrap();
let mut pos = 0;
+2 -10
View File
@@ -112,11 +112,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
" “importing”,\nbut then I thought, why not do both? ☺\n"
)
);
let nested_message = message
.get_attachment(0)
.unwrap()
.unwrap_message()
.get_body();
let nested_message = message.get_attachment(0).unwrap().unwrap_message();
assert_eq!(
nested_message.get_subject().unwrap(),
"Exporting my book about coffee tables"
@@ -132,11 +128,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
let nested_attachment = nested_message.get_attachment(0).unwrap().unwrap_binary();
assert_eq!(nested_attachment.len(), 42);
assert_eq!(
nested_attachment
.get_content_type()
.unwrap()
.get_attribute("name")
.unwrap(),
nested_attachment.get_attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
+2 -2
View File
@@ -113,7 +113,7 @@ Content-Type: text/plain
}
],
"structure": {
"List": []
"Part": 0
},
"offset_header": 30,
"offset_body": 60,
@@ -123,7 +123,7 @@ Content-Type: text/plain
}
],
"structure": {
"List": []
"Part": 0
},
"offset_header": 0,
"offset_body": 30,
+8 -1
View File
@@ -163,7 +163,14 @@ Content-Type: text/plain
"structure": {
"MultiPart": [
0,
[]
[
{
"Part": 1
},
{
"Part": 2
}
]
]
},
"offset_header": 0,
+22 -19
View File
@@ -74,9 +74,6 @@ Content-Transfer-Encoding: Quoted-printable
---- EXPECTED STRUCTURE ----
{
"headers_rfc": {
"subject": {
"Text": "A multipart example"
},
"content_type": {
"ContentType": {
"c_type": "multipart",
@@ -86,14 +83,23 @@ Content-Transfer-Encoding: Quoted-printable
}
}
},
"mime_version": {
"Text": "1.0"
},
"to": {
"Address": {
"name": "Ned Freed",
"address": "ned@innosoft.com"
}
},
"mime_version": {
"Text": "1.0"
"from": {
"Address": {
"name": "Nathaniel Borenstein",
"address": "nsb@nsb.fv.com"
}
},
"subject": {
"Text": "A multipart example"
},
"date": {
"DateTime": {
@@ -107,12 +113,6 @@ Content-Transfer-Encoding: Quoted-printable
"tz_hour": 7,
"tz_minute": 0
}
},
"from": {
"Address": {
"name": "Nathaniel Borenstein",
"address": "nsb@nsb.fv.com"
}
}
},
"headers_offsets": [
@@ -211,14 +211,14 @@ Content-Transfer-Encoding: Quoted-printable
{
"Text": {
"headers": {
"content_transfer_encoding": {
"Text": "base64"
},
"content_type": {
"ContentType": {
"c_type": "audio",
"c_subtype": "basic"
}
},
"content_transfer_encoding": {
"Text": "base64"
}
},
"body": "... base64-encoded 8000 Hz single-channel\n mu-law-format audio data goes here ...\n"
@@ -265,11 +265,6 @@ Content-Transfer-Encoding: Quoted-printable
},
"body": {
"headers_rfc": {
"from": {
"Address": {
"name": "mailbox in US-ASCII"
}
},
"to": {
"Address": {
"name": "address in US-ASCII"
@@ -284,6 +279,11 @@ Content-Transfer-Encoding: Quoted-printable
}
}
},
"from": {
"Address": {
"name": "mailbox in US-ASCII"
}
},
"content_transfer_encoding": {
"Text": "Quoted-printable"
},
@@ -374,6 +374,9 @@ Content-Transfer-Encoding: Quoted-printable
},
{
"Part": 5
},
{
"Part": 6
}
]
},
+57 -50
View File
@@ -74,15 +74,6 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
---- EXPECTED STRUCTURE ----
{
"headers_rfc": {
"subject": {
"Text": "[Fwd: Map of Argentina with Description]"
},
"from": {
"Address": {
"name": "Al Gore",
"address": "vice-president@whitehouse.gov"
}
},
"content_type": {
"ContentType": {
"c_type": "multipart",
@@ -92,11 +83,20 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
}
}
},
"from": {
"Address": {
"name": "Al Gore",
"address": "vice-president@whitehouse.gov"
}
},
"to": {
"Address": {
"name": "White House Transportation Coordinator",
"address": "transport@whitehouse.gov"
}
},
"subject": {
"Text": "[Fwd: Map of Argentina with Description]"
}
},
"headers_offsets": [
@@ -142,6 +142,9 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
{
"Text": {
"headers": {
"content_transfer_encoding": {
"Text": "7bit"
},
"content_type": {
"ContentType": {
"c_type": "text",
@@ -150,9 +153,6 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
"charset": "us-ascii"
}
}
},
"content_transfer_encoding": {
"Text": "7bit"
}
},
"body": "Fred,\n\nFire up Air Force One! We're going South!\n\nThanks,\nAl"
@@ -164,28 +164,22 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
"content_transfer_encoding": {
"Text": "7bit"
},
"content_disposition": {
"ContentType": {
"c_type": "inline"
}
},
"content_type": {
"ContentType": {
"c_type": "message",
"c_subtype": "rfc822"
}
},
"content_disposition": {
"ContentType": {
"c_type": "inline"
}
}
},
"body": {
"headers_rfc": {
"content_type": {
"ContentType": {
"c_type": "multipart",
"c_subtype": "mixed",
"attributes": {
"boundary": "DC8------------DC8638F443D87A7F0726DEF7"
}
}
"return_path": {
"Text": "president@whitehouse.gov"
},
"message_id": {
"Text": "199804130742.RAA20366@mai1host.whitehouse.gov"
@@ -193,25 +187,6 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
"subject": {
"Text": "Map of Argentina with Description"
},
"from": {
"Address": {
"name": "Bill Clinton",
"address": "president@whitehouse.gov"
}
},
"return_path": {
"Text": "president@whitehouse.gov"
},
"received": {
"Collection": [
{
"Text": "from mailhost.whitehouse.gov ([192.168.51.200])\n by heartbeat.whitehouse.gov (8.8.8/8.8.8) with ESMTP id SAA22453\n for <vice-president@heartbeat.whitehouse.gov>;\n Mon, 13 Aug 1998 l8:14:23 +1000"
},
{
"Text": "from the_big_box.whitehouse.gov ([192.168.51.50])\n by mailhost.whitehouse.gov (8.8.8/8.8.7) with ESMTP id RAA20366\n for vice-president@whitehouse.gov; Mon, 13 Aug 1998 17:42:41 +1000"
}
]
},
"date": {
"DateTime": {
"year": 1998,
@@ -225,14 +200,39 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
"tz_minute": 0
}
},
"mime_version": {
"Text": "1.0"
"received": {
"Collection": [
{
"Text": "from mailhost.whitehouse.gov ([192.168.51.200])\n by heartbeat.whitehouse.gov (8.8.8/8.8.8) with ESMTP id SAA22453\n for <vice-president@heartbeat.whitehouse.gov>;\n Mon, 13 Aug 1998 l8:14:23 +1000"
},
{
"Text": "from the_big_box.whitehouse.gov ([192.168.51.50])\n by mailhost.whitehouse.gov (8.8.8/8.8.7) with ESMTP id RAA20366\n for vice-president@whitehouse.gov; Mon, 13 Aug 1998 17:42:41 +1000"
}
]
},
"content_type": {
"ContentType": {
"c_type": "multipart",
"c_subtype": "mixed",
"attributes": {
"boundary": "DC8------------DC8638F443D87A7F0726DEF7"
}
}
},
"to": {
"Address": {
"name": "A1 Gore (The Enforcer)",
"address": "vice-president@whitehouse.gov"
}
},
"from": {
"Address": {
"name": "Bill Clinton",
"address": "president@whitehouse.gov"
}
},
"mime_version": {
"Text": "1.0"
}
},
"headers_offsets": [
@@ -341,6 +341,9 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
{
"InlineBinary": {
"headers": {
"content_transfer_encoding": {
"Text": "base64"
},
"content_disposition": {
"ContentType": {
"c_type": "inline",
@@ -357,9 +360,6 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
"name": "map_of_Argentina.gif"
}
}
},
"content_transfer_encoding": {
"Text": "base64"
}
},
"body": [
@@ -673,7 +673,14 @@ U6ZGxseyk8SasGw3J9GRzdTQky1iHNvcPNNI4TLeKdfMvy0vMqLrItvuxfDW8ubjueDtJufz
}
],
"structure": {
"Part": 0
"List": [
{
"Part": 0
},
{
"Part": 1
}
]
},
"offset_header": 0,
"offset_body": 270,
+38 -31
View File
@@ -37,11 +37,31 @@ Subject: my different opinion
---- EXPECTED STRUCTURE ----
{
"headers_rfc": {
"mime_version": {
"Text": "1.0"
},
"content_type": {
"ContentType": {
"c_type": "multipart",
"c_subtype": "mixed",
"attributes": {
"boundary": "---- main boundary ----"
}
}
},
"subject": {
"Text": "Internet Digest, volume 42"
},
"from": {
"Address": {
"name": "Moderator-Address"
}
},
"to": {
"Address": {
"name": "Recipient-List"
}
},
"date": {
"DateTime": {
"year": 1994,
@@ -54,26 +74,6 @@ Subject: my different opinion
"tz_hour": 0,
"tz_minute": 0
}
},
"mime_version": {
"Text": "1.0"
},
"to": {
"Address": {
"name": "Recipient-List"
}
},
"content_type": {
"ContentType": {
"c_type": "multipart",
"c_subtype": "mixed",
"attributes": {
"boundary": "---- main boundary ----"
}
}
},
"subject": {
"Text": "Internet Digest, volume 42"
}
},
"headers_offsets": [
@@ -161,6 +161,11 @@ Subject: my different opinion
},
"body": {
"headers_rfc": {
"from": {
"Address": {
"name": "someone-else"
}
},
"date": {
"DateTime": {
"year": 1993,
@@ -176,11 +181,6 @@ Subject: my different opinion
},
"subject": {
"Text": "my opinion"
},
"from": {
"Address": {
"name": "someone-else"
}
}
},
"headers_offsets": [
@@ -240,11 +240,6 @@ Subject: my different opinion
},
"body": {
"headers_rfc": {
"from": {
"Address": {
"name": "someone-else-again"
}
},
"date": {
"DateTime": {
"year": 1993,
@@ -260,6 +255,11 @@ Subject: my different opinion
},
"subject": {
"Text": "my different opinion"
},
"from": {
"Address": {
"name": "someone-else-again"
}
}
},
"headers_offsets": [
@@ -316,7 +316,14 @@ Subject: my different opinion
{
"MultiPart": [
1,
[]
[
{
"Part": 2
},
{
"Part": 3
}
]
]
}
]
+18 -15
View File
@@ -201,16 +201,16 @@ K
{
"InlineBinary": {
"headers": {
"content_disposition": {
"ContentType": {
"c_type": "inline"
}
},
"content_type": {
"ContentType": {
"c_type": "image",
"c_subtype": "jpeg"
}
},
"content_disposition": {
"ContentType": {
"c_type": "inline"
}
}
},
"body": [
@@ -280,16 +280,16 @@ K
{
"Binary": {
"headers": {
"content_disposition": {
"ContentType": {
"c_type": "attachment"
}
},
"content_type": {
"ContentType": {
"c_type": "image",
"c_subtype": "jpeg"
}
},
"content_disposition": {
"ContentType": {
"c_type": "attachment"
}
}
},
"body": [
@@ -362,16 +362,16 @@ K
{
"Text": {
"headers": {
"content_disposition": {
"ContentType": {
"c_type": "inline"
}
},
"content_type": {
"ContentType": {
"c_type": "text",
"c_subtype": "plain"
}
},
"content_disposition": {
"ContentType": {
"c_type": "inline"
}
}
},
"body": "K"
@@ -428,6 +428,9 @@ K
},
{
"Part": 11
},
{
"Part": 12
}
]
]
+287
View File
@@ -0,0 +1,287 @@
Content-Type: multipart/mixed;
boundary=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
This is a message with a base64 encoded attached email
--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Content-Disposition: attachment; filename="attached_email.eml"
Content-Type: message/rfc822
Content-Transfer-Encoding: base64
VG86ICJlbWFpbEBleGFtcGxlLmNvbSIgPGVtYWlsQGV4YW1wbGUuY29tPg0KRnJvbTogTmFtZSA8
ZW1haWxAZXhhbXBsZS5jb20+DQpTdWJqZWN0OiBIVE1MIHRlc3QNCk1lc3NhZ2UtSUQ6IDxyYW5k
b20tbWVzc2FnZS1pZEBleGFtcGxlLmNvbT4NCkRhdGU6IFR1ZSwgMTQgRGVjIDIwMjEgMTE6NDg6
MjUgKzAxMDANCk1JTUUtVmVyc2lvbjogMS4wDQpDb250ZW50LVR5cGU6IG11bHRpcGFydC9hbHRl
cm5hdGl2ZTsNCiBib3VuZGFyeT0iYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYSINCkNvbnRlbnQtTGFuZ3VhZ2U6IGVuLVVTDQoNClRoaXMgaXMgYSBtdWx0aS1wYXJ0IG1l
c3NhZ2UgaW4gTUlNRSBmb3JtYXQuDQotLWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWENCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbjsgY2hhcnNldD11dGYtODsgZm9ybWF0
PWZsb3dlZA0KQ29udGVudC1UcmFuc2Zlci1FbmNvZGluZzogN2JpdA0KDQpUaGlzIGlzIGFuICpI
VE1MKiB0ZXN0IG1lc3NhZ2UNCi0tYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYQ0KQ29udGVudC1UeXBlOiB0ZXh0L2h0bWw7IGNoYXJzZXQ9dXRmLTgNCkNvbnRlbnQtVHJh
bnNmZXItRW5jb2Rpbmc6IDdiaXQNCg0KPGh0bWw+DQogIDxoZWFkPg0KICAgIDxtZXRhIGh0dHAt
ZXF1aXY9ImNvbnRlbnQtdHlwZSIgY29udGVudD0idGV4dC9odG1sOyBjaGFyc2V0PVVURi04Ij4N
CiAgPC9oZWFkPg0KICA8Ym9keT4NCiAgICBUaGlzIGlzIGFuIDxiPkhUTUw8L2I+IHRlc3QgbWVz
c2FnZQ0KICA8L2JvZHk+DQo8L2h0bWw+DQoNCi0tYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh
YWFhYWFhYWFhYWFhYS0tDQo=
--bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb--
---- EXPECTED STRUCTURE ----
{
"headers_rfc": {
"content_type": {
"ContentType": {
"c_type": "multipart",
"c_subtype": "mixed",
"attributes": {
"boundary": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
}
}
}
},
"headers_offsets": [
{
"name": {
"Rfc": "content_type"
},
"start": 13,
"end": 82
}
],
"html_body": [
0
],
"text_body": [
0
],
"attachments": [
1
],
"parts": [
{
"Text": {
"headers": {
"content_transfer_encoding": {
"Text": "7bit"
},
"content_type": {
"ContentType": {
"c_type": "text",
"c_subtype": "plain",
"attributes": {
"charset": "utf-8"
}
}
}
},
"body": "This is a message with a base64 encoded attached email"
}
},
{
"Message": {
"headers": {
"content_disposition": {
"ContentType": {
"c_type": "attachment",
"attributes": {
"filename": "attached_email.eml"
}
}
},
"content_type": {
"ContentType": {
"c_type": "message",
"c_subtype": "rfc822"
}
},
"content_transfer_encoding": {
"Text": "base64"
}
},
"body": {
"headers_rfc": {
"subject": {
"Text": "HTML test"
},
"to": {
"Address": {
"name": "email@example.com",
"address": "email@example.com"
}
},
"content_type": {
"ContentType": {
"c_type": "multipart",
"c_subtype": "alternative",
"attributes": {
"boundary": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
}
},
"from": {
"Address": {
"name": "Name",
"address": "email@example.com"
}
},
"content_language": {
"Text": "en-US"
},
"date": {
"DateTime": {
"year": 2021,
"month": 12,
"day": 14,
"hour": 11,
"minute": 48,
"second": 25,
"tz_before_gmt": false,
"tz_hour": 1,
"tz_minute": 0
}
},
"message_id": {
"Text": "random-message-id@example.com"
},
"mime_version": {
"Text": "1.0"
}
},
"headers_offsets": [
{
"name": {
"Rfc": "to"
},
"start": 3,
"end": 45
},
{
"name": {
"Rfc": "from"
},
"start": 50,
"end": 77
},
{
"name": {
"Rfc": "subject"
},
"start": 85,
"end": 97
},
{
"name": {
"Rfc": "message_id"
},
"start": 108,
"end": 142
},
{
"name": {
"Rfc": "date"
},
"start": 147,
"end": 181
},
{
"name": {
"Rfc": "mime_version"
},
"start": 194,
"end": 200
},
{
"name": {
"Rfc": "content_type"
},
"start": 213,
"end": 292
},
{
"name": {
"Rfc": "content_language"
},
"start": 309,
"end": 317
}
],
"html_body": [
1
],
"text_body": [
0
],
"parts": [
{
"Text": {
"headers": {
"content_type": {
"ContentType": {
"c_type": "text",
"c_subtype": "plain",
"attributes": {
"charset": "utf-8",
"format": "flowed"
}
}
},
"content_transfer_encoding": {
"Text": "7bit"
}
},
"body": "This is an *HTML* test message\r"
}
},
{
"Html": {
"headers": {
"content_type": {
"ContentType": {
"c_type": "text",
"c_subtype": "html",
"attributes": {
"charset": "utf-8"
}
}
},
"content_transfer_encoding": {
"Text": "7bit"
}
},
"body": "<html>\r\n <head>\r\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\r\n </head>\r\n <body>\r\n This is an <b>HTML</b> test message\r\n </body>\r\n</html>\r\n\r"
}
}
],
"structure": {
"List": [
{
"Part": 0
},
{
"Part": 1
}
]
},
"offset_header": 0,
"offset_body": 319,
"offset_end": 870
}
}
}
],
"structure": {
"List": [
{
"Part": 0
},
{
"Part": 1
}
]
},
"offset_header": 0,
"offset_body": 83,
"offset_end": 1648
}
+23 -13
View File
@@ -145,14 +145,14 @@ Foobar
},
"body": {
"headers_rfc": {
"subject": {
"Text": "i disagree"
},
"from": {
"Address": {
"name": "another one",
"address": "another@one"
}
},
"subject": {
"Text": "i disagree"
}
},
"headers_offsets": [
@@ -205,6 +205,12 @@ Foobar
},
"body": {
"headers_rfc": {
"from": {
"Address": {
"name": "attachment",
"address": "attachment@user"
}
},
"subject": {
"Text": "funny hat"
},
@@ -216,12 +222,6 @@ Foobar
"boundary": "2"
}
}
},
"from": {
"Address": {
"name": "attachment",
"address": "attachment@user"
}
}
},
"headers_offsets": [
@@ -260,14 +260,14 @@ Foobar
{
"Text": {
"headers": {
"content_transfer_encoding": {
"Text": "binary"
},
"content_type": {
"ContentType": {
"c_type": "text",
"c_subtype": "plain"
}
},
"content_transfer_encoding": {
"Text": "binary"
}
},
"body": "Lovely attachment for you"
@@ -319,7 +319,17 @@ Foobar
}
],
"structure": {
"List": []
"List": [
{
"Part": 0
},
{
"Part": 1
},
{
"Part": 2
}
]
},
"offset_header": 0,
"offset_body": 82,
+14 -11
View File
@@ -58,10 +58,8 @@ Root MIME epilogue
---- EXPECTED STRUCTURE ----
{
"headers_rfc": {
"from": {
"Address": {
"address": "user@domain.org"
}
"mime_version": {
"Text": "1.0"
},
"content_type": {
"ContentType": {
@@ -72,8 +70,10 @@ Root MIME epilogue
}
}
},
"mime_version": {
"Text": "1.0"
"from": {
"Address": {
"address": "user@domain.org"
}
},
"date": {
"DateTime": {
@@ -170,11 +170,6 @@ Root MIME epilogue
},
"body": {
"headers_rfc": {
"from": {
"Address": {
"address": "sub@domain.org"
}
},
"subject": {
"Text": "submsg"
},
@@ -191,6 +186,11 @@ Root MIME epilogue
"tz_minute": 0
}
},
"from": {
"Address": {
"address": "sub@domain.org"
}
},
"content_type": {
"ContentType": {
"c_type": "multipart",
@@ -351,6 +351,9 @@ Root MIME epilogue
{
"Part": 0
},
{
"Part": 1
},
{
"Part": 2
}