Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/api/tests/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ impl Transport for Idle {
answer: Answer::Delivered,
reply: Vec::new(),
event: prepared.opener.event(c.recipient, c.stamp, &body).ok(),
bounced: None,
}
})
.collect()
Expand Down
78 changes: 78 additions & 0 deletions crates/deliver/src/classify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,39 @@ const THROTTLE: [&str; 6] = [
"too many concurrent",
];

const GONE: [&str; 9] = [
"user unknown",
"unknown user",
"no such user",
"no such mailbox",
"mailbox not found",
"recipient unknown",
"unknown recipient",
"user does not exist",
"mailbox does not exist",
];

const NOT_RECIPIENT: [&str; 2] = ["sender", "verif"];

pub fn gone(response: &Response) -> bool {
if !matches!(response.code, 550 | 551 | 553) {
return false;
}
match response.status {
Some((5, subject, detail)) => matches!((subject, detail), (1, 1 | 6 | 10) | (2, 1)),
Some(_) => false,
None => {
let text = response.lines.join(" ").to_ascii_lowercase();
let quoted = response
.lines
.iter()
.any(|l| l.trim_start().to_ascii_lowercase().starts_with("response:"));
let sender = NOT_RECIPIENT.iter().any(|w| text.contains(w));
!quoted && !sender && GONE.iter().any(|w| text.contains(w))
}
}
}

pub fn answer(response: &Response) -> Answer {
match response.code {
200..=399 => Answer::Delivered,
Expand Down Expand Up @@ -104,4 +137,49 @@ mod tests {
assert_eq!(answer(&response), want, "{}", response.text());
}
}

#[test]
fn only_mailbox_level_failures_are_gone() {
let cases = [
(response(550, Some((5, 1, 1)), "no such user"), true),
(response(550, Some((5, 1, 10)), "null MX"), true),
(response(551, Some((5, 1, 6)), "moved"), true),
(response(550, Some((5, 2, 1)), "account disabled"), true),
(response(550, None, "User unknown"), true),
(response(553, None, "mailbox does not exist"), true),
(response(550, Some((5, 7, 1)), "user unknown"), false),
(response(554, Some((5, 1, 1)), "no such user"), false),
(response(550, Some((5, 2, 2)), "mailbox full"), false),
(response(550, Some((4, 1, 1)), "no such user"), false),
(response(550, None, "blocked"), false),
(response(550, None, "sender domain does not exist"), false),
(response(450, Some((4, 1, 1)), "user unknown"), false),
(
Response {
code: 550,
status: None,
lines: vec![
"Verification failed for <noreply@example.com>".to_owned(),
"No Such User Here".to_owned(),
"Sender verify failed".to_owned(),
],
},
false,
),
(
Response {
code: 550,
status: None,
lines: vec![
"Callout check failed".to_owned(),
"Response: 550 5.1.1 <a@example.com> User unknown".to_owned(),
],
},
false,
),
];
for (response, want) in cases {
assert_eq!(gone(&response), want, "{}", response.text());
}
}
}
164 changes: 120 additions & 44 deletions crates/deliver/src/deliver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use control::{KIND_RPT, KIND_STS, Leases};
use dns::{Found, Name, Record, Type};
use rt::{Ends, Instant, JoinHandle, now, timeout, wall_ms};
use sched::{
Answer, Answered, Attempt, Body, Destination, Envelope, EventBody, EventKind, Kind, OwnStats,
Recipient, ReportMail, Reported, Required, Restore, Ret, Transport, TransportStats,
Answer, Answered, Attempt, Body, Bounced, Destination, Envelope, EventBody, EventKind, Kind,
OwnStats, Recipient, ReportMail, Reported, Required, Restore, Ret, Transport, TransportStats,
};
use smtp::client::{
self, Answer as Reply, Capabilities, Dots, Mail, Rcpt, Refused, Response, Step, Transaction,
Expand Down Expand Up @@ -72,6 +72,7 @@ pub struct Outcome {
pub recipient: u32,
pub answer: Answer,
pub reply: Vec<u8>,
pub gone: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -677,41 +678,22 @@ impl<D: Dns, L: Local> Deliver<D, L> {
.transact(&mut link.conn, &mut transaction, message)
.await;
let finished = run.is_ok();
let answers = transaction.answers();
let delivered = finished && answers.iter().any(|a| a == &Some(Reply::Accepted));
let mut closing = false;
let (done, lost) = match &run {
Ok(last) => {
closing = last.as_ref().is_some_and(|r| r.code == 421);
(last.as_ref().map(Response::text), Lost::Closed)
}
Err(lost) => (None, *lost),
let (done, lost, mut closing) = match &run {
Ok(last) => (
last.as_ref().map(Response::text),
Lost::Closed,
last.as_ref().is_some_and(|r| r.code == 421),
),
Err(lost) => (None, *lost, false),
};
let outcomes = message
.recipients
.iter()
.zip(answers)
.map(|((recipient, _), answer)| {
let (answer, reply) = match answer {
Some(Reply::Accepted) if finished => (
Answer::Delivered,
done.clone().unwrap_or_default().into_bytes(),
),
Some(Reply::Refused(r)) => {
closing |= r.code == 421;
(classify::answer(&r), r.text().into_bytes())
}
Some(Reply::Again(r)) if delivered => (Answer::Later(0), r.text().into_bytes()),
Some(Reply::Again(r)) => (TEMPORARY, r.text().into_bytes()),
_ => (TEMPORARY, lost.text().to_vec()),
};
Outcome {
recipient: *recipient,
answer,
reply,
}
})
.collect();
let (outcomes, refused_closing) = transacted(
message.recipients,
&transaction,
finished,
done.as_deref(),
lost,
);
closing |= refused_closing;
link.used += 1;
if finished && transaction.reusable() && !closing && link.used < self.settings.reuse {
self.pool.park(key.clone(), link).await;
Expand Down Expand Up @@ -1106,12 +1088,9 @@ impl<D: Dns, L: Local> Transport for Deliver<D, L> {
let (answer, reply) = outcome.map_or((TEMPORARY, Lost::Closed.text()), |o| {
(o.answer, o.reply.as_slice())
});
let address = prepared
.recipients
.iter()
.find(|(r, _)| *r == c.recipient)
.map(|(_, r)| r.address.as_bytes().to_vec())
.unwrap_or_default();
let found = address_of(&prepared.recipients, c.recipient);
let bounced = bounced(found, outcome, prepared.opener.generation());
let address = found.map(|a| a.as_bytes().to_vec()).unwrap_or_default();
let event = EventKind::of(answer).and_then(|kind| {
let body = EventBody {
kind,
Expand All @@ -1131,6 +1110,7 @@ impl<D: Dns, L: Local> Transport for Deliver<D, L> {
.seal_reply(c.recipient, c.stamp, reply)
.unwrap_or_default(),
event,
bounced,
}
})
.collect()
Expand Down Expand Up @@ -1162,13 +1142,70 @@ fn finished(
all(recipients, TEMPORARY, &last)
}

fn address_of(recipients: &[(u32, Recipient)], recipient: u32) -> Option<&str> {
recipients
.iter()
.find(|(r, _)| *r == recipient)
.map(|(_, r)| r.address.as_str())
}

fn bounced(address: Option<&str>, outcome: Option<&Outcome>, generation: u32) -> Option<Bounced> {
address
.filter(|_| outcome.is_some_and(|o| o.gone && o.answer == Answer::Failed))
.map(|address| Bounced {
generation,
address: address.into(),
})
}

fn transacted(
recipients: &[(u32, Recipient)],
transaction: &Transaction,
finished: bool,
done: Option<&str>,
lost: Lost,
) -> (Vec<Outcome>, bool) {
let answers = transaction.answers();
let delivered = finished && answers.iter().any(|a| a == &Some(Reply::Accepted));
let mut closing = false;
let outcomes = recipients
.iter()
.zip(answers)
.zip(transaction.refused_at_rcpt())
.map(|(((recipient, _), answer), at_rcpt)| {
let gone = at_rcpt && matches!(&answer, Some(Reply::Refused(r)) if classify::gone(r));
let (answer, reply) = match answer {
Some(Reply::Accepted) if finished => (
Answer::Delivered,
done.unwrap_or_default().as_bytes().to_vec(),
),
Some(Reply::Refused(r)) => {
closing |= r.code == 421;
(classify::answer(&r), r.text().into_bytes())
}
Some(Reply::Again(r)) if delivered => (Answer::Later(0), r.text().into_bytes()),
Some(Reply::Again(r)) => (TEMPORARY, r.text().into_bytes()),
_ => (TEMPORARY, lost.text().to_vec()),
};
Outcome {
recipient: *recipient,
answer,
reply,
gone,
}
})
.collect();
(outcomes, closing)
}

fn all(recipients: &[(u32, Recipient)], answer: Answer, reply: &[u8]) -> Vec<Outcome> {
recipients
.iter()
.map(|(recipient, _)| Outcome {
recipient: *recipient,
answer,
reply: reply.to_vec(),
gone: false,
})
.collect()
}
Expand Down Expand Up @@ -1247,9 +1284,48 @@ async fn body(conn: &mut Conn, message: &mut Message<'_>, limit: Duration) -> Re

#[cfg(test)]
mod tests {
use sched::Required;
use sched::{Answer, Bounced, Kind, Recipient, Required};

use super::honoured;
use super::{Outcome, address_of, bounced, honoured};

#[test]
fn only_a_gone_failure_names_its_own_address_and_generation() {
let recipients: Vec<(u32, Recipient)> = [(4, "a@example.com"), (9, "b@example.com")]
.into_iter()
.map(|(r, address)| {
let recipient = Recipient {
address: address.to_owned(),
..Recipient::default()
};
(r, recipient)
})
.collect();
let outcome = |answer, gone| Outcome {
recipient: 9,
answer,
reply: Vec::new(),
gone,
};
let gone = outcome(Answer::Failed, true);
assert_eq!(
bounced(address_of(&recipients, 9), Some(&gone), 7),
Some(Bounced {
generation: 7,
address: "b@example.com".into(),
})
);
assert_eq!(address_of(&recipients, 4), Some("a@example.com"));
assert_eq!(address_of(&recipients, 5), None);
assert_eq!(bounced(None, Some(&gone), 7), None);
assert_eq!(bounced(address_of(&recipients, 9), None, 7), None);
for other in [
outcome(Answer::Failed, false),
outcome(Answer::Deferred(Kind::Temporary), true),
outcome(Answer::Delivered, true),
] {
assert_eq!(bounced(address_of(&recipients, 9), Some(&other), 7), None);
}
}

#[test]
fn only_the_report_tenant_keeps_tls_optional() {
Expand Down
2 changes: 1 addition & 1 deletion crates/deliver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ mod sts;
mod upload;

pub use address::{Bind, Cidr, Local};
pub use classify::{answer, kind};
pub use classify::{answer, gone, kind};
pub use deliver::{Deliver, Due, Message, Outcome};
pub use gzip::gzip;
pub use hook::{HookSettings, Hooks, delivery_id, signature};
Expand Down
5 changes: 5 additions & 0 deletions crates/deliver/tests/deliver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,8 @@ fn answers_each_recipient() {
]
);
assert_eq!(reply(&outcomes[1]), "550 5.1.1 no such user");
let gone: Vec<bool> = outcomes.iter().map(|o| o.gone).collect();
assert_eq!(gone, [false, true, false, false, false]);
assert_eq!(seen.borrow().bodies.len(), 1);
}

Expand Down Expand Up @@ -454,6 +456,8 @@ fn transaction_replies_answer_everyone() {
),
("250 2.1.0 ok", "554 5.7.1 spam", Answer::Failed),
("250 2.1.0 ok", "451 4.3.0 try later", TEMPORARY),
("550 5.1.1 no such user", "250 2.0.0 queued", Answer::Failed),
("250 2.1.0 ok", "550 5.1.1 no such user", Answer::Failed),
];
for (mail, done, want) in cases {
let outcomes = run(async move {
Expand All @@ -472,6 +476,7 @@ fn transaction_replies_answer_everyone() {
.await
});
assert_eq!(answers(&outcomes), [want, want], "{mail} / {done}");
assert!(outcomes.iter().all(|o| !o.gone), "{mail} / {done}");
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/intake/tests/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ fn answered(claimed: &[Claimed], answer: Answer) -> Vec<Answered> {
answer,
reply: Vec::new(),
event: None,
bounced: None,
})
.collect()
}
Expand Down
4 changes: 4 additions & 0 deletions crates/node/src/scrape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ catalog! {
AttemptsUnrouted: Counter, "attempts_unrouted", "Delivery attempts that found no route";
AttemptsUnreadable: Counter, "attempts_unreadable", "Delivery attempts skipped because the message could not be read";
SigningFaults: Counter, "signing_faults", "Signing attempts refused for a message format fault";
SuppressionsBounced: Counter, "suppressions_bounced", "Recipients suppressed after a mailbox-level hard failure";
SuppressionsBounceFailed: Counter, "suppressions_bounce_failed", "Mailbox-level hard failures that could not be suppressed";
SchedRefused: Counter, "sched_refused", "Scheduler entries and notes refused as stale or invalid";
RecipientsDelivered: Counter, "recipients_delivered", "Recipient attempts answered as delivered";
RecipientsFailed: Counter, "recipients_failed", "Recipient attempts answered as failed";
Expand Down Expand Up @@ -162,6 +164,8 @@ impl<T: Transport + 'static> Sources<'_, T> {
set(Id::AttemptsUnrouted, sched.unrouted());
set(Id::AttemptsUnreadable, sched.unreadable());
set(Id::SigningFaults, sched.unsigned());
set(Id::SuppressionsBounced, sched.bounced());
set(Id::SuppressionsBounceFailed, sched.bounce_failed());
set(Id::SchedRefused, sched.refused());
set(Id::TicksLate, self.node.ticks_late());
let answers = sched.answers();
Expand Down
2 changes: 1 addition & 1 deletion crates/sched/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub use suppress::{
};
pub use system::{Done, RecordStats, Records, Restore, Saved, Unsaved};
pub use transport::{
Answered, Attempt, Claimed, Destination, OwnStats, ReportMail, Reported, Transport,
Answered, Attempt, Bounced, Claimed, Destination, OwnStats, ReportMail, Reported, Transport,
TransportStats,
};
pub use unopened::{Action, DROPS_PER_MINUTE, UnopenedStats, action};
Loading
Loading