Skip to main content

turnloop_smtp/
lib.rs

1#![deny(unsafe_op_in_unsafe_fn)]
2//!
3//! # Getting started on turnloop
4//! Enable the `turnloop` feature for the `asynchronous` module. The embedding
5//! host owns `LocalExecutor` and calls `turn`; adapters await its streams and
6//! deadline futures. See the crate README and turnloop-io for ownership, streaming
7//! and cancellation examples. Default features retain the sans-I/O API.
8
9//! Pull-driven SMTP with explicit TLS transitions. Socket, DNS, certificate
10//! policy and clock ownership remain in the host. `Ready` also completes verify.
11pub mod message;
12use base64::{Engine, engine::general_purpose::STANDARD};
13use std::{
14    collections::VecDeque,
15    io::Write,
16    time::{Duration, Instant},
17};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Tls {
21    /// Never attempt STARTTLS (nodemailer `ignoreTLS`).
22    None,
23    /// Upgrade with STARTTLS when the server offers it, otherwise stay in the clear.
24    Opportunistic,
25    /// Upgrade with STARTTLS or fail. A server that does not offer STARTTLS, or
26    /// refuses it, yields `Failed` with code `ETLS` before any AUTH is sent,
27    /// followed by `CloseTransport` and `Closed`; `Ready` is never reached in
28    /// the clear (nodemailer `requireTLS`).
29    Required,
30    /// TLS from the first byte (nodemailer `secure`).
31    Implicit,
32}
33#[derive(Clone)]
34pub enum Auth {
35    Plain { user: String, password: String },
36    Login { user: String, password: String },
37    Xoauth2 { user: String, access_token: String },
38}
39#[derive(Clone)]
40pub struct Config {
41    pub name: String,
42    pub tls: Tls,
43    pub auth: Option<Auth>,
44    pub greeting_timeout: Duration,
45    pub socket_timeout: Duration,
46    pub max_response_bytes: usize,
47}
48impl Default for Config {
49    fn default() -> Self {
50        Self {
51            name: "[127.0.0.1]".into(),
52            tls: Tls::Opportunistic,
53            auth: None,
54            greeting_timeout: Duration::from_secs(30),
55            socket_timeout: Duration::from_secs(600),
56            max_response_bytes: 64 * 1024,
57        }
58    }
59}
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct Capabilities {
62    pub starttls: bool,
63    pub pipelining: bool,
64    pub size: Option<u64>,
65    pub size_supported: bool,
66    pub eight_bit_mime: bool,
67    pub smtp_utf8: bool,
68    pub auth_plain: bool,
69    pub auth_login: bool,
70    pub auth_xoauth2: bool,
71}
72impl Capabilities {
73    fn parse(&mut self, response: &str) {
74        *self = Self::default();
75        // First EHLO line is the server greeting, not an extension.
76        for line in response.lines().skip(1) {
77            let Some(text) = line.get(4..) else {
78                continue;
79            };
80            let mut words = text.split_ascii_whitespace();
81            let Some(name) = words.next() else {
82                continue;
83            };
84            if name.eq_ignore_ascii_case("STARTTLS") {
85                self.starttls = true;
86            } else if name.eq_ignore_ascii_case("PIPELINING") {
87                self.pipelining = true;
88            } else if name.eq_ignore_ascii_case("8BITMIME") {
89                self.eight_bit_mime = true;
90            } else if name.eq_ignore_ascii_case("SMTPUTF8") {
91                self.smtp_utf8 = true;
92            } else if name.eq_ignore_ascii_case("SIZE") {
93                self.size_supported = true;
94                self.size = words.next().and_then(|v| v.parse().ok());
95            } else if name.eq_ignore_ascii_case("AUTH")
96                || name.to_ascii_uppercase().starts_with("AUTH=")
97            {
98                for word in name.get(5..).into_iter().chain(words) {
99                    if word.eq_ignore_ascii_case("PLAIN") {
100                        self.auth_plain = true;
101                    }
102                    if word.eq_ignore_ascii_case("LOGIN") {
103                        self.auth_login = true;
104                    }
105                    if word.eq_ignore_ascii_case("XOAUTH2") {
106                        self.auth_xoauth2 = true;
107                    }
108                }
109            }
110        }
111    }
112}
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct Envelope {
115    pub from: String,
116    pub to: Vec<String>,
117}
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct Error {
120    pub code: &'static str,
121    pub message: String,
122    pub response: String,
123    pub response_code: Option<u16>,
124    pub command: &'static str,
125}
126impl std::fmt::Display for Error {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        f.write_str(&self.message)
129    }
130}
131impl std::error::Error for Error {}
132fn error(
133    code: &'static str,
134    command: &'static str,
135    message: &str,
136    response_code: Option<u16>,
137    response: &str,
138) -> Error {
139    Error {
140        code,
141        command,
142        message: if response.is_empty() {
143            message.into()
144        } else {
145            format!("{message}: {response}")
146        },
147        response_code,
148        response: response.into(),
149    }
150}
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Rejection {
153    pub recipient: String,
154    pub error: Error,
155}
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct SendInfo {
158    pub response: String,
159    pub response_code: u16,
160    pub accepted: Vec<String>,
161    pub rejected: Vec<Rejection>,
162    pub envelope: Envelope,
163    pub message_id: String,
164}
165#[derive(Debug, PartialEq, Eq)]
166pub enum Event {
167    UpgradeTls,
168    Ready,
169    Sent {
170        token: u64,
171        info: SendInfo,
172    },
173    /// A streamed message's DATA was accepted (354): write its content with
174    /// [`Connection::send_chunk`] and end it with [`Connection::finish_body`].
175    BodyReady {
176        token: u64,
177    },
178    Failed {
179        token: Option<u64>,
180        error: Error,
181        envelope: Option<Envelope>,
182        accepted: Vec<String>,
183        rejected: Vec<Rejection>,
184    },
185    Reset,
186    CloseTransport,
187    Closed,
188}
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum State {
191    Disconnected,
192    Tls,
193    Greeting,
194    Ehlo,
195    Helo,
196    StartTls,
197    Auth,
198    LoginUser,
199    LoginPassword,
200    OAuthFailure,
201    Ready,
202    Mail,
203    Recipients,
204    Data,
205    Body,
206    Reset,
207    Quit,
208    Closed,
209}
210pub struct Connection {
211    config: Config,
212    state: State,
213    secure: bool,
214    implicit_pending: bool,
215    capabilities: Capabilities,
216    tx: Vec<u8>,
217    tx_pos: usize,
218    rx: Vec<u8>,
219    response: String,
220    response_code: Option<u16>,
221    auth_raw: Vec<u8>,
222    auth_encoded: String,
223    body: Vec<u8>,
224    streaming: Option<StreamBody>,
225    encoder: DataEncoder,
226    body_open: bool,
227    events: VecDeque<Event>,
228    deadline: Option<Instant>,
229    token: Option<u64>,
230    envelope: Option<Envelope>,
231    message_id: String,
232    accepted: Vec<String>,
233    rejected: Vec<Rejection>,
234    recipient_index: usize,
235    mail_error: Option<Error>,
236    automatic_reset: bool,
237}
238impl Connection {
239    pub fn new(config: Config) -> Result<Self, Error> {
240        if config.name.is_empty() || config.name.bytes().any(|b| b <= b' ' || b == 127) {
241            return Err(error("EINVAL", "EHLO", "Invalid client hostname", None, ""));
242        }
243        Ok(Self {
244            config,
245            state: State::Disconnected,
246            secure: false,
247            implicit_pending: false,
248            capabilities: Capabilities::default(),
249            tx: Vec::with_capacity(4096),
250            tx_pos: 0,
251            rx: Vec::with_capacity(4096),
252            response: String::with_capacity(1024),
253            response_code: None,
254            auth_raw: Vec::with_capacity(256),
255            auth_encoded: String::with_capacity(512),
256            body: Vec::with_capacity(8192),
257            streaming: None,
258            encoder: DataEncoder::new(),
259            body_open: false,
260            events: VecDeque::with_capacity(16),
261            deadline: None,
262            token: None,
263            envelope: None,
264            message_id: String::new(),
265            accepted: Vec::new(),
266            rejected: Vec::new(),
267            recipient_index: 0,
268            mail_error: None,
269            automatic_reset: false,
270        })
271    }
272    pub fn state(&self) -> State {
273        self.state
274    }
275    pub fn capabilities(&self) -> &Capabilities {
276        &self.capabilities
277    }
278    pub fn output(&self) -> &[u8] {
279        &self.tx[self.tx_pos..]
280    }
281    pub fn consume_output(&mut self, count: usize) {
282        assert!(count <= self.output().len());
283        self.tx_pos += count;
284        if self.tx_pos == self.tx.len() {
285            self.tx.clear();
286            self.tx_pos = 0;
287        }
288    }
289    pub fn poll_event(&mut self) -> Option<Event> {
290        self.events.pop_front()
291    }
292    pub fn connected(&mut self, now: Instant) -> Result<(), Error> {
293        if self.state != State::Disconnected {
294            return Err(error("ESTATE", "CONN", "Already connected", None, ""));
295        }
296        self.deadline = now.checked_add(self.config.greeting_timeout);
297        if self.config.tls == Tls::Implicit {
298            self.state = State::Tls;
299            self.implicit_pending = true;
300            self.events.push_back(Event::UpgradeTls);
301        } else {
302            self.state = State::Greeting;
303        }
304        Ok(())
305    }
306    pub fn tls_established(&mut self, now: Instant) -> Result<(), Error> {
307        if self.state != State::Tls {
308            return Err(error(
309                "ESTATE",
310                "STARTTLS",
311                "Unexpected TLS completion",
312                None,
313                "",
314            ));
315        }
316        self.secure = true;
317        self.capabilities = Capabilities::default();
318        if self.implicit_pending {
319            self.implicit_pending = false;
320            self.state = State::Greeting;
321            self.deadline = now.checked_add(self.config.greeting_timeout);
322        } else {
323            self.ehlo();
324            self.arm(now);
325        }
326        Ok(())
327    }
328    fn arm(&mut self, now: Instant) {
329        self.deadline = now.checked_add(self.config.socket_timeout);
330    }
331    fn ehlo(&mut self) {
332        self.state = State::Ehlo;
333        write!(self.tx, "EHLO {}\r\n", self.config.name).unwrap();
334    }
335    pub fn receive(&mut self, bytes: &[u8], now: Instant) -> Result<(), Error> {
336        if matches!(self.state, State::Disconnected | State::Tls | State::Closed) {
337            return Err(error(
338                "ESTATE",
339                "CONN",
340                "Bytes outside SMTP protocol state",
341                None,
342                "",
343            ));
344        }
345        if self.state != State::Greeting {
346            self.arm(now);
347        }
348        for chunk in bytes.chunks(4096) {
349            self.rx.extend_from_slice(chunk);
350            while let Some(end) = self.rx.iter().position(|b| *b == b'\n') {
351                if end < 4
352                    || self.rx[end - 1] != b'\r'
353                    || !self.rx[..3].iter().all(u8::is_ascii_digit)
354                    || !matches!(self.rx[3], b' ' | b'-')
355                {
356                    return self.protocol_error("Invalid SMTP response");
357                }
358                let code = u16::from(self.rx[0] - b'0') * 100
359                    + u16::from(self.rx[1] - b'0') * 10
360                    + u16::from(self.rx[2] - b'0');
361                if !(200..600).contains(&code) || self.response_code.is_some_and(|c| c != code) {
362                    return self.protocol_error("Inconsistent SMTP response code");
363                }
364                self.response_code = Some(code);
365                if !self.response.is_empty() {
366                    self.response.push('\n');
367                }
368                self.response
369                    .push_str(&String::from_utf8_lossy(&self.rx[..end - 1]));
370                let complete = self.rx[3] == b' ';
371                self.rx.drain(..=end);
372                if self.response.len() > self.config.max_response_bytes {
373                    return self.protocol_error("SMTP response too large");
374                }
375                if complete {
376                    self.response_code = None;
377                    let mut response = std::mem::take(&mut self.response);
378                    self.reply(code, &response);
379                    if !matches!(self.state, State::Closed | State::Greeting) {
380                        self.arm(now);
381                    }
382                    response.clear();
383                    self.response = response;
384                    if self.state == State::Tls && !self.rx.is_empty() {
385                        return self.protocol_error("Unexpected plaintext after STARTTLS");
386                    }
387                    if self.state == State::Closed {
388                        break;
389                    }
390                }
391            }
392            if self.rx.len() + self.response.len() > self.config.max_response_bytes {
393                return self.protocol_error("SMTP response too large");
394            }
395        }
396        Ok(())
397    }
398    fn protocol_error(&mut self, message: &str) -> Result<(), Error> {
399        let e = error("EPROTOCOL", self.command_name(), message, None, "");
400        self.fail(e.clone());
401        self.close_transport();
402        Err(e)
403    }
404    fn reply(&mut self, code: u16, response: &str) {
405        if code == 421 {
406            let e = error(
407                "ECONNECTION",
408                self.command_name(),
409                "Server closed connection",
410                Some(code),
411                response,
412            );
413            self.fail(e);
414            self.close_transport();
415            return;
416        }
417        match self.state {
418            State::Greeting if code == 220 => self.ehlo(),
419            State::Ehlo if code == 250 => {
420                self.capabilities.parse(response);
421                self.after_ehlo();
422            }
423            State::Ehlo if matches!(code, 500 | 502 | 504) => {
424                self.state = State::Helo;
425                write!(self.tx, "HELO {}\r\n", self.config.name).unwrap();
426            }
427            State::Helo if code == 250 => {
428                self.capabilities = Capabilities::default();
429                self.after_ehlo();
430            }
431            State::StartTls if code == 220 => {
432                self.state = State::Tls;
433                self.events.push_back(Event::UpgradeTls);
434            }
435            State::Auth if code == 235 => self.ready(),
436            State::Auth if code == 334 => match &self.config.auth {
437                Some(Auth::Login { user, .. }) => {
438                    self.auth_raw.clear();
439                    self.auth_raw.extend_from_slice(user.as_bytes());
440                    self.auth_line();
441                    self.state = State::LoginUser;
442                }
443                Some(Auth::Plain { .. }) => {
444                    self.auth_line();
445                    self.state = State::LoginPassword;
446                }
447                Some(Auth::Xoauth2 { .. }) => {
448                    self.tx.extend_from_slice(b"\r\n");
449                    self.state = State::OAuthFailure;
450                }
451                None => self.unexpected(code, response),
452            },
453            State::LoginUser if code == 334 => {
454                if let Some(Auth::Login { password, .. }) = &self.config.auth {
455                    self.auth_raw.clear();
456                    self.auth_raw.extend_from_slice(password.as_bytes());
457                    self.auth_line();
458                    self.state = State::LoginPassword;
459                }
460            }
461            State::LoginPassword if code == 235 => self.ready(),
462            State::Mail => {
463                if code != 250 {
464                    self.mail_error = Some(error(
465                        "EENVELOPE",
466                        "MAIL FROM",
467                        "Mail command failed",
468                        Some(code),
469                        response,
470                    ));
471                }
472                self.state = State::Recipients;
473                if !self.capabilities.pipelining {
474                    if let Some(e) = self.mail_error.take() {
475                        self.fail_and_reset(e);
476                    } else {
477                        self.rcpt(0);
478                    }
479                }
480            }
481            State::Recipients => {
482                let recipient = self.envelope.as_ref().unwrap().to[self.recipient_index].clone();
483                if matches!(code, 250..=252) && self.mail_error.is_none() {
484                    self.accepted.push(recipient);
485                } else {
486                    self.rejected.push(Rejection {
487                        recipient,
488                        error: error(
489                            "EENVELOPE",
490                            "RCPT TO",
491                            "Recipient command failed",
492                            Some(code),
493                            response,
494                        ),
495                    });
496                }
497                self.recipient_index += 1;
498                if self.recipient_index == self.envelope.as_ref().unwrap().to.len() {
499                    if let Some(e) = self.mail_error.take() {
500                        self.fail_and_reset(e);
501                    } else if self.accepted.is_empty() {
502                        self.fail_and_reset(error(
503                            "EENVELOPE",
504                            "RCPT TO",
505                            "Can't send mail - all recipients were rejected",
506                            Some(code),
507                            response,
508                        ));
509                    } else {
510                        self.tx.extend_from_slice(b"DATA\r\n");
511                        self.state = State::Data;
512                    }
513                } else if !self.capabilities.pipelining {
514                    self.rcpt(self.recipient_index);
515                }
516            }
517            State::Data if code == 354 => {
518                self.state = State::Body;
519                if self.streaming.is_some() {
520                    self.encoder = DataEncoder::new();
521                    self.body_open = true;
522                    let token = self.token.unwrap();
523                    self.events.push_back(Event::BodyReady { token });
524                } else {
525                    self.tx.extend_from_slice(&self.body);
526                }
527            }
528            State::Body if code == 250 && !self.body_open => {
529                let token = self.token.take().unwrap();
530                let info = SendInfo {
531                    response: response.into(),
532                    response_code: code,
533                    accepted: std::mem::take(&mut self.accepted),
534                    rejected: std::mem::take(&mut self.rejected),
535                    envelope: self.envelope.take().unwrap(),
536                    message_id: std::mem::take(&mut self.message_id),
537                };
538                self.events.push_back(Event::Sent { token, info });
539                self.state = State::Ready;
540            }
541            State::Reset if code == 250 => {
542                self.state = State::Ready;
543                if self.automatic_reset {
544                    self.automatic_reset = false;
545                } else {
546                    self.events.push_back(Event::Reset);
547                }
548            }
549            State::Quit if code == 221 => self.close_transport(),
550            _ => self.unexpected(code, response),
551        }
552    }
553    fn after_ehlo(&mut self) {
554        if !self.secure && self.config.tls != Tls::None && self.capabilities.starttls {
555            self.tx.extend_from_slice(b"STARTTLS\r\n");
556            self.state = State::StartTls;
557        } else if !self.secure && self.config.tls == Tls::Required {
558            self.fail(error(
559                "ETLS",
560                "STARTTLS",
561                "Error upgrading connection with STARTTLS: server does not support STARTTLS",
562                None,
563                "",
564            ));
565            self.close_transport();
566        } else {
567            self.authenticate();
568        }
569    }
570    fn authenticate(&mut self) {
571        self.auth_raw.clear();
572        match &self.config.auth {
573            None => {
574                self.ready();
575                return;
576            }
577            Some(Auth::Plain { user, password }) if self.capabilities.auth_plain => {
578                self.auth_raw.push(0);
579                self.auth_raw.extend_from_slice(user.as_bytes());
580                self.auth_raw.push(0);
581                self.auth_raw.extend_from_slice(password.as_bytes());
582                self.tx.extend_from_slice(b"AUTH PLAIN ");
583                self.auth_line();
584            }
585            Some(Auth::Login { .. }) if self.capabilities.auth_login => {
586                self.tx.extend_from_slice(b"AUTH LOGIN\r\n")
587            }
588            Some(Auth::Xoauth2 { user, access_token }) if self.capabilities.auth_xoauth2 => {
589                write!(
590                    self.auth_raw,
591                    "user={user}\x01auth=Bearer {access_token}\x01\x01"
592                )
593                .unwrap();
594                self.tx.extend_from_slice(b"AUTH XOAUTH2 ");
595                self.auth_line();
596            }
597            _ => {
598                self.fail(error(
599                    "EAUTH",
600                    "AUTH",
601                    "No supported authentication method",
602                    None,
603                    "",
604                ));
605                self.close_transport();
606                return;
607            }
608        }
609        self.state = State::Auth;
610    }
611    fn auth_line(&mut self) {
612        self.auth_encoded.clear();
613        STANDARD.encode_string(&self.auth_raw, &mut self.auth_encoded);
614        self.tx.extend_from_slice(self.auth_encoded.as_bytes());
615        self.tx.extend_from_slice(b"\r\n");
616    }
617    /// Whether the configured TLS policy forbids a plaintext session.
618    fn tls_mandatory(&self) -> bool {
619        matches!(self.config.tls, Tls::Required | Tls::Implicit)
620    }
621    /// The only transition to `Ready`. `after_ehlo` already refuses to AUTH in
622    /// the clear under `Tls::Required`; this re-checks at the transition itself so
623    /// no path can hand the host a plaintext session its policy forbids.
624    fn ready(&mut self) {
625        if self.tls_mandatory() && !self.secure {
626            self.fail(error(
627                "ETLS",
628                "STARTTLS",
629                "TLS is required but the SMTP session was never encrypted",
630                None,
631                "",
632            ));
633            self.close_transport();
634            return;
635        }
636        self.state = State::Ready;
637        self.events.push_back(Event::Ready);
638    }
639    /// Move the result's inherent envelope/ID ownership into the core. `content`
640    /// may be lettre's formatted MIME bytes or another already-built message.
641    /// For a message too large to hold twice in memory, use [`Self::start_send`].
642    pub fn send(
643        &mut self,
644        token: u64,
645        envelope: Envelope,
646        message_id: String,
647        content: &[u8],
648        now: Instant,
649    ) -> Result<(), Error> {
650        let eight_bit = !content.is_ascii();
651        self.check_send(&envelope, eight_bit)?;
652        self.body.clear();
653        let size = encode_data(content, &mut self.body);
654        self.begin(
655            token,
656            envelope,
657            message_id,
658            Some(size as u64),
659            eight_bit,
660            now,
661        )?;
662        self.streaming = None;
663        Ok(())
664    }
665    /// Starts a message whose content is streamed instead of passed whole.
666    /// MAIL/RCPT/DATA proceed as for [`Self::send`]; once the server accepts
667    /// DATA the core emits [`Event::BodyReady`], after which the host passes the
668    /// content in any number of [`Self::send_chunk`] calls and then calls
669    /// [`Self::finish_body`]. Line-ending normalization and dot-stuffing carry
670    /// across chunk boundaries, so any split yields the bytes `send` would.
671    /// The result is the same single `Sent`/`Failed` for `token`.
672    pub fn start_send(
673        &mut self,
674        token: u64,
675        envelope: Envelope,
676        message_id: String,
677        body: StreamBody,
678        now: Instant,
679    ) -> Result<(), Error> {
680        self.check_send(&envelope, body.eight_bit)?;
681        self.begin(token, envelope, message_id, body.size, body.eight_bit, now)?;
682        self.streaming = Some(body);
683        Ok(())
684    }
685    /// True between [`Event::BodyReady`] and [`Self::finish_body`].
686    pub fn can_send_body(&self) -> bool {
687        self.body_open && self.state == State::Body
688    }
689    /// Encodes one piece of a streamed message into `output()`. Drain `output()`
690    /// between chunks to keep memory bounded by the chunk size. 8-bit bytes in
691    /// a body not declared `eight_bit` cannot be retracted mid-DATA, so they
692    /// fail the transaction and close the transport.
693    pub fn send_chunk(&mut self, chunk: &[u8], now: Instant) -> Result<(), Error> {
694        self.check_body()?;
695        if !chunk.is_ascii() && !self.streaming.is_some_and(|b| b.eight_bit) {
696            let e = error(
697                "EMESSAGE",
698                "DATA",
699                "8-bit content in a body not declared eight_bit",
700                None,
701                "",
702            );
703            self.fail(e.clone());
704            self.close_transport();
705            return Err(e);
706        }
707        self.encoder.encode(chunk, &mut self.tx);
708        self.arm(now);
709        Ok(())
710    }
711    /// Ends a streamed message: terminates its last line if needed and writes
712    /// the `.` terminator. The server's reply settles the token.
713    pub fn finish_body(&mut self, now: Instant) -> Result<(), Error> {
714        self.check_body()?;
715        self.encoder.finish(&mut self.tx);
716        self.body_open = false;
717        self.arm(now);
718        Ok(())
719    }
720    fn check_body(&self) -> Result<(), Error> {
721        if self.can_send_body() {
722            Ok(())
723        } else {
724            Err(error(
725                "ESTATE",
726                "DATA",
727                "No streamed SMTP message body is open",
728                None,
729                "",
730            ))
731        }
732    }
733    fn check_send(&self, envelope: &Envelope, eight_bit: bool) -> Result<(), Error> {
734        if self.state != State::Ready {
735            return Err(error(
736                "ESTATE",
737                "MAIL FROM",
738                "SMTP connection is not ready",
739                None,
740                "",
741            ));
742        }
743        let valid_address = |s: &str| {
744            !s.bytes()
745                .any(|b| b <= b' ' || matches!(b, b'<' | b'>' | 127))
746        };
747        if !valid_address(&envelope.from)
748            || envelope.to.is_empty()
749            || envelope
750                .to
751                .iter()
752                .any(|s| s.is_empty() || !valid_address(s))
753        {
754            return Err(error(
755                "EENVELOPE",
756                "MAIL FROM",
757                "Invalid envelope",
758                None,
759                "",
760            ));
761        }
762        if utf8(envelope) && !self.capabilities.smtp_utf8 {
763            return Err(error(
764                "EENVELOPE",
765                "MAIL FROM",
766                "SMTPUTF8 is required but not supported",
767                None,
768                "",
769            ));
770        }
771        if eight_bit && !self.capabilities.eight_bit_mime {
772            return Err(error(
773                "EMESSAGE",
774                "MAIL FROM",
775                "8BITMIME is required but not supported",
776                None,
777                "",
778            ));
779        }
780        Ok(())
781    }
782    /// Emits MAIL FROM (and pipelined RCPT TO) once `check_send` has passed.
783    fn begin(
784        &mut self,
785        token: u64,
786        envelope: Envelope,
787        message_id: String,
788        size: Option<u64>,
789        eight_bit: bool,
790        now: Instant,
791    ) -> Result<(), Error> {
792        if size.is_some_and(|size| {
793            self.capabilities
794                .size
795                .is_some_and(|limit| limit != 0 && size > limit)
796        }) {
797            return Err(error(
798                "EMESSAGE",
799                "MAIL FROM",
800                "Message exceeds server SIZE limit",
801                None,
802                "",
803            ));
804        }
805        self.accepted.clear();
806        self.rejected.clear();
807        self.mail_error = None;
808        self.recipient_index = 0;
809        self.body_open = false;
810        write!(self.tx, "MAIL FROM:<{}>", envelope.from).unwrap();
811        if let Some(size) = size
812            && self.capabilities.size_supported
813        {
814            write!(self.tx, " SIZE={size}").unwrap();
815        }
816        if eight_bit {
817            self.tx.extend_from_slice(b" BODY=8BITMIME");
818        }
819        if utf8(&envelope) {
820            self.tx.extend_from_slice(b" SMTPUTF8");
821        }
822        self.tx.extend_from_slice(b"\r\n");
823        self.envelope = Some(envelope);
824        self.message_id = message_id;
825        self.token = Some(token);
826        if self.capabilities.pipelining {
827            for i in 0..self.envelope.as_ref().unwrap().to.len() {
828                self.rcpt(i);
829            }
830        }
831        self.state = State::Mail;
832        self.arm(now);
833        Ok(())
834    }
835    fn rcpt(&mut self, index: usize) {
836        write!(
837            self.tx,
838            "RCPT TO:<{}>\r\n",
839            self.envelope.as_ref().unwrap().to[index]
840        )
841        .unwrap();
842    }
843    fn unexpected(&mut self, code: u16, response: &str) {
844        let auth = matches!(
845            self.state,
846            State::Auth | State::LoginUser | State::LoginPassword | State::OAuthFailure
847        );
848        let tls = self.state == State::StartTls;
849        let body = self.state == State::Body;
850        let data = self.state == State::Data;
851        let e = error(
852            if body {
853                "EMESSAGE"
854            } else if auth {
855                "EAUTH"
856            } else if tls {
857                "ETLS"
858            } else {
859                "EENVELOPE"
860            },
861            self.command_name(),
862            if body {
863                "Message failed"
864            } else if data {
865                "Data command failed"
866            } else if auth {
867                "Invalid login"
868            } else if tls {
869                "Error upgrading connection with STARTTLS"
870            } else {
871                "Unexpected SMTP response"
872            },
873            Some(code),
874            response,
875        );
876        // RSET cannot follow a DATA body that was never terminated.
877        if matches!(self.state, State::Data | State::Body) && !self.body_open {
878            self.fail_and_reset(e);
879        } else {
880            self.fail(e);
881            self.close_transport();
882        }
883    }
884    fn fail_and_reset(&mut self, e: Error) {
885        self.fail(e);
886        self.tx.extend_from_slice(b"RSET\r\n");
887        self.state = State::Reset;
888        self.automatic_reset = true;
889    }
890    fn fail(&mut self, e: Error) {
891        self.events.push_back(Event::Failed {
892            token: self.token.take(),
893            error: e,
894            envelope: self.envelope.take(),
895            accepted: std::mem::take(&mut self.accepted),
896            rejected: std::mem::take(&mut self.rejected),
897        });
898    }
899    pub fn reset(&mut self, now: Instant) -> Result<(), Error> {
900        if self.state != State::Ready {
901            return Err(error(
902                "ESTATE",
903                "RSET",
904                "SMTP connection is not ready",
905                None,
906                "",
907            ));
908        }
909        self.tx.extend_from_slice(b"RSET\r\n");
910        self.state = State::Reset;
911        self.automatic_reset = false;
912        self.arm(now);
913        Ok(())
914    }
915    pub fn quit(&mut self, now: Instant) -> Result<(), Error> {
916        if self.state != State::Ready {
917            return Err(error(
918                "ESTATE",
919                "QUIT",
920                "SMTP connection is not ready",
921                None,
922                "",
923            ));
924        }
925        self.tx.extend_from_slice(b"QUIT\r\n");
926        self.state = State::Quit;
927        self.arm(now);
928        Ok(())
929    }
930    fn command_name(&self) -> &'static str {
931        match self.state {
932            State::Ehlo => "EHLO",
933            State::Helo => "HELO",
934            State::StartTls | State::Tls => "STARTTLS",
935            State::Auth | State::LoginUser | State::LoginPassword | State::OAuthFailure => {
936                match self.config.auth {
937                    Some(Auth::Plain { .. }) => "AUTH PLAIN",
938                    Some(Auth::Login { .. }) => "AUTH LOGIN",
939                    Some(Auth::Xoauth2 { .. }) => "AUTH XOAUTH2",
940                    None => "AUTH",
941                }
942            }
943            State::Mail => "MAIL FROM",
944            State::Recipients => "RCPT TO",
945            State::Data | State::Body => "DATA",
946            State::Reset => "RSET",
947            State::Quit => "QUIT",
948            _ => "CONN",
949        }
950    }
951    pub fn next_timeout(&self) -> Option<Instant> {
952        self.deadline
953    }
954    pub fn handle_timeout(&mut self, now: Instant) {
955        if self.deadline.is_some_and(|d| d <= now) {
956            self.fail(error(
957                "ETIMEDOUT",
958                self.command_name(),
959                if self.state == State::Greeting {
960                    "Greeting never received"
961                } else {
962                    "Timeout"
963                },
964                None,
965                "",
966            ));
967            self.close_transport();
968        }
969    }
970    pub fn transport_lost(&mut self) {
971        if self.state != State::Closed {
972            self.fail(error(
973                "ECONNECTION",
974                self.command_name(),
975                "Connection closed unexpectedly",
976                None,
977                "",
978            ));
979            self.close_transport();
980        }
981    }
982    pub fn close(&mut self) {
983        if self.token.is_some() {
984            self.fail(error(
985                "ECANCELLED",
986                self.command_name(),
987                "Cancelled",
988                None,
989                "",
990            ));
991        }
992        self.close_transport();
993    }
994    fn close_transport(&mut self) {
995        if self.state == State::Closed {
996            return;
997        }
998        self.state = State::Closed;
999        self.body_open = false;
1000        self.deadline = None;
1001        self.tx.clear();
1002        self.tx_pos = 0;
1003        self.events.push_back(Event::CloseTransport);
1004        self.events.push_back(Event::Closed);
1005    }
1006}
1007fn utf8(envelope: &Envelope) -> bool {
1008    !envelope.from.is_ascii() || envelope.to.iter().any(|s| !s.is_ascii())
1009}
1010/// How a streamed message body will be sent; see [`Connection::start_send`].
1011#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1012pub struct StreamBody {
1013    /// Expected normalized content octets, sent as the SIZE parameter when the
1014    /// server supports it and checked against the server's advertised limit.
1015    /// `None` omits the parameter. The server, not this core, enforces it.
1016    pub size: Option<u64>,
1017    /// The body may contain 8-bit bytes: sends BODY=8BITMIME, which the server
1018    /// must support. Without it, a non-ASCII chunk fails the transaction.
1019    pub eight_bit: bool,
1020}
1021/// Incremental SMTP DATA encoding: normalizes LF, CRLF and bare CR to CRLF and
1022/// dot-stuffs each line. State carries across [`DataEncoder::encode`] calls, so
1023/// a CR/LF pair or a line-leading `.` split between chunks encodes exactly as
1024/// it would in one piece.
1025#[derive(Debug, Clone)]
1026pub struct DataEncoder {
1027    at_line_start: bool,
1028    after_cr: bool,
1029    size: usize,
1030}
1031impl Default for DataEncoder {
1032    fn default() -> Self {
1033        Self::new()
1034    }
1035}
1036impl DataEncoder {
1037    pub fn new() -> Self {
1038        Self {
1039            at_line_start: true,
1040            after_cr: false,
1041            size: 0,
1042        }
1043    }
1044    pub fn encode(&mut self, content: &[u8], out: &mut Vec<u8>) {
1045        for &byte in content {
1046            match byte {
1047                // The LF of a CRLF whose CR already produced the line break.
1048                b'\n' if self.after_cr => self.after_cr = false,
1049                b'\r' | b'\n' => {
1050                    out.extend_from_slice(b"\r\n");
1051                    self.size += 2;
1052                    self.at_line_start = true;
1053                    self.after_cr = byte == b'\r';
1054                }
1055                byte => {
1056                    if self.at_line_start && byte == b'.' {
1057                        out.push(b'.');
1058                    }
1059                    out.push(byte);
1060                    self.size += 1;
1061                    self.at_line_start = false;
1062                    self.after_cr = false;
1063                }
1064            }
1065        }
1066    }
1067    /// Terminates an unfinished last line and appends the DATA terminator.
1068    /// Returns SIZE octets (normalized content, excluding transparency dots)
1069    /// and resets the encoder for the next message.
1070    pub fn finish(&mut self, out: &mut Vec<u8>) -> usize {
1071        if !self.at_line_start {
1072            out.extend_from_slice(b"\r\n");
1073            self.size += 2;
1074        }
1075        out.extend_from_slice(b".\r\n");
1076        let size = self.size;
1077        *self = Self::new();
1078        size
1079    }
1080}
1081/// Normalize LF, CRLF and bare CR, dot-stuff each line, append the SMTP DATA
1082/// terminator. Returns SIZE octets (normalized content, excluding transparency).
1083pub fn encode_data(content: &[u8], out: &mut Vec<u8>) -> usize {
1084    let mut encoder = DataEncoder::new();
1085    encoder.encode(content, out);
1086    encoder.finish(out)
1087}
1088
1089#[cfg(feature = "turnloop")]
1090pub mod asynchronous;
1091
1092#[cfg(test)]
1093mod tests {
1094    use super::*;
1095    /// Reaching the Ready transition in the clear, by any path, must fail the
1096    /// session under a mandatory TLS policy rather than report `Ready`.
1097    #[test]
1098    fn ready_refuses_plaintext_under_mandatory_tls() {
1099        let now = Instant::now();
1100        for (tls, allowed) in [
1101            (Tls::Required, false),
1102            (Tls::Implicit, false),
1103            (Tls::Opportunistic, true),
1104            (Tls::None, true),
1105        ] {
1106            let mut c = Connection::new(Config {
1107                tls,
1108                ..Config::default()
1109            })
1110            .expect("config");
1111            c.connected(now).expect("connected");
1112            c.state = State::Ehlo;
1113            // Skip after_ehlo's STARTTLS decision, as a future path might.
1114            c.authenticate();
1115            let events: Vec<_> = std::iter::from_fn(|| c.poll_event()).collect();
1116            let events: Vec<_> = events
1117                .into_iter()
1118                .filter(|e| *e != Event::UpgradeTls)
1119                .collect();
1120            if allowed {
1121                assert_eq!(events, [Event::Ready], "{tls:?}");
1122                assert_eq!(c.state(), State::Ready);
1123            } else {
1124                assert_eq!(events.len(), 3, "{tls:?}: {events:?}");
1125                assert!(
1126                    matches!(&events[0], Event::Failed { token: None, error, .. }
1127                        if error.code == "ETLS" && error.message.contains("never encrypted")),
1128                    "{tls:?}: {events:?}"
1129                );
1130                assert_eq!(events[1..], [Event::CloseTransport, Event::Closed]);
1131                assert_eq!(c.state(), State::Closed);
1132            }
1133        }
1134    }
1135}