use mail_parser::{MessageParser, MessagePart, MessageRef, PartFlags};
use sha1::{Digest, Sha1};
use crate::Error;
mod assignment;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct AttachmentHash {
name: String,
sha1: [u8; 20],
}
impl AttachmentHash {
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn sha1(&self) -> &[u8; 20] {
&self.sha1
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum AttachmentCheck {
Matches(Option<String>),
Carried(Option<String>),
Differs(String),
Missing(Option<String>),
NotSent(Option<String>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TextLineEnds {
Canonical,
CanonicalOrLf,
}
fn parse_sent(sent: &[u8]) -> Result<mail_parser::Message<'_>, Error> {
MessageParser::default()
.parse(sent)
.filter(|parsed| !limit_reached(parsed))
.ok_or(Error::NotMime)
}
pub(crate) fn limit_reached(parsed: &mail_parser::Message<'_>) -> bool {
parsed
.parts()
.any(|part| part.flags().contains(PartFlags::LIMIT_REACHED))
}
pub(crate) fn read(
original: MessageRef<'_>,
sent: &[u8],
line_ends: TextLineEnds,
) -> Result<Vec<AttachmentHash>, Error> {
let parsed = parse_sent(sent)?;
let comparison = Comparison::new(original, parsed.root(), line_ends)?;
Ok(comparison
.candidates
.iter()
.filter(|candidate| !candidate.carried)
.filter_map(|candidate| {
Some(AttachmentHash {
name: candidate.name()?.to_owned(),
sha1: candidate.hash?,
})
})
.collect())
}
fn replaced_name(file: &str) -> Option<&str> {
file.strip_suffix(".hash")
}
pub(crate) fn check(
original: MessageRef<'_>,
sent: &[u8],
line_ends: TextLineEnds,
) -> Result<Vec<AttachmentCheck>, Error> {
let parsed = parse_sent(sent)?;
let comparison = Comparison::new(original, parsed.root(), line_ends)?;
let mut checks = Vec::with_capacity(
comparison.outgoing.len()
+ comparison
.candidates
.iter()
.filter(|candidate| !candidate.paired)
.count(),
);
checks.extend(
comparison
.outgoing
.iter()
.zip(comparison.pairs)
.map(|(attachment, pair)| match pair {
Some(Pair {
changed_name: Some(name),
..
}) => AttachmentCheck::Differs(name.to_owned()),
Some(pair) => {
comparison.candidates[pair.candidate].found(attachment.name.map(str::to_owned))
}
None => AttachmentCheck::Missing(attachment.name.map(str::to_owned)),
}),
);
checks.extend(
comparison
.candidates
.iter()
.filter(|candidate| !candidate.paired)
.map(|candidate| AttachmentCheck::NotSent(candidate.name().map(str::to_owned))),
);
Ok(checks)
}
struct Comparison<'r, 's> {
outgoing: Vec<Attachment<'s>>,
candidates: Vec<Candidate<'r>>,
pairs: Vec<Option<Pair<'s>>>,
}
impl<'r, 's> Comparison<'r, 's> {
fn new(
original: MessageRef<'r>,
sent: MessageRef<'s>,
line_ends: TextLineEnds,
) -> Result<Self, Error> {
let outgoing = attachments(sent, line_ends);
let mut candidates: Vec<_> = replaceable(original).map(Candidate::new).collect();
let pairs = assignment::assign(&outgoing, &mut candidates)?;
for candidate in &mut candidates {
if let Some(file) = candidate.file
&& !candidate.carried
&& candidate.hash.is_none()
{
return Err(Error::InvalidAttachmentHash(file.to_owned()));
}
}
Ok(Self {
outgoing,
candidates,
pairs,
})
}
}
#[derive(Clone, Copy)]
struct Pair<'a> {
candidate: usize,
changed_name: Option<&'a str>,
}
struct Candidate<'a> {
file: Option<&'a str>,
sha1: [u8; 20],
hash: Option<[u8; 20]>,
carried: bool,
paired: bool,
}
impl<'a> Candidate<'a> {
fn new(part: MessagePart<'a>) -> Self {
let decoded = part
.nested()
.map_or_else(|| part.decoded(), |message| message.raw().into());
let content: &[u8] = &decoded;
let file = part.attachment_name();
let hash_name = file.and_then(replaced_name);
Self {
file,
sha1: Sha1::digest(content).into(),
hash: file.and_then(|_| digest(content.trim_ascii())),
carried: hash_name.is_none(),
paired: false,
}
}
fn hash_name(&self) -> Option<&'a str> {
self.file.and_then(replaced_name)
}
fn name(&self) -> Option<&'a str> {
if self.carried {
self.file
} else {
self.hash_name().or(self.file)
}
}
const fn found(&self, name: Option<String>) -> AttachmentCheck {
if self.carried {
AttachmentCheck::Carried(name)
} else {
AttachmentCheck::Matches(name)
}
}
}
struct Attachment<'a> {
name: Option<&'a str>,
sha1: [u8; 20],
lf_sha1: Option<[u8; 20]>,
}
impl Attachment<'_> {
fn has(&self, sha1: &[u8; 20]) -> bool {
self.sha1 == *sha1 || self.lf_sha1.as_ref() == Some(sha1)
}
}
fn attachments(message: MessageRef<'_>, line_ends: TextLineEnds) -> Vec<Attachment<'_>> {
replaceable(message)
.map(|part| {
let decoded = part
.nested()
.map_or_else(|| part.decoded(), |message| message.raw().into());
let content: &[u8] = &decoded;
let lf_sha1 = (line_ends == TextLineEnds::CanonicalOrLf
&& (part.is_message() || is_text(&part)))
.then(|| lf_form(content))
.flatten()
.map(|lf| Sha1::digest(lf).into());
Attachment {
name: part.attachment_name(),
sha1: Sha1::digest(content).into(),
lf_sha1,
}
})
.collect()
}
fn is_text(part: &MessagePart<'_>) -> bool {
part.content_type()
.is_none_or(|content_type| content_type.ctype().eq_ignore_ascii_case("text"))
}
fn lf_form(text: &[u8]) -> Option<Vec<u8>> {
if !text.windows(2).any(|pair| pair == b"\r\n") {
return None;
}
let mut lf = Vec::with_capacity(text.len());
let mut bytes = text.iter().peekable();
while let Some(&byte) = bytes.next() {
if byte != b'\r' || bytes.peek() != Some(&&b'\n') {
lf.push(byte);
}
}
Some(lf)
}
fn replaceable(message: MessageRef<'_>) -> impl Iterator<Item = MessagePart<'_>> {
let root = message.root_part();
let content = if root.is_content_type("multipart", "signed") {
root.children().next()
} else {
Some(root)
};
let range = content.map(|part| part.offset_header()..part.offset_end());
let mut after = 0;
let skip_root = root.is_content_type("application", "pkcs7-mime")
|| root.is_content_type("application", "x-pkcs7-mime");
message
.parts()
.skip(usize::from(skip_root))
.filter(move |part| {
let offset = part.offset_header();
if offset < after || !range.as_ref().is_some_and(|range| range.contains(&offset)) {
return false;
}
if part.attachment_name().is_none() && !part.is_message() {
return false;
}
after = part.offset_end();
true
})
}
fn digest(hex: &[u8]) -> Option<[u8; 20]> {
let (pairs, []) = hex.as_chunks::<2>() else {
return None;
};
if pairs.len() != 20 {
return None;
}
let mut sha1 = [0; 20];
for (byte, [high, low]) in sha1.iter_mut().zip(pairs) {
*byte = nibble(*high)? << 4 | nibble(*low)?;
}
Some(sha1)
}
const fn nibble(digit: u8) -> Option<u8> {
match digit {
b'0'..=b'9' => Some(digit - b'0'),
b'a'..=b'f' => Some(digit - b'a' + 10),
b'A'..=b'F' => Some(digit - b'A' + 10),
_ => None,
}
}