use crate::{DeliveryReceipt, Mail, MailError, MailResult, MailTransport, Mailbox, PreparedMail};
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use std::{
fs::{self, File, OpenOptions},
future::Future,
io::{Read, Write},
path::{Path, PathBuf},
pin::Pin,
time::{SystemTime, UNIX_EPOCH},
};
const MAX_BYTES: u64 = 64 * 1024 * 1024;
const MAX_MESSAGES: usize = 100;
#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct CaptureContent {
from: Mailbox,
text: Option<String>,
html: Option<String>,
headers: Vec<(String, String)>,
}
impl CaptureContent {
pub(crate) fn new(mail: &Mail, default_from: &Mailbox) -> Self {
Self {
from: mail.from.clone().unwrap_or_else(|| default_from.clone()),
text: mail.text.clone(),
html: mail.html.clone(),
headers: mail.headers.clone(),
}
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct CapturedMail {
id: String,
message_id: String,
message_type: String,
subject: String,
recipients: Vec<Mailbox>,
content: CaptureContent,
mime: String,
timestamp_ms: u64,
}
impl CapturedMail {
pub(crate) fn from_prepared(mail: PreparedMail) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
mime: String::from_utf8_lossy(&mail.message.formatted()).into_owned(),
message_id: mail.message_id,
message_type: mail.message_type,
subject: mail.subject,
recipients: mail.recipients,
content: mail.content,
timestamp_ms: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64,
}
}
pub(crate) fn bytes(&self) -> usize {
self.mime.len()
+ self.content.text.as_ref().map_or(0, String::len)
+ self.content.html.as_ref().map_or(0, String::len)
+ self.subject.len()
+ self.recipients.len() * 512
+ 8192
}
pub fn id(&self) -> &str {
&self.id
}
pub fn message_id(&self) -> &str {
&self.message_id
}
pub fn timestamp_ms(&self) -> u64 {
self.timestamp_ms
}
pub fn sender(&self) -> &Mailbox {
&self.content.from
}
pub fn recipients(&self) -> &[Mailbox] {
&self.recipients
}
pub fn subject(&self) -> &str {
&self.subject
}
pub fn text(&self) -> Option<&str> {
self.content.text.as_deref()
}
pub fn html(&self) -> Option<&str> {
self.content.html.as_deref()
}
pub fn headers(&self) -> &[(String, String)] {
&self.content.headers
}
pub fn raw_message(&self) -> Vec<u8> {
self.mime.as_bytes().to_vec()
}
pub fn was_sent_to(&self, address: &str) -> bool {
self.recipients.iter().any(|r| r.address() == address)
}
pub fn has_subject(&self, subject: &str) -> bool {
self.subject == subject
}
pub fn is_type<M: crate::Mailable>(&self) -> bool {
self.message_type == M::NAME
}
}
impl std::fmt::Debug for CapturedMail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("CapturedMail([REDACTED])")
}
}
#[derive(Clone)]
pub struct DevelopmentInbox {
directory: PathBuf,
}
impl DevelopmentInbox {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self {
directory: path.into(),
}
}
fn lock(&self) -> MailResult<File> {
let mut builder = fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder
.create(&self.directory)
.map_err(|_| MailError::CaptureStorage)?;
let metadata =
fs::symlink_metadata(&self.directory).map_err(|_| MailError::CaptureStorage)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(MailError::CaptureStorage);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(MailError::CaptureStorage);
}
}
let path = self.directory.join(".lock");
reject_symlink(&path)?;
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let lock = options.open(path).map_err(|_| MailError::CaptureStorage)?;
lock.lock_exclusive()
.map_err(|_| MailError::CaptureStorage)?;
Ok(lock)
}
fn files(&self) -> MailResult<Vec<PathBuf>> {
let mut files = Vec::new();
for entry in fs::read_dir(&self.directory).map_err(|_| MailError::CaptureStorage)? {
let entry = entry.map_err(|_| MailError::CaptureStorage)?;
let path = entry.path();
if path.extension().is_some_and(|v| v == "json") {
reject_symlink(&path)?;
files.push(path);
}
}
if files.len() > MAX_MESSAGES {
return Err(MailError::CaptureFull);
}
Ok(files)
}
fn read(path: &Path) -> MailResult<CapturedMail> {
reject_symlink(path)?;
let file = File::open(path).map_err(|_| MailError::CaptureStorage)?;
if file
.metadata()
.map_err(|_| MailError::CaptureStorage)?
.len()
> MAX_BYTES
{
return Err(MailError::CaptureFull);
}
let mut bytes = Vec::new();
file.take(MAX_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|_| MailError::CaptureStorage)?;
if bytes.len() as u64 > MAX_BYTES {
return Err(MailError::CaptureFull);
}
serde_json::from_slice(&bytes).map_err(|_| MailError::CaptureStorage)
}
pub fn list(&self) -> MailResult<Vec<CapturedMail>> {
let _lock = self.lock()?;
let files = self.files()?;
let total = files
.iter()
.try_fold(0u64, |total, p| {
fs::metadata(p).map(|m| total.saturating_add(m.len()))
})
.map_err(|_| MailError::CaptureStorage)?;
if total > MAX_BYTES {
return Err(MailError::CaptureFull);
}
let mut messages = files
.iter()
.map(|p| Self::read(p))
.collect::<MailResult<Vec<_>>>()?;
messages.sort_by(|a, b| (a.timestamp_ms, &a.id).cmp(&(b.timestamp_ms, &b.id)));
Ok(messages)
}
pub fn show(&self, id: &str) -> MailResult<CapturedMail> {
let id = uuid::Uuid::parse_str(id).map_err(|_| MailError::CaptureStorage)?;
let _lock = self.lock()?;
Self::read(&self.directory.join(format!("{id}.json")))
}
pub fn clear(&self) -> MailResult<usize> {
let _lock = self.lock()?;
let files = self.files()?;
for file in &files {
fs::remove_file(file).map_err(|_| MailError::CaptureStorage)?;
}
Ok(files.len())
}
fn store(&self, mail: CapturedMail) -> MailResult<()> {
let _lock = self.lock()?;
let bytes = serde_json::to_vec(&mail).map_err(|_| MailError::CaptureStorage)?;
let files = self.files()?;
let retained = files
.iter()
.try_fold(0u64, |total, p| {
fs::metadata(p).map(|m| total.saturating_add(m.len()))
})
.map_err(|_| MailError::CaptureStorage)?;
if files.len() >= MAX_MESSAGES || retained.saturating_add(bytes.len() as u64) > MAX_BYTES {
return Err(MailError::CaptureFull);
}
let mut file = tempfile::NamedTempFile::new_in(&self.directory)
.map_err(|_| MailError::CaptureStorage)?;
file.write_all(&bytes)
.map_err(|_| MailError::CaptureStorage)?;
file.as_file()
.sync_all()
.map_err(|_| MailError::CaptureStorage)?;
file.persist_noclobber(self.directory.join(format!("{}.json", mail.id)))
.map_err(|_| MailError::CaptureStorage)?;
tracing::debug!(event = "mail.capture.stored");
Ok(())
}
}
fn reject_symlink(path: &Path) -> MailResult<()> {
match fs::symlink_metadata(path) {
Ok(m) if m.file_type().is_symlink() || !m.is_file() => Err(MailError::CaptureStorage),
Ok(_) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(_) => Err(MailError::CaptureStorage),
}
}
impl MailTransport for DevelopmentInbox {
fn name(&self) -> &'static str {
"capture"
}
fn development_only(&self) -> bool {
true
}
fn send(
&self,
mail: PreparedMail,
) -> Pin<Box<dyn Future<Output = MailResult<DeliveryReceipt>> + Send + '_>> {
Box::pin(async move {
let inbox = self.clone();
let receipt = DeliveryReceipt {
message_id: mail.message_id.clone(),
provider_id: None,
};
tokio::task::spawn_blocking(move || inbox.store(CapturedMail::from_prepared(mail)))
.await
.map_err(|_| MailError::CaptureStorage)??;
Ok(receipt)
})
}
}