214 lines
7.4 KiB
Rust
214 lines
7.4 KiB
Rust
//! Parsing a raw RFC 5322 message (mail-parser) into what the app stores and shows.
|
|
|
|
use crate::{Address, safe_filename};
|
|
use mail_parser::{MessageParser, MessagePart, PartKind};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
/// Larger messages are refused before parsing (Proton's own limit is 25 MB of attachments).
|
|
pub const MAX_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
|
|
/// A subject longer than this is cut (characters).
|
|
pub const MAX_SUBJECT_CHARS: usize = 998;
|
|
/// At most this many addresses per field are kept.
|
|
pub const MAX_ADDRESSES: usize = 500;
|
|
/// At most this many attachments are kept; the rest are counted in `dropped_attachments`.
|
|
pub const MAX_ATTACHMENTS: usize = 500;
|
|
|
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
|
pub struct Parsed {
|
|
pub message_id: Option<String>,
|
|
pub in_reply_to: Vec<String>,
|
|
pub references: Vec<String>,
|
|
pub subject: String,
|
|
pub from: Vec<Address>,
|
|
pub to: Vec<Address>,
|
|
pub cc: Vec<Address>,
|
|
pub reply_to: Vec<Address>,
|
|
/// Seconds since the Unix epoch, from the Date header.
|
|
pub date: Option<i64>,
|
|
/// The Date header as RFC 822 text, for "On <date>, <name> wrote:".
|
|
pub date_text: Option<String>,
|
|
/// Line endings are `\n`.
|
|
pub text: Option<String>,
|
|
pub html: Option<String>,
|
|
pub attachments: Vec<Attachment>,
|
|
pub dropped_attachments: usize,
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct Attachment {
|
|
/// Already safe for a file system (`safe_filename`).
|
|
pub filename: String,
|
|
pub content_type: String,
|
|
/// Without the angle brackets.
|
|
pub content_id: Option<String>,
|
|
pub inline: bool,
|
|
pub data: Vec<u8>,
|
|
}
|
|
|
|
/// Bodies and attachments are personal data: `Debug` prints sizes only.
|
|
impl std::fmt::Debug for Parsed {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("Parsed")
|
|
.field("text_len", &self.text.as_ref().map(String::len))
|
|
.field("html_len", &self.html.as_ref().map(String::len))
|
|
.field("attachments", &self.attachments.len())
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Debug for Attachment {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("Attachment")
|
|
.field("bytes", &self.data.len())
|
|
.field("inline", &self.inline)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum ParseError {
|
|
TooLarge,
|
|
NotMail,
|
|
}
|
|
|
|
impl std::fmt::Display for ParseError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
ParseError::TooLarge => write!(f, "message larger than {MAX_MESSAGE_BYTES} bytes"),
|
|
ParseError::NotMail => f.write_str("not a mail message"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for ParseError {}
|
|
|
|
/// At most this many Message-IDs are kept from In-Reply-To and References.
|
|
pub const MAX_REFERENCES: usize = 100;
|
|
|
|
pub fn parse(raw: &[u8]) -> Result<Parsed, ParseError> {
|
|
if raw.len() > MAX_MESSAGE_BYTES {
|
|
return Err(ParseError::TooLarge);
|
|
}
|
|
if raw.iter().all(u8::is_ascii_whitespace) {
|
|
return Err(ParseError::NotMail);
|
|
}
|
|
let message = MessageParser::new().parse(raw).ok_or(ParseError::NotMail)?;
|
|
|
|
let subject: String =
|
|
message.subject().unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_SUBJECT_CHARS).collect();
|
|
|
|
let text = join_bodies(message.text_body().filter_map(|part| part.text()));
|
|
// mail-parser converts a text-only message to HTML; the app renders text itself, so keep real HTML only.
|
|
let html = join_bodies(
|
|
message.html_body().filter(|part| matches!(part.kind(), PartKind::Html)).filter_map(|part| part.text()),
|
|
);
|
|
|
|
let mut attachments = Vec::new();
|
|
let mut dropped_attachments = 0;
|
|
for part in message.attachments() {
|
|
if attachments.len() >= MAX_ATTACHMENTS {
|
|
dropped_attachments += 1;
|
|
continue;
|
|
}
|
|
attachments.push(attachment(&part));
|
|
}
|
|
|
|
Ok(Parsed {
|
|
message_id: message.message_id().map(clean_id).filter(|id| !id.is_empty()),
|
|
in_reply_to: ids(message.in_reply_to()),
|
|
references: ids(message.references()),
|
|
subject: subject.trim().to_string(),
|
|
from: addresses(message.from()),
|
|
to: addresses(message.to()),
|
|
cc: addresses(message.cc()),
|
|
reply_to: addresses(message.reply_to()),
|
|
date: message.date().map(|d| d.to_timestamp()),
|
|
date_text: message.date().map(|d| d.to_rfc822()),
|
|
text,
|
|
html,
|
|
attachments,
|
|
dropped_attachments,
|
|
})
|
|
}
|
|
|
|
fn join_bodies<'a>(parts: impl Iterator<Item = std::borrow::Cow<'a, str>>) -> Option<String> {
|
|
let mut out = String::new();
|
|
for part in parts {
|
|
if !out.is_empty() {
|
|
out.push('\n');
|
|
}
|
|
out.push_str(&part);
|
|
}
|
|
if out.is_empty() { None } else { Some(normalize_newlines(&out)) }
|
|
}
|
|
|
|
pub(crate) fn normalize_newlines(s: &str) -> String {
|
|
s.replace("\r\n", "\n").replace('\r', "\n")
|
|
}
|
|
|
|
fn clean_id(id: &str) -> String {
|
|
id.trim().trim_start_matches('<').trim_end_matches('>').trim().chars().take(998).collect()
|
|
}
|
|
|
|
fn ids(list: Option<mail_parser::TextList<'_>>) -> Vec<String> {
|
|
let mut out: Vec<String> = Vec::new();
|
|
for id in list.iter().flat_map(|l| l.iter()) {
|
|
let id = clean_id(id);
|
|
if !id.is_empty() && !out.contains(&id) && out.len() < MAX_REFERENCES {
|
|
out.push(id);
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn addresses(list: Option<mail_parser::AddressList<'_>>) -> Vec<Address> {
|
|
list.iter()
|
|
.flat_map(|l| l.mailboxes())
|
|
.filter_map(|m| {
|
|
let email = m.address()?.trim();
|
|
if email.is_empty() {
|
|
return None;
|
|
}
|
|
let name = m.name().map(|n| n.chars().filter(|c| !c.is_control()).collect::<String>());
|
|
Some(Address::new(name.as_deref(), email))
|
|
})
|
|
.take(MAX_ADDRESSES)
|
|
.collect()
|
|
}
|
|
|
|
fn attachment(part: &MessagePart<'_>) -> Attachment {
|
|
let content_type = part
|
|
.content_type()
|
|
.map(|ct| match ct.subtype() {
|
|
Some(sub) => format!("{}/{}", ct.ctype(), sub),
|
|
None => ct.ctype().to_string(),
|
|
})
|
|
.map(|ct| ct.to_ascii_lowercase())
|
|
.filter(|ct| ct.len() <= 127 && ct.chars().all(|c| c.is_ascii_graphic()))
|
|
.unwrap_or_else(|| "application/octet-stream".to_string());
|
|
|
|
let content_id = part.content_id().map(clean_id).filter(|id| !id.is_empty());
|
|
let declared_attachment = part.content_disposition().is_some_and(|d| d.is_attachment());
|
|
let inline = content_id.is_some() && !declared_attachment;
|
|
|
|
let (name, data) = match part.kind() {
|
|
PartKind::Message(nested) => {
|
|
let name = part
|
|
.attachment_name()
|
|
.map(str::to_owned)
|
|
.unwrap_or_else(|| format!("{}.eml", nested.subject().unwrap_or("message")));
|
|
let name = if name.to_ascii_lowercase().ends_with(".eml") { name } else { format!("{name}.eml") };
|
|
(name, part.decoded().into_owned())
|
|
}
|
|
_ => {
|
|
let name = part.attachment_name().map(str::to_owned).unwrap_or_else(|| {
|
|
let ext = content_type.rsplit('/').next().unwrap_or("bin");
|
|
format!("attachment.{ext}")
|
|
});
|
|
(name, part.decoded().into_owned())
|
|
}
|
|
};
|
|
|
|
Attachment { filename: safe_filename(&name), content_type, content_id, inline, data }
|
|
}
|