Skip to content
Merged
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
250 changes: 232 additions & 18 deletions pkgs/id/src/directory_mail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,26 @@ impl MailSink for CommandSink {
}
}

/// The SMTP exchange's failure budget, and the bound that actually applies:
/// `RELAY_TIMEOUT` is the TOTAL deadline for one `send` — every reply must
/// finish within it, not merely make progress within it. The socket read and
/// write timeouts are also set to it, so a single silent read or write is
/// bounded by the same value, but a relay that keeps every read in-window
/// (a trickling reply) still fails at the deadline. One reply line may buffer
/// at most `MAX_REPLY_LINE_BYTES` and one reply may span at most
/// `MAX_REPLY_CONTINUATION_LINES` continuation lines, so a never-terminating
/// reply cannot grow memory or line counts without limit either.
const RELAY_TIMEOUT: Duration = Duration::from_secs(10);

/// Cap on one SMTP reply line's buffered length. RFC 5321 limits a text line
/// to 1000 octets including CRLF; this is generous by comparison so verbose
/// but well-formed relays still pass, while an unterminated line is refused
/// instead of buffering without limit.
const MAX_REPLY_LINE_BYTES: usize = 8_192;

/// Cap on the continuation (`250-...`) lines in one SMTP reply.
const MAX_REPLY_CONTINUATION_LINES: usize = 100;

/// Hands mail to an SMTP relay on this machine, with plain SMTP and no login.
#[derive(Clone, Debug)]
pub struct SmtpSink {
Expand Down Expand Up @@ -213,8 +231,8 @@ impl SmtpSink {
}
}

impl MailSink for SmtpSink {
fn send(&self, mail: &Mail) -> Result<()> {
impl SmtpSink {
fn send_with_timeout(&self, mail: &Mail, timeout: Duration) -> Result<()> {
ensure!(
mail.to.is_ascii(),
"cannot mail {}: it is internationalised (not ASCII), and the SMTP sink does not speak SMTPUTF8 (RFC 6531), so the message was not sent",
Expand All @@ -228,27 +246,30 @@ impl MailSink for SmtpSink {
!mail.subject.chars().any(char::is_control),
"the subject has a line break or control character"
);
let deadline = Instant::now() + timeout;
let stream = TcpStream::connect_timeout(&self.relay, RELAY_TIMEOUT)
.context("connect to the mail relay")?;
stream.set_read_timeout(Some(RELAY_TIMEOUT))?;
stream.set_write_timeout(Some(RELAY_TIMEOUT))?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut writer = stream;
expect(&mut reader, 220)?;
smtp_command(&mut writer, &mut reader, "EHLO id.local", 250)?;
expect(&mut reader, 220, deadline)?;
smtp_command(&mut writer, &mut reader, "EHLO id.local", 250, deadline)?;
smtp_command(
&mut writer,
&mut reader,
&format!("MAIL FROM:<{}>", self.from),
250,
deadline,
)?;
smtp_command(
&mut writer,
&mut reader,
&format!("RCPT TO:<{}>", mail.to),
250,
deadline,
)?;
smtp_command(&mut writer, &mut reader, "DATA", 354)?;
smtp_command(&mut writer, &mut reader, "DATA", 354, deadline)?;
let message = format!(
"From: {}\r\nTo: {}\r\nSubject: {}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n{}.\r\n",
self.from,
Expand All @@ -259,12 +280,18 @@ impl MailSink for SmtpSink {
writer
.write_all(message.as_bytes())
.context("write to the mail relay")?;
expect(&mut reader, 250)?;
let _ = smtp_command(&mut writer, &mut reader, "QUIT", 221);
expect(&mut reader, 250, deadline)?;
let _ = smtp_command(&mut writer, &mut reader, "QUIT", 221, deadline);
Ok(())
}
}

impl MailSink for SmtpSink {
fn send(&self, mail: &Mail) -> Result<()> {
self.send_with_timeout(mail, RELAY_TIMEOUT)
}
}

/// A bare address with no spaces, control characters or SMTP syntax in it.
fn plain_address(text: &str) -> bool {
text.contains('@')
Expand All @@ -288,27 +315,30 @@ fn dot_stuffed(body: &str) -> String {

fn smtp_command(
writer: &mut TcpStream,
reader: &mut impl BufRead,
reader: &mut BufReader<TcpStream>,
line: &str,
code: u16,
deadline: Instant,
) -> Result<()> {
writer
.write_all(format!("{line}\r\n").as_bytes())
.context("write to the mail relay")?;
expect(reader, code)
expect(reader, code, deadline)
}

/// Read one reply, which may span lines, and check its code.
fn expect(reader: &mut impl BufRead, code: u16) -> Result<()> {
///
/// The reply must finish before `deadline` (the send's total budget): the
/// socket read timeout is recomputed from the time remaining before every
/// underlying read (see `read_reply_line`), so a relay that sends a
/// continuation line — or a single byte — every few seconds, always inside
/// the socket inactivity window, still fails at the deadline.
fn expect(reader: &mut BufReader<TcpStream>, code: u16, deadline: Instant) -> Result<()> {
let mut continuations = 0_usize;
loop {
let mut line = String::new();
ensure!(
reader
.read_line(&mut line)
.context("read from the mail relay")?
> 0,
"the mail relay closed the connection"
);
let Some(line) = read_reply_line(reader, deadline)? else {
bail!("the mail relay closed the connection");
};
let line = line.trim_end();
ensure!(
line.get(..3).and_then(|c| c.parse::<u16>().ok()) == Some(code),
Expand All @@ -317,9 +347,73 @@ fn expect(reader: &mut impl BufRead, code: u16) -> Result<()> {
if line.as_bytes().get(3) != Some(&b'-') {
return Ok(());
}
continuations += 1;
ensure!(
continuations <= MAX_REPLY_CONTINUATION_LINES,
"the mail relay sent more than {MAX_REPLY_CONTINUATION_LINES} continuation lines in one reply"
);
}
}

/// Read one reply line (through its `\n`), or `None` if the relay closed the
/// connection before sending any byte of it.
///
/// The socket read timeout is recomputed from the time remaining before
/// EVERY underlying read, not once per line: `read_line` on a trickling
/// relay performs many socket reads per line, and a timeout set once would
/// let each of them run for the full inactivity window, stretching one line
/// far past the total deadline. The buffered length is checked as bytes
/// arrive, so an unterminated line is refused at the cap instead of
/// buffering without limit.
fn read_reply_line(reader: &mut BufReader<TcpStream>, deadline: Instant) -> Result<Option<String>> {
let mut bytes: Vec<u8> = Vec::new();
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
ensure!(
!remaining.is_zero(),
"the mail relay did not finish its reply before the send deadline"
);
reader
.get_ref()
.set_read_timeout(Some(remaining.min(RELAY_TIMEOUT)))?;
let available = match reader.fill_buf() {
Ok(buf) => buf,
Err(error) => {
if Instant::now() >= deadline {
bail!("the mail relay did not finish its reply before the send deadline");
}
return Err(error).context("read from the mail relay");
}
};
if available.is_empty() {
// EOF: no byte of this line at all is a closed connection; a
// partial line is returned for the caller to judge, matching
// read_line's behaviour at EOF.
if bytes.is_empty() {
return Ok(None);
}
break;
}
let (chunk, complete) = match available.iter().position(|&b| b == b'\n') {
Some(pos) => (&available[..=pos], true),
None => (available, false),
};
let chunk_len = chunk.len();
bytes.extend_from_slice(chunk);
reader.consume(chunk_len);
ensure!(
bytes.len() <= MAX_REPLY_LINE_BYTES,
"the mail relay sent a reply line longer than {MAX_REPLY_LINE_BYTES} bytes"
);
if complete {
break;
}
}
String::from_utf8(bytes)
.map(Some)
.context("the mail relay sent a reply line that is not valid UTF-8")
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
Expand Down Expand Up @@ -611,4 +705,124 @@ mod tests {
let error = sink.send(&smuggled).unwrap_err();
assert!(error.to_string().contains("recipient"));
}
/// A relay that answers EHLO with an endless trickle of continuation
/// lines, each well inside the socket read timeout.
fn trickling_relay() -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut writer = stream;
writer.write_all(b"220 fake ready\r\n").unwrap();
let mut line = String::new();
if reader.read_line(&mut line).unwrap() == 0 {
return;
}
while writer.write_all(b"250-trickle\r\n").is_ok() {
thread::sleep(Duration::from_millis(50));
}
});
addr
}

#[test]
fn a_trickling_reply_fails_at_the_total_deadline() {
let sink = SmtpSink::new(trickling_relay(), "id@example.test".to_owned()).unwrap();
let started = Instant::now();
let error = sink
.send_with_timeout(&sample(), Duration::from_millis(300))
.unwrap_err();
assert!(
error.to_string().contains("before the send deadline"),
"{error:#}"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"trickling reply took {:?} to fail",
started.elapsed()
);
}

/// A relay that answers EHLO with one line that never terminates.
fn giant_line_relay() -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut writer = stream;
writer.write_all(b"220 fake ready\r\n").unwrap();
let mut line = String::new();
if reader.read_line(&mut line).unwrap() == 0 {
return;
}
let flood = vec![b'x'; 64 * 1024];
let _ = writer.write_all(b"250-");
let _ = writer.write_all(&flood);
thread::sleep(Duration::from_secs(2));
});
addr
}

/// A relay that answers EHLO by trickling single bytes of one line,
/// never completing it — every socket read is fast, so only a timeout
/// recomputed per underlying read can enforce the total deadline.
fn byte_trickling_relay() -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut writer = stream;
writer.write_all(b"220 fake ready\r\n").unwrap();
let mut line = String::new();
if reader.read_line(&mut line).unwrap() == 0 {
return;
}
if writer.write_all(b"250-").is_err() {
return;
}
while writer.write_all(b"x").is_ok() {
thread::sleep(Duration::from_millis(20));
}
});
addr
}

#[test]
fn a_byte_trickling_line_fails_at_the_total_deadline() {
let sink = SmtpSink::new(byte_trickling_relay(), "id@example.test".to_owned()).unwrap();
let started = Instant::now();
let error = sink
.send_with_timeout(&sample(), Duration::from_millis(300))
.unwrap_err();
assert!(
error.to_string().contains("before the send deadline"),
"{error:#}"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"byte-trickling line took {:?} to fail",
started.elapsed()
);
}

#[test]
fn an_over_long_reply_line_is_refused_instead_of_buffered() {
let sink = SmtpSink::new(giant_line_relay(), "id@example.test".to_owned()).unwrap();
let started = Instant::now();
let error = sink
.send_with_timeout(&sample(), Duration::from_secs(5))
.unwrap_err();
assert!(
error.to_string().contains("reply line longer than"),
"{error:#}"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"over-long line took {:?} to fail",
started.elapsed()
);
}
}
Loading