diff --git a/examples/export_to_json_and_yaml.rs b/examples/export_to_json_and_yaml.rs
index cb04686..257110f 100644
--- a/examples/export_to_json_and_yaml.rs
+++ b/examples/export_to_json_and_yaml.rs
@@ -112,7 +112,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
);
// Supports nested messages as well as multipart/digest
- let nested_message = message.get_attachment(0).unwrap().unwrap_message();
+ let nested_message = message.get_attachment(0).unwrap().get_message().unwrap();
assert_eq!(
nested_message.get_subject().unwrap(),
@@ -129,7 +129,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
"
ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
- let nested_attachment = nested_message.get_attachment(0).unwrap().unwrap_binary();
+ let nested_attachment = nested_message.get_attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);
diff --git a/examples/write_attachments.rs b/examples/write_attachments.rs
index 0a86f52..ccab369 100644
--- a/examples/write_attachments.rs
+++ b/examples/write_attachments.rs
@@ -60,30 +60,14 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
fn write_attachments(message: &Message) {
for attachment in message.get_attachments() {
- match attachment {
- MessagePart::Text(text) | MessagePart::Html(text) => write_part(text),
- MessagePart::Binary(blob) | MessagePart::InlineBinary(blob) => write_part(blob),
- 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);
- }
- _ => (),
+ if !attachment.is_message() {
+ std::fs::write(
+ attachment.get_attachment_name().unwrap_or("Untitled"),
+ attachment.get_contents(),
+ )
+ .unwrap();
+ } else {
+ write_attachments(&attachment.get_message().unwrap());
}
}
}
-
-fn write_part<'x>(part: &'x impl BodyPart<'x>) {
- std::fs::write(
- part.get_attachment_name().unwrap_or("Untitled"),
- part.get_contents(),
- )
- .unwrap();
-}
diff --git a/src/lib.rs b/src/lib.rs
index 97a58af..c84d213 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -266,14 +266,9 @@ use parsers::{
use serde::{Deserialize, Serialize};
/// An RFC5322/RFC822 message.
-#[derive(Debug, Default, PartialEq)]
+#[derive(Debug, Default, PartialEq, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Message<'x> {
- #[cfg_attr(feature = "serde_support", serde(default))]
- pub headers_rfc: RfcHeaders<'x>,
- #[cfg_attr(feature = "serde_support", serde(default))]
- pub headers_raw: RawHeaders<'x>,
-
#[cfg_attr(feature = "serde_support", serde(default))]
pub html_body: Vec,
#[cfg_attr(feature = "serde_support", serde(default))]
@@ -285,60 +280,23 @@ pub struct Message<'x> {
#[cfg_attr(feature = "serde_support", serde(borrow))]
pub parts: Vec>,
- #[cfg_attr(feature = "serde_support", serde(default))]
- pub structure: MessageStructure,
-
- pub offset_header: usize,
- pub offset_body: usize,
- pub offset_end: usize,
#[cfg_attr(feature = "serde_support", serde(skip))]
pub raw_message: Cow<'x, [u8]>,
}
-/// Body structure.
-#[derive(Debug, PartialEq)]
+/// MIME Message Part
+#[derive(Debug, PartialEq, Default, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
-pub enum MessageStructure {
- Part(MessagePartId),
- List(Vec),
- MultiPart((MessagePartId, Vec)),
-}
-
-impl Default for MessageStructure {
- fn default() -> Self {
- MessageStructure::Part(0)
- }
-}
-
-/// Part of the message.
-#[derive(Debug, Default, PartialEq)]
-#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
-pub struct Part<'x, T> {
+pub struct MessagePart<'x> {
#[cfg_attr(feature = "serde_support", serde(default))]
pub headers_rfc: RfcHeaders<'x>,
#[cfg_attr(feature = "serde_support", serde(default))]
+ #[cfg_attr(feature = "serde_support", serde(skip))]
pub headers_raw: RawHeaders<'x>,
pub is_encoding_problem: bool,
- pub body: T,
- pub offset_header: usize,
- pub offset_body: usize,
- pub offset_end: usize,
-}
-
-impl<'x, T> Part<'x, T> {
- pub fn get_body(&self) -> &T {
- &self.body
- }
-}
-
-/// Multipart part
-#[derive(Debug, Default, PartialEq)]
-#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
-pub struct MultiPart<'x> {
#[cfg_attr(feature = "serde_support", serde(default))]
- pub headers_rfc: RfcHeaders<'x>,
- #[cfg_attr(feature = "serde_support", serde(default))]
- pub headers_raw: RawHeaders<'x>,
+ #[cfg_attr(feature = "serde_support", serde(borrow))]
+ pub body: PartType<'x>,
pub offset_header: usize,
pub offset_body: usize,
pub offset_end: usize,
@@ -354,85 +312,38 @@ pub type MessagePartId = usize;
/// - Message: Nested RFC5322 message.
/// - MultiPart: Multipart part.
///
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
-pub enum MessagePart<'x> {
+pub enum PartType<'x> {
/// Any text/* part
- Text(Part<'x, Cow<'x, str>>),
+ Text(Cow<'x, str>),
/// A text/html part
- Html(Part<'x, Cow<'x, str>>),
+ Html(Cow<'x, str>),
/// Any other part type that is not text.
#[cfg_attr(feature = "serde_support", serde(borrow))]
- Binary(Part<'x, Cow<'x, [u8]>>),
+ Binary(Cow<'x, [u8]>),
/// Any inline binary data that.
#[cfg_attr(feature = "serde_support", serde(borrow))]
- InlineBinary(Part<'x, Cow<'x, [u8]>>),
+ InlineBinary(Cow<'x, [u8]>),
/// Nested RFC5322 message.
- Message(Part<'x, MessageAttachment<'x>>),
+ Message(MessageAttachment<'x>),
/// Multipart part
- Multipart(MultiPart<'x>),
+ Multipart(Vec),
}
-impl<'x> MessagePart<'x> {
- pub fn raw_offsets(&self) -> (usize, usize, usize) {
- match self {
- MessagePart::Text(part) => (part.offset_header, part.offset_body, part.offset_end),
- MessagePart::Html(part) => (part.offset_header, part.offset_body, part.offset_end),
- MessagePart::Binary(part) => (part.offset_header, part.offset_body, part.offset_end),
- MessagePart::InlineBinary(part) => {
- (part.offset_header, part.offset_body, part.offset_end)
- }
- MessagePart::Message(part) => (part.offset_header, part.offset_body, part.offset_end),
- MessagePart::Multipart(part) => (part.offset_header, part.offset_body, part.offset_end),
- }
- }
-
- pub fn unwrap_text(&self) -> &Part<'x, Cow<'x, str>> {
- match self {
- MessagePart::Text(part) => part,
- MessagePart::Html(part) => part,
- _ => panic!("Expected text part."),
- }
- }
-
- pub fn unwrap_binary(&self) -> &Part<'x, Cow<'x, [u8]>> {
- match self {
- MessagePart::Binary(part) => part,
- MessagePart::InlineBinary(part) => part,
- _ => panic!("Expected binary part."),
- }
- }
-
- pub fn unwrap_message(&self) -> &Message {
- match self {
- 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> {
- 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."),
- }
+impl<'x> Default for PartType<'x> {
+ fn default() -> Self {
+ PartType::Multipart(Vec::with_capacity(0))
}
}
/// An RFC5322 or RFC2369 internet address.
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Addr<'x> {
/// The address name including comments
@@ -461,7 +372,7 @@ impl<'x> Addr<'x> {
}
/// An RFC5322 address group.
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Group<'x> {
/// Group name
@@ -538,7 +449,7 @@ impl<'x> HeaderName<'x> {
/// A header field
#[repr(u8)]
-#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
+#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, PartialOrd, Ord)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde_support", serde(rename_all = "snake_case"))]
pub enum RfcHeader {
@@ -632,9 +543,8 @@ impl Display for RfcHeader {
}
/// Parsed header value.
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
-//#[cfg_attr(feature = "serde_support", serde(tag = "type"))]
pub enum HeaderValue<'x> {
/// Single address
Address(Addr<'x>),
@@ -706,6 +616,20 @@ impl<'x> HeaderValue<'x> {
}
}
+ pub fn as_text_list(&self) -> Option> {
+ match *self {
+ HeaderValue::Text(ref s) => Some(vec![s.as_ref()]),
+ HeaderValue::TextList(ref l) => Some(l.iter().map(|l| l.as_ref()).collect()),
+ HeaderValue::Collection(ref l) => Some(
+ l.iter()
+ .filter_map(|v| v.as_text_list())
+ .flatten()
+ .collect(),
+ ),
+ _ => None,
+ }
+ }
+
pub fn get_content_type(&self) -> &ContentType<'x> {
match *self {
HeaderValue::ContentType(ref ct) => ct,
@@ -767,7 +691,7 @@ impl<'x> HeaderValue<'x> {
}
/// An RFC2047 Content-Type or RFC2183 Content-Disposition MIME header field.
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct ContentType<'x> {
pub c_type: Cow<'x, str>,
@@ -793,201 +717,233 @@ pub struct DateTime {
}
impl<'x> Message<'x> {
+ /// Returns the root message part
+ pub fn get_root_part(&self) -> &MessagePart<'x> {
+ &self.parts[0]
+ }
+
/// Returns a parsed RFC header.
pub fn get_header(&self, header: &RfcHeader) -> Option<&HeaderValue> {
- self.headers_rfc.get(header)
+ self.parts[0].headers_rfc.get(header)
}
/// Returns an iterator over the RFC headers of this message.
pub fn get_headers_rfc(&self) -> impl Iterator- )> {
- self.headers_rfc.iter()
+ self.parts[0].headers_rfc.iter()
}
/// Returns the BCC header field
pub fn get_bcc(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Bcc)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the CC header field
pub fn get_cc(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Cc)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Comments header fields
pub fn get_comments(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Comments)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Date header field
pub fn get_date(&self) -> Option<&DateTime> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Date)
.and_then(|header| header.as_datetime_ref())
}
/// Returns the From header field
pub fn get_from(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::From)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all In-Reply-To header fields
pub fn get_in_reply_to(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::InReplyTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Keywords header fields
pub fn get_keywords(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Keywords)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Archive header field
pub fn get_list_archive(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListArchive)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Help header field
pub fn get_list_help(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListHelp)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-ID header field
pub fn get_list_id(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListId)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Owner header field
pub fn get_list_owner(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListOwner)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Post header field
pub fn get_list_post(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListPost)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Subscribe header field
pub fn get_list_subscribe(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListSubscribe)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the List-Unsubscribe header field
pub fn get_list_unsubscribe(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ListUnsubscribe)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Message-ID header field
pub fn get_message_id(&self) -> Option<&str> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::MessageId)
.and_then(|header| header.as_text_ref())
}
/// Returns the MIME-Version header field
pub fn get_mime_version(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::MimeVersion)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Received header fields
pub fn get_received(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Received)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all References header fields
pub fn get_references(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::References)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Reply-To header field
pub fn get_reply_to(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ReplyTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-BCC header field
pub fn get_resent_bcc(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentBcc)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-CC header field
pub fn get_resent_cc(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Resent-Date header fields
pub fn get_resent_date(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentDate)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-From header field
pub fn get_resent_from(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentFrom)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Resent-Message-ID header fields
pub fn get_resent_message_id(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentMessageId)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Sender header field
pub fn get_resent_sender(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentSender)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Resent-To header field
pub fn get_resent_to(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ResentTo)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns all Return-Path header fields
pub fn get_return_path(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ReturnPath)
.unwrap_or(&HeaderValue::Empty)
}
@@ -995,10 +951,10 @@ impl<'x> Message<'x> {
/// Returns the return address from either the Return-Path
/// or From header fields
pub fn get_return_address(&self) -> Option<&str> {
- match self.headers_rfc.get(&RfcHeader::ReturnPath) {
+ match self.parts[0].headers_rfc.get(&RfcHeader::ReturnPath) {
Some(HeaderValue::Text(text)) => Some(text.as_ref()),
Some(HeaderValue::TextList(text_list)) => text_list.last().map(|t| t.as_ref()),
- _ => match self.headers_rfc.get(&RfcHeader::From) {
+ _ => match self.parts[0].headers_rfc.get(&RfcHeader::From) {
Some(HeaderValue::Address(addr)) => addr.address.as_deref(),
Some(HeaderValue::AddressList(addr_list)) => {
addr_list.last().and_then(|a| a.address.as_deref())
@@ -1010,14 +966,16 @@ impl<'x> Message<'x> {
/// Returns the Sender header field
pub fn get_sender(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Sender)
.unwrap_or(&HeaderValue::Empty)
}
/// Returns the Subject header field
pub fn get_subject(&self) -> Option<&str> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::Subject)
.and_then(|header| header.as_text_ref())
}
@@ -1030,7 +988,8 @@ impl<'x> Message<'x> {
/// Returns the To header field
pub fn get_to(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::To)
.unwrap_or(&HeaderValue::Empty)
}
@@ -1048,7 +1007,7 @@ impl<'x> Message<'x> {
/// Returns all headers in raw format
pub fn get_raw_headers(&self) -> impl Iterator
- )> {
- self.headers_raw.iter().map(move |(name, offset)| {
+ self.parts[0].headers_raw.iter().map(move |(name, offset)| {
(
name,
String::from_utf8_lossy(&self.raw_message[offset.start..offset.end]),
@@ -1057,7 +1016,7 @@ impl<'x> Message<'x> {
}
pub fn _get_raw(&'x self, name: HeaderName) -> Option>> {
- let headers = self
+ let headers = self.parts[0]
.headers_raw
.iter()
.filter_map(|(k, v)| {
@@ -1087,51 +1046,39 @@ impl<'x> Message<'x> {
self._get_raw(HeaderName::Rfc(name))
}
- fn get_part(&self, list: &'x [MessagePartId], pos: usize) -> Option<&'x dyn BodyPart> {
- match self.parts.get(*list.get(pos)?)? {
- MessagePart::Text(v) => Some(v),
- MessagePart::Html(v) => Some(v),
- MessagePart::Binary(v) => Some(v),
- MessagePart::InlineBinary(v) => Some(v),
- MessagePart::Message(v) => Some(v),
- _ => None,
- }
- }
-
/// Returns the transformed contents an inline HTML body part by position
pub fn get_html_body(&'x self, pos: usize) -> Option> {
- match self.parts.get(*self.html_body.get(pos)?)? {
- MessagePart::Html(html) => Some(html.body.as_ref().into()),
- MessagePart::Text(text) => Some(text_to_html(text.body.as_ref()).into()),
+ let part = self.parts.get(*self.html_body.get(pos)?)?;
+ match &part.body {
+ PartType::Html(html) => Some(html.as_ref().into()),
+ PartType::Text(text) => Some(text_to_html(text.as_ref()).into()),
_ => None,
}
}
/// Returns the transformed contents an inline text body part by position
pub fn get_text_body(&'x self, pos: usize) -> Option> {
- match self.parts.get(*self.text_body.get(pos)?)? {
- MessagePart::Text(text) => Some(text.body.as_ref().into()),
- MessagePart::Html(html) => Some(html_to_text(html.body.as_ref()).into()),
+ let part = self.parts.get(*self.html_body.get(pos)?)?;
+ match &part.body {
+ PartType::Text(text) => Some(text.as_ref().into()),
+ PartType::Html(html) => Some(html_to_text(html.as_ref()).into()),
_ => None,
}
}
+ /// Returns a message part by position
+ pub fn get_part(&self, pos: usize) -> Option<&MessagePart> {
+ self.parts.get(pos)
+ }
+
/// Returns an inline HTML body part by position
- pub fn get_html_part(&self, pos: usize) -> Option<&Part>> {
- match self.parts.get(*self.html_body.get(pos)?)? {
- MessagePart::Html(html) => Some(html),
- MessagePart::Text(text) => Some(text),
- _ => None,
- }
+ pub fn get_html_part(&self, pos: usize) -> Option<&MessagePart> {
+ self.parts.get(*self.html_body.get(pos)?)
}
/// Returns an inline text body part by position
- pub fn get_text_part(&self, pos: usize) -> Option<&Part>> {
- match self.parts.get(*self.text_body.get(pos)?)? {
- MessagePart::Html(html) => Some(html),
- MessagePart::Text(text) => Some(text),
- _ => None,
- }
+ pub fn get_text_part(&self, pos: usize) -> Option<&MessagePart> {
+ self.parts.get(*self.text_body.get(pos)?)
}
/// Returns an attacment by position
@@ -1199,162 +1146,150 @@ pub trait MimeHeaders<'x> {
impl<'x> MimeHeaders<'x> for Message<'x> {
fn get_content_description(&self) -> Option<&str> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentDescription)
.and_then(|header| header.as_text_ref())
}
fn get_content_disposition(&self) -> Option<&ContentType> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentDisposition)
.and_then(|header| header.as_content_type_ref())
}
fn get_content_id(&self) -> Option<&str> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentId)
.and_then(|header| header.as_text_ref())
}
fn get_content_transfer_encoding(&self) -> Option<&str> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentTransferEncoding)
.and_then(|header| header.as_text_ref())
}
fn get_content_type(&self) -> Option<&ContentType> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentType)
.and_then(|header| header.as_content_type_ref())
}
fn get_content_language(&self) -> &HeaderValue<'x> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentLanguage)
.unwrap_or(&HeaderValue::Empty)
}
fn get_content_location(&self) -> Option<&str> {
- self.headers_rfc
+ self.parts[0]
+ .headers_rfc
.get(&RfcHeader::ContentLocation)
.and_then(|header| header.as_text_ref())
}
}
-/// An inline Text or Binary body part.
-pub trait BodyPart<'x>: fmt::Display + MimeHeaders<'x> {
+impl<'x> MessagePart<'x> {
/// Returns the body part's contents as a `u8` slice
- fn get_contents(&'x self) -> &'x [u8];
+ pub fn get_contents(&'x self) -> &'x [u8] {
+ match &self.body {
+ PartType::Text(text) | PartType::Html(text) => text.as_bytes(),
+ PartType::Binary(bin)
+ | PartType::InlineBinary(bin)
+ | PartType::Message(MessageAttachment::Raw(bin)) => bin.as_ref(),
+ PartType::Message(MessageAttachment::Parsed(message)) => message.raw_message.as_ref(),
+ PartType::Multipart(_) => b"",
+ }
+ }
/// Returns the body part's contents as a `str`
- fn get_text_contents(&'x self) -> &'x str;
+ pub fn get_text_contents(&'x self) -> Option<&'x str> {
+ match &self.body {
+ PartType::Text(text) | PartType::Html(text) => text.as_ref().into(),
+ PartType::Binary(bin)
+ | PartType::InlineBinary(bin)
+ | PartType::Message(MessageAttachment::Raw(bin)) => {
+ std::str::from_utf8(bin.as_ref()).ok()
+ }
+ PartType::Message(MessageAttachment::Parsed(message)) => {
+ std::str::from_utf8(message.raw_message.as_ref()).ok()
+ }
+ PartType::Multipart(_) => None,
+ }
+ }
+
+ /// Returns the nested message
+ pub fn get_message(&'x self) -> Option>> {
+ if let PartType::Message(message) = &self.body {
+ message.get_message()
+ } else {
+ None
+ }
+ }
+
+ /// Returns the sub parts ids of a MIME part
+ pub fn get_sub_parts(&'x self) -> Option<&[MessagePartId]> {
+ if let PartType::Multipart(parts) = &self.body {
+ Some(parts.as_ref())
+ } else {
+ None
+ }
+ }
/// Returns the body part's length
- fn len(&self) -> usize;
+ pub fn len(&self) -> usize {
+ self.offset_end.saturating_sub(self.offset_header)
+ }
/// Returns `true` when the body part MIME type is text/*
- fn is_text(&self) -> bool;
+ pub fn is_text(&self) -> bool {
+ matches!(self.body, PartType::Text(_) | PartType::Html(_))
+ }
- /// Returns `true` when the part is not text
- fn is_binary(&self) -> bool;
+ /// Returns `true` when the part is binary
+ pub fn is_binary(&self) -> bool {
+ matches!(self.body, PartType::Binary(_) | PartType::InlineBinary(_))
+ }
+
+ /// Returns `true` when the part is multipart
+ pub fn is_multipart(&self) -> bool {
+ matches!(self.body, PartType::Multipart(_))
+ }
+
+ /// Returns `true` when the part is a nested message
+ pub fn is_message(&self) -> bool {
+ matches!(self.body, PartType::Message(_))
+ }
/// Returns `true` when the body part is empty
- fn is_empty(&self) -> bool {
+ pub fn is_empty(&self) -> bool {
self.len() == 0
}
-}
-impl<'x> BodyPart<'x> for Part<'x, Cow<'x, str>> {
- fn get_contents(&'x self) -> &'x [u8] {
- self.body.as_bytes()
+ /// Get the message headers
+ pub fn headers_rfc(&self) -> &HashMap {
+ &self.headers_rfc
}
- fn is_text(&self) -> bool {
- true
- }
-
- fn is_binary(&self) -> bool {
- false
- }
-
- fn get_text_contents(&'x self) -> &'x str {
- self.body.as_ref()
- }
-
- fn len(&self) -> usize {
- self.body.len()
+ /// Get the raw offsets of this part
+ pub fn raw_offsets(&self) -> (usize, usize, usize) {
+ (self.offset_header, self.offset_body, self.offset_end)
}
}
-impl<'x> fmt::Display for Part<'x, Cow<'x, str>> {
+impl<'x> fmt::Display for MessagePart<'x> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.write_str(self.body.as_ref())
+ fmt.write_str(self.get_text_contents().unwrap_or("[no contents]"))
}
}
-impl<'x> BodyPart<'x> for Part<'x, Cow<'x, [u8]>> {
- fn get_contents(&'x self) -> &'x [u8] {
- self.body.as_ref()
- }
-
- fn get_text_contents(&'x self) -> &'x str {
- std::str::from_utf8(self.body.as_ref()).unwrap_or("")
- }
-
- fn is_text(&self) -> bool {
- false
- }
-
- fn is_binary(&self) -> bool {
- true
- }
-
- fn len(&self) -> usize {
- self.body.len()
- }
-}
-
-impl<'x> fmt::Display for Part<'x, Cow<'x, [u8]>> {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.write_str("[binary contents]")
- }
-}
-
-impl<'x> BodyPart<'x> for Part<'x, MessageAttachment<'x>> {
- fn get_contents(&'x self) -> &'x [u8] {
- 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.get_contents()).unwrap_or("")
- }
-
- fn is_text(&self) -> bool {
- false
- }
-
- fn is_binary(&self) -> bool {
- true
- }
-
- fn len(&self) -> usize {
- match &self.body {
- MessageAttachment::Parsed(msg) => msg.raw_message.len(),
- MessageAttachment::Raw(raw) => raw.len(),
- }
- }
-}
-
-impl<'x> fmt::Display for Part<'x, MessageAttachment<'x>> {
- fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- fmt.write_str(self.get_text_contents())
- }
-}
-
-impl<'x, T> MimeHeaders<'x> for Part<'x, T> {
+impl<'x> MimeHeaders<'x> for MessagePart<'x> {
fn get_content_description(&self) -> Option<&str> {
self.headers_rfc
.get(&RfcHeader::ContentDescription)
@@ -1422,11 +1357,11 @@ impl<'x> BodyPartIterator<'x> {
}
impl<'x> Iterator for BodyPartIterator<'x> {
- type Item = &'x dyn BodyPart<'x>;
+ type Item = &'x MessagePart<'x>;
fn next(&mut self) -> Option {
self.pos += 1;
- self.message.get_part(self.list, self.pos as usize)
+ self.message.parts.get(*self.list.get(self.pos as usize)?)
}
}
@@ -1481,7 +1416,7 @@ impl<'x> ContentType<'x> {
}
/// Contents of an e-mail message attachment.
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Clone)]
pub enum MessageAttachment<'x> {
Parsed(Box>),
Raw(Cow<'x, [u8]>),
@@ -1494,57 +1429,12 @@ impl<'x> Default for MessageAttachment<'x> {
}
impl<'x> MessageAttachment<'x> {
- /// Parse the message attachment and return a `Message` object.
- pub fn parse_raw(&'x self) -> Option> {
- 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> {
+ /// Get nested message
+ pub fn get_message(&'x self) -> Option>> {
match self {
- MessageAttachment::Parsed(message) => (*std::mem::take(&mut message).unwrap()).into(),
- MessageAttachment::Raw(raw) => Message::parse(raw.as_ref()),
+ MessageAttachment::Parsed(message) => Some(Cow::Borrowed(message.as_ref())),
+ MessageAttachment::Raw(raw_message) => Some(Cow::Owned(Message::parse(raw_message)?)),
}
- }*/
-}
-
-impl<'x> Part<'x, MessageAttachment<'x>> {
- /// Parse the message attachment and return a `Message` object.
- pub fn parse_raw(&'x self) -> Option> {
- 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()
}
}
diff --git a/src/parsers/message.rs b/src/parsers/message.rs
index 72aa80b..3d1ccfd 100644
--- a/src/parsers/message.rs
+++ b/src/parsers/message.rs
@@ -1,6 +1,6 @@
/*
* Copyright Stalwart Labs Ltd. See the COPYING
- * file at the top-level directory of this distribution.
+ * file at the top-level dir&ectory of this distribution.
*
* Licensed under the Apache License, Version 2.0 or the MIT license
@@ -16,28 +16,15 @@ use crate::{
base64::decode_base64, charsets::map::get_charset_decoder,
quoted_printable::decode_quoted_printable, DecodeFnc, DecodeResult,
},
- ContentType, HeaderName, HeaderValue, Message, MessageAttachment, MessagePart, MessagePartId,
- MessageStructure, MultiPart, Part, RawHeaders, RfcHeader, RfcHeaders,
+ ContentType, HeaderValue, Message, MessageAttachment, MessagePart, MessagePartId, PartType,
+ RawHeaders, RfcHeader, RfcHeaders,
};
use super::{
header::parse_headers,
- mime::{
- get_bytes_to_boundary, seek_crlf, seek_next_part, seek_part_end, skip_crlf,
- skip_multipart_end,
- },
+ mime::{get_bytes_to_boundary, seek_crlf, seek_next_part, skip_crlf, skip_multipart_end},
};
-const MIME_HEADERS: &[RfcHeader] = &[
- RfcHeader::ContentType,
- RfcHeader::ContentDisposition,
- RfcHeader::ContentId,
- RfcHeader::ContentLanguage,
- RfcHeader::ContentLocation,
- RfcHeader::ContentTransferEncoding,
- RfcHeader::ContentDescription,
-];
-
#[derive(Debug, PartialEq)]
enum MimeType {
MultipartMixed,
@@ -115,7 +102,7 @@ fn get_mime_type(
_ => (false, false, true, MimeType::TextOther),
},
"image" | "audio" | "video" => (false, true, false, MimeType::Inline),
- "message" if content_type.get_subtype() == Some("rfc822") => {
+ "message" if [Some("rfc822"), Some("global")].contains(&content_type.get_subtype()) => {
(false, false, false, MimeType::Message)
}
_ => (false, false, false, MimeType::Other),
@@ -155,8 +142,8 @@ struct MessageParserState {
text_parts: usize,
need_html_body: bool,
need_text_body: bool,
- part_id: Option,
- structure: Vec,
+ part_id: MessagePartId,
+ sub_part_ids: Vec,
offset_header: usize,
offset_body: usize,
offset_end: usize,
@@ -176,18 +163,6 @@ impl MessageParserState {
..Default::default()
}
}
-
- pub fn get_structure(&mut self) -> MessageStructure {
- if let Some(part_id) = self.part_id {
- MessageStructure::MultiPart((part_id, std::mem::take(&mut self.structure)))
- } else if self.structure.len() > 1 {
- MessageStructure::List(std::mem::take(&mut self.structure))
- } else if self.structure.len() == 1 {
- self.structure.pop().unwrap()
- } else {
- MessageStructure::List(vec![])
- }
- }
}
pub struct MessageStream<'x> {
@@ -210,7 +185,7 @@ impl<'x> Message<'x> {
/// Returns `false` if at least one header field was successfully parsed.
pub fn is_empty(&self) -> bool {
- self.headers_rfc.is_empty() && self.headers_raw.is_empty()
+ self.parts.is_empty()
}
/// Parses a byte slice containing the RFC5322 raw message and returns a
@@ -227,35 +202,20 @@ impl<'x> Message<'x> {
let mut state = MessageParserState::new();
let mut state_stack = Vec::with_capacity(4);
- let mut mime_part_header = RfcHeaders::new();
- let mut mime_part_header_raw = RawHeaders::new();
+ let mut part_header = RfcHeaders::new();
+ let mut part_header_raw = RawHeaders::new();
'outer: loop {
// Parse headers
state.offset_header = stream.pos;
- let (is_message, header) = if let MimeType::Message = state.mime_type {
- if !parse_headers(
- &mut message.headers_rfc,
- &mut message.headers_raw,
- &mut stream,
- ) {
- break;
- }
- (true, &mut message.headers_rfc)
- } else {
- if !parse_headers(
- &mut mime_part_header,
- &mut mime_part_header_raw,
- &mut stream,
- ) {
- break;
- }
- (false, &mut mime_part_header)
- };
+ if !parse_headers(&mut part_header, &mut part_header_raw, &mut stream) {
+ break;
+ }
state.parts += 1;
+ state.sub_part_ids.push(message.parts.len());
- let content_type = header
+ let content_type = part_header
.get(&RfcHeader::ContentType)
.and_then(|c| c.as_content_type_ref());
@@ -270,6 +230,7 @@ impl<'x> Message<'x> {
state.offset_body = seek_crlf(&stream, stream.pos);
if seek_next_part(&mut stream, mime_boundary.as_ref()) {
+ let part_id = message.parts.len();
let new_state = MessageParserState {
in_alternative: state.in_alternative
|| mime_type == MimeType::MultipartAlernative,
@@ -279,23 +240,19 @@ impl<'x> Message<'x> {
text_parts: message.text_body.len(),
need_html_body: state.need_html_body,
need_text_body: state.need_text_body,
- part_id: if !is_message {
- Some(message.parts.len())
- } else {
- None
- },
+ part_id,
..Default::default()
};
- if !is_message {
- add_missing_type(&mut mime_part_header, "text".into(), "plain".into());
- message.parts.push(MessagePart::Multipart(MultiPart {
- headers_rfc: std::mem::take(&mut mime_part_header),
- headers_raw: std::mem::take(&mut mime_part_header_raw),
- offset_header: state.offset_header,
- offset_body: state.offset_body,
- offset_end: 0,
- }));
- }
+ add_missing_type(&mut part_header, "text".into(), "plain".into());
+ message.parts.push(MessagePart {
+ headers_rfc: std::mem::take(&mut part_header),
+ headers_raw: std::mem::take(&mut part_header_raw),
+ offset_header: state.offset_header,
+ offset_body: state.offset_body,
+ offset_end: 0,
+ is_encoding_problem: false,
+ body: PartType::default(),
+ });
state_stack.push((state, None));
state = new_state;
skip_crlf(&mut stream);
@@ -310,7 +267,7 @@ impl<'x> Message<'x> {
skip_crlf(&mut stream);
state.offset_body = stream.pos;
- let (is_binary, decode_fnc): (bool, DecodeFnc) = match header
+ let (is_binary, decode_fnc): (bool, DecodeFnc) = match part_header
.get(&RfcHeader::ContentTransferEncoding)
{
Some(HeaderValue::Text(encoding)) if encoding.eq_ignore_ascii_case("base64") => {
@@ -324,28 +281,27 @@ 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,
+ part_id: message.parts.len(),
..Default::default()
};
- add_missing_type(&mut mime_part_header, "message".into(), "rfc822".into());
- state_stack.push((
- state,
- (
- message,
- std::mem::take(&mut mime_part_header),
- std::mem::take(&mut mime_part_header_raw),
- )
- .into(),
- ));
+ add_missing_type(&mut part_header, "message".into(), "rfc822".into());
+ message.attachments.push(message.parts.len());
+ message.parts.push(MessagePart {
+ headers_rfc: std::mem::take(&mut part_header),
+ headers_raw: std::mem::take(&mut part_header_raw),
+ is_encoding_problem: false,
+ offset_header: state.offset_header,
+ offset_body: state.offset_body,
+ offset_end: 0,
+ body: PartType::default(), // Temp value, will be replaced later.
+ });
+ state_stack.push((state, message.into()));
message = Message::new();
state = new_state;
continue;
@@ -364,57 +320,77 @@ impl<'x> Message<'x> {
// Attempt to recover contents of an invalid message
let is_encoding_problem = bytes_read == 0;
if is_encoding_problem {
- if stream.pos >= stream.data.len() || (is_binary && state.mime_boundary.is_none()) {
- state.structure.pop();
- break;
- }
+ 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)
+ };
- // 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)
- };
-
- 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;
+ 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;
+ true
+ } else {
+ false
+ }
} else {
- state.structure.pop();
- break;
+ false
}
} else {
- state.structure.pop();
- break;
+ bytes = r_bytes;
+ stream.pos += bytes_read;
+ true
}
} else {
- bytes = r_bytes;
- stream.pos += bytes_read;
+ 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_rfc: std::mem::take(&mut part_header),
+ headers_raw: std::mem::take(&mut part_header_raw),
+ is_encoding_problem: true,
+ body: PartType::Binary((&[][..]).into()),
+ offset_header: state.offset_header,
+ offset_body: state.offset_body,
+ offset_end: stream.pos,
+ });
+ break;
}
- mime_type = MimeType::TextOther;
- is_inline = false;
- is_text = true;
} else {
stream.pos += bytes_read;
}
- state.offset_end = seek_part_end(&stream, stream.pos, state.mime_boundary.as_deref());
+ state.offset_end = state
+ .mime_boundary
+ .as_ref()
+ .map(|b| stream.pos.saturating_sub(b.len() - 1))
+ .unwrap_or(stream.pos);
- if mime_type != MimeType::Message {
+ let body_part = if mime_type != MimeType::Message {
let is_inline = is_inline
- && header
+ && part_header
.get(&RfcHeader::ContentDisposition)
.map_or_else(|| true, |d| !d.get_content_type().is_attachment())
&& (state.parts == 1
@@ -448,40 +424,10 @@ impl<'x> Message<'x> {
};
if is_text {
+ let text = result_to_string(bytes, stream.data, content_type);
let is_html = mime_type == MimeType::TextHtml;
- let mut text_part = Part {
- body: result_to_string(bytes, stream.data, content_type),
- headers_rfc: std::mem::take(&mut mime_part_header),
- headers_raw: std::mem::take(&mut mime_part_header_raw),
- is_encoding_problem,
- offset_header: state.offset_header,
- offset_body: state.offset_body,
- offset_end: state.offset_end,
- };
- // If there is a single part in the message, move MIME headers
- // to the part
- if is_message {
- for header_name in MIME_HEADERS {
- if let Some(value) = message.headers_rfc.remove(header_name) {
- text_part.headers_rfc.insert(*header_name, value);
- }
- }
-
- for (header_name, offset) in &message.headers_raw {
- match header_name {
- HeaderName::Rfc(header_name)
- if MIME_HEADERS.contains(header_name) =>
- {
- text_part
- .headers_raw
- .push((HeaderName::Rfc(*header_name), offset.clone()));
- }
- _ => (),
- }
- }
- }
- add_missing_type(&mut text_part.headers_rfc, "text".into(), "plain".into());
+ add_missing_type(&mut part_header, "text".into(), "plain".into());
if add_to_html && !is_html {
message.html_body.push(message.parts.len());
@@ -497,11 +443,11 @@ impl<'x> Message<'x> {
message.attachments.push(message.parts.len());
}
- message.parts.push(if is_html {
- MessagePart::Html(text_part)
+ if is_html {
+ PartType::Html(text)
} else {
- MessagePart::Text(text_part)
- });
+ PartType::Text(text)
+ }
} else {
if add_to_html {
message.html_body.push(message.parts.len());
@@ -512,86 +458,52 @@ impl<'x> Message<'x> {
message.attachments.push(message.parts.len());
- let mut binary_part = Part {
- headers_rfc: std::mem::take(&mut mime_part_header),
- headers_raw: std::mem::take(&mut mime_part_header_raw),
- is_encoding_problem,
- body: result_to_bytes(bytes, stream.data),
- offset_header: state.offset_header,
- offset_body: state.offset_body,
- offset_end: state.offset_end,
- };
-
- // If there is a single part in the message, move MIME headers
- // to the part
- if is_message {
- for header_name in MIME_HEADERS {
- if let Some(value) = message.headers_rfc.remove(header_name) {
- binary_part.headers_rfc.insert(*header_name, value);
- }
- }
-
- for (header_name, offset) in &message.headers_raw {
- match header_name {
- HeaderName::Rfc(header_name)
- if MIME_HEADERS.contains(header_name) =>
- {
- binary_part
- .headers_raw
- .push((HeaderName::Rfc(*header_name), offset.clone()));
- }
- _ => (),
- }
- }
- }
-
- message.parts.push(if !is_inline {
- MessagePart::Binary(binary_part)
+ let bytes = result_to_bytes(bytes, stream.data);
+ if !is_inline {
+ PartType::Binary(bytes)
} else {
- MessagePart::InlineBinary(binary_part)
- });
- };
+ PartType::InlineBinary(bytes)
+ }
+ }
} else {
- add_missing_type(&mut mime_part_header, "message".into(), "rfc822".into());
+ add_missing_type(&mut part_header, "message".into(), "rfc822".into());
message.attachments.push(message.parts.len());
- message.parts.push(MessagePart::Message(Part {
- headers_rfc: std::mem::take(&mut mime_part_header),
- headers_raw: std::mem::take(&mut mime_part_header_raw),
- is_encoding_problem,
- body: MessageAttachment::Raw(result_to_bytes(bytes, stream.data)),
- offset_header: state.offset_header,
- offset_body: state.offset_body,
- offset_end: state.offset_end,
- }));
- }
+ PartType::Message(MessageAttachment::Raw(result_to_bytes(bytes, stream.data)))
+ };
+
+ // Add part
+ message.parts.push(MessagePart {
+ headers_rfc: std::mem::take(&mut part_header),
+ headers_raw: std::mem::take(&mut part_header_raw),
+ is_encoding_problem,
+ body: body_part,
+ offset_header: state.offset_header,
+ offset_body: state.offset_body,
+ offset_end: state.offset_end,
+ });
if state.mime_boundary.is_some() {
// Currently processing a MIME part
'inner: loop {
if let MimeType::Message = state.mime_type {
// Finished processing a nested message, restore parent message from stack
- if let Some((
- mut prev_state,
- Some((mut prev_message, headers, headers_raw)),
- )) = state_stack.pop()
- {
- message.structure = state.get_structure();
- message.offset_header = state.offset_header;
- message.offset_body = state.offset_body;
- message.offset_end =
- seek_part_end(&stream, stream.pos, state.mime_boundary.as_deref());
+ if let Some((mut prev_state, Some(mut prev_message))) = state_stack.pop() {
+ let offset_end = state
+ .mime_boundary
+ .as_ref()
+ .map(|b| stream.pos.saturating_sub(b.len() - 1))
+ .unwrap_or(stream.pos);
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 {
- headers_rfc: headers,
- headers_raw,
- is_encoding_problem: false,
- offset_header: prev_state.offset_header,
- offset_body: prev_state.offset_body,
- offset_end: message.offset_end,
- body: MessageAttachment::Parsed(Box::new(message)),
- }));
+ raw_message[state.offset_header..offset_end].as_ref().into();
+
+ if let Some(part) = prev_message.parts.get_mut(state.part_id) {
+ part.body =
+ PartType::Message(MessageAttachment::Parsed(Box::new(message)));
+ part.offset_end = offset_end;
+ } else {
+ debug_assert!(false, "Invalid part ID, could not find message.");
+ }
+
message = prev_message;
prev_state.mime_boundary = state.mime_boundary;
state = prev_state;
@@ -627,21 +539,17 @@ impl<'x> Message<'x> {
}
}
- // Update end offset
- if let Some(part_id) = state.part_id {
- if let Some(part) = message.parts.get_mut(part_id) {
- if let MessagePart::Multipart(ref mut part) = part {
- part.offset_end = seek_crlf(&stream, stream.pos);
- }
- } else {
- debug_assert!(false, "This should not have happened.");
- }
+ if let Some(part) = message.parts.get_mut(state.part_id) {
+ // Update end offset
+ part.offset_end = seek_crlf(&stream, stream.pos);
+ // Add headers and substructure to parent part
+ part.body =
+ PartType::Multipart(std::mem::take(&mut state.sub_part_ids));
+ } else {
+ debug_assert!(false, "Invalid part ID, could not find multipart.");
}
- if let Some((mut prev_state, _)) = state_stack.pop() {
- // Add headers and substructure to parent part
- prev_state.structure.push(state.get_structure());
-
+ if let Some((prev_state, _)) = state_stack.pop() {
// Restore ancestor's state
state = prev_state;
@@ -666,48 +574,28 @@ impl<'x> Message<'x> {
}
// Corrupted MIME message, try to recover whatever is possible.
- while let Some((mut prev_state, prev_message)) = state_stack.pop() {
- if let Some((mut prev_message, headers, headers_raw)) = prev_message {
- if !message.is_empty() {
- message.offset_header = state.offset_header;
- message.offset_body = state.offset_body;
- message.offset_end = stream.pos;
- 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 {
- headers_rfc: headers,
- headers_raw,
- is_encoding_problem: false,
- offset_header: prev_state.offset_header,
- offset_body: prev_state.offset_body,
- offset_end: message.offset_end,
- body: MessageAttachment::Parsed(Box::new(message)),
- }));
- message = prev_message;
+ while let Some((prev_state, prev_message)) = state_stack.pop() {
+ if let Some(mut prev_message) = prev_message {
+ message.raw_message = raw_message[state.offset_header..stream.pos].as_ref().into();
+
+ if let Some(part) = prev_message.parts.get_mut(state.part_id) {
+ part.body = PartType::Message(MessageAttachment::Parsed(Box::new(message)));
+ part.offset_end = stream.pos;
+ } else {
+ debug_assert!(false, "Invalid part ID, could not find message.");
}
+
+ message = prev_message;
+ } else if let Some(part) = message.parts.get_mut(state.part_id) {
+ part.offset_end = stream.pos;
+ part.body = PartType::Multipart(state.sub_part_ids);
} else {
- if let Some(part_id) = state.part_id {
- if let Some(part) = message.parts.get_mut(part_id) {
- if let MessagePart::Multipart(ref mut part) = part {
- part.offset_end = stream.pos;
- }
- } else {
- debug_assert!(false, "This should not have happened.");
- }
- }
- // Add headers and substructure to parent part
- prev_state.structure.push(state.get_structure());
+ debug_assert!(false, "This should not have happened.");
}
state = prev_state;
}
message.raw_message = raw_message.into();
- message.structure = state.get_structure();
- message.offset_header = state.offset_header;
- message.offset_body = state.offset_body;
- message.offset_end = stream.pos;
if !message.is_empty() {
Some(message)
@@ -718,14 +606,62 @@ impl<'x> Message<'x> {
}
#[cfg(test)]
mod tests {
- use std::{fs, path::PathBuf};
+ use std::{collections::BTreeMap, fs, path::PathBuf};
+ use serde::Serialize;
use serde_json::Value;
- use crate::parsers::message::Message;
+ use crate::{
+ parsers::message::Message, HeaderValue, MessagePart, MessagePartId, PartType, RawHeaders,
+ RfcHeader, RfcHeaders,
+ };
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----".as_bytes();
+ #[derive(Serialize)]
+ pub struct SortedMessage<'x> {
+ pub html_body: Vec,
+ pub text_body: Vec,
+ pub attachments: Vec,
+ pub parts: Vec>,
+ }
+
+ #[derive(Serialize)]
+ pub struct SortedMessagePart<'x> {
+ pub headers_rfc: BTreeMap>,
+ pub headers_raw: RawHeaders<'x>,
+ pub is_encoding_problem: bool,
+ pub body: PartType<'x>,
+ pub offset_header: usize,
+ pub offset_body: usize,
+ pub offset_end: usize,
+ }
+
+ impl<'x> From> for SortedMessage<'x> {
+ fn from(message: Message<'x>) -> Self {
+ SortedMessage {
+ html_body: message.html_body,
+ text_body: message.text_body,
+ attachments: message.attachments,
+ parts: message.parts.into_iter().map(|p| p.into()).collect(),
+ }
+ }
+ }
+
+ impl<'x> From> for SortedMessagePart<'x> {
+ fn from(part: MessagePart<'x>) -> Self {
+ SortedMessagePart {
+ headers_rfc: part.headers_rfc.into_iter().collect(),
+ headers_raw: part.headers_raw,
+ is_encoding_problem: part.is_encoding_problem,
+ body: part.body,
+ offset_header: part.offset_header,
+ offset_body: part.offset_body,
+ offset_end: part.offset_end,
+ }
+ }
+ }
+
#[test]
fn parse_full_messages() {
for test_suite in ["rfc", "legacy", "thirdparty", "malformed"] {
@@ -756,14 +692,14 @@ mod tests {
tests_run += 1;
- let input = input.split_at_mut(pos);
- let message = Message::parse(input.0).unwrap();
+ let (raw_message, expected_result) = input.split_at_mut(pos);
+ let message = SortedMessage::from(Message::parse(raw_message).unwrap());
let json_message = serde_json::to_string_pretty(&message).unwrap();
assert_eq!(
serde_json::from_str::(&json_message).unwrap(),
serde_json::from_str::(
- std::str::from_utf8(&input.1[SEPARATOR.len()..]).unwrap()
+ std::str::from_utf8(&expected_result[SEPARATOR.len()..]).unwrap()
)
.unwrap(),
"Test failed for '{}', result was:\n{}",
diff --git a/src/parsers/mime.rs b/src/parsers/mime.rs
index 2851557..974a860 100644
--- a/src/parsers/mime.rs
+++ b/src/parsers/mime.rs
@@ -166,22 +166,3 @@ pub fn seek_crlf(stream: &MessageStream, mut start_pos: usize) -> usize {
start_pos
}
-
-#[inline(always)]
-pub fn seek_part_end(
- stream: &MessageStream,
- mut start_pos: usize,
- boundary: Option<&[u8]>,
-) -> usize {
- if let Some(boundary) = boundary {
- start_pos = start_pos.saturating_sub(boundary.len());
- if let Some(ch) = stream.data.get(start_pos - 1) {
- if *ch == b'\r' {
- start_pos = start_pos.saturating_sub(1);
- }
- }
- start_pos
- } else {
- start_pos
- }
-}
diff --git a/tests/integration_test.rs b/tests/integration_test.rs
index 138669b..3007198 100644
--- a/tests/integration_test.rs
+++ b/tests/integration_test.rs
@@ -57,9 +57,11 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
let message = Message::parse(input).unwrap();
assert_eq!(
- bincode::deserialize::(&bincode::serialize(&message.headers_rfc).unwrap())
- .unwrap(),
- message.headers_rfc
+ bincode::deserialize::(
+ &bincode::serialize(&message.parts[0].headers_rfc).unwrap()
+ )
+ .unwrap(),
+ message.parts[0].headers_rfc
);
assert_eq!(
@@ -114,7 +116,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
)
);
- let nested_message = message.get_attachment(0).unwrap().unwrap_message();
+ let nested_message = message.get_attachment(0).unwrap().get_message().unwrap();
assert_eq!(
nested_message.get_subject().unwrap(),
@@ -131,7 +133,7 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
- let nested_attachment = nested_message.get_attachment(0).unwrap().unwrap_binary();
+ let nested_attachment = nested_message.get_attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);