Skip to main content

io_smtp/rfc5321/
raw.rs

1//! SMTP raw passthrough coroutine; sends an arbitrary command line
2//! and returns the server reply verbatim.
3//!
4//! Reserved for simple request/reply commands (`NOOP`, `VRFY`, `HELP`,
5//! `RSET`, ...); do not use for `DATA` or `STARTTLS`, which switch the
6//! stream into a different mode.
7//!
8//! # Example
9//!
10//! ```rust,no_run
11//! use std::{
12//!     io::{Read, Write},
13//!     net::TcpStream,
14//! };
15//!
16//! use io_smtp::{
17//!     coroutine::{SmtpCoroutine, SmtpCoroutineState, SmtpYield},
18//!     rfc5321::raw::SmtpRaw,
19//! };
20//!
21//! // Ready stream needed (TCP-connected, TLS-negociated, SMTP-handshaked)
22//! let mut stream = TcpStream::connect("localhost:25").unwrap();
23//!
24//! let mut buf = [0u8; 4096];
25//!
26//! let mut coroutine = SmtpRaw::new("VRFY postmaster");
27//! let mut arg = None;
28//!
29//! loop {
30//!     match coroutine.resume(arg.take()) {
31//!         SmtpCoroutineState::Yielded(SmtpYield::WantsWrite(bytes)) => {
32//!             stream.write_all(&bytes).unwrap();
33//!         }
34//!         SmtpCoroutineState::Yielded(SmtpYield::WantsRead) => {
35//!             let n = stream.read(&mut buf).unwrap();
36//!             arg = Some(&buf[..n]);
37//!         }
38//!         SmtpCoroutineState::Complete(Ok(reply)) => {
39//!             print!("{reply}");
40//!             break;
41//!         }
42//!         SmtpCoroutineState::Complete(Err(err)) => panic!("{err}"),
43//!     }
44//! }
45//! ```
46
47use core::fmt::{self, Write};
48
49use alloc::{borrow::Cow, string::String, vec::Vec};
50
51use log::{debug, trace};
52use thiserror::Error;
53
54use crate::{coroutine::*, send::*, smtp_try};
55
56/// An arbitrary raw SMTP command line, without the trailing CRLF.
57pub struct SmtpRawCommand<'a> {
58    /// The command line to send; CRLF is appended on serialisation.
59    pub line: Cow<'a, str>,
60}
61
62impl<'a> From<SmtpRawCommand<'a>> for Vec<u8> {
63    fn from(cmd: SmtpRawCommand<'a>) -> Vec<u8> {
64        let mut buf = cmd.line.into_owned();
65        buf.push_str("\r\n");
66        buf.into_bytes()
67    }
68}
69
70/// Failure causes during the SMTP raw exchange.
71#[derive(Clone, Debug, Error)]
72pub enum SmtpRawError {
73    /// The underlying command exchange failed.
74    #[error("SMTP raw command failed: {0}")]
75    Send(#[from] SmtpCommandSendError),
76}
77
78/// I/O-free SMTP raw passthrough coroutine.
79pub struct SmtpRaw {
80    state: State,
81}
82
83impl SmtpRaw {
84    /// `command` is a single SMTP command line without the trailing
85    /// CRLF (e.g. `NOOP`, `VRFY foo@bar`, `HELP`).
86    pub fn new(command: impl Into<Cow<'static, str>>) -> Self {
87        Self {
88            state: State::Send(SmtpCommandSend::new(SmtpRawCommand {
89                line: command.into(),
90            })),
91        }
92    }
93}
94
95impl SmtpCoroutine for SmtpRaw {
96    type Yield = SmtpYield;
97    type Return = Result<String, SmtpRawError>;
98
99    fn resume(&mut self, arg: Option<&[u8]>) -> SmtpCoroutineState<Self::Yield, Self::Return> {
100        match &mut self.state {
101            State::Send(send) => {
102                let out = smtp_try!(send, arg);
103
104                // NOTE: reconstruct the full reply text from the
105                // parsed response: every line carries the same
106                // 3-digit code, continuation lines use `-`, the final
107                // line a space. Any reply code is a valid answer
108                // here, including 4xx and 5xx; only transport/parse
109                // failures are errors.
110                let response = out.response;
111                let lines = response.lines.as_ref();
112                let last = lines.len() - 1;
113
114                let mut reply = String::new();
115                for (i, line) in lines.iter().enumerate() {
116                    let sep = if i == last { ' ' } else { '-' };
117                    let _ = write!(reply, "{}{sep}{line}\r\n", response.code);
118                }
119
120                debug!("raw reply received");
121                trace!("{reply:?}");
122                SmtpCoroutineState::Complete(Ok(reply))
123            }
124        }
125    }
126}
127
128enum State {
129    Send(SmtpCommandSend<SmtpRawCommand<'static>>),
130}
131
132impl fmt::Display for State {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        match self {
135            Self::Send(_) => f.write_str("send raw command"),
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use alloc::{string::String, vec::Vec};
143
144    use crate::{coroutine::*, rfc5321::raw::*, send::SmtpCommandSendError};
145
146    #[test]
147    fn success_returns_reply() {
148        let mut raw = SmtpRaw::new("NOOP");
149
150        let bytes = expect_wants_write(&mut raw, None);
151        assert_eq!(bytes, b"NOOP\r\n");
152
153        expect_wants_read(&mut raw);
154        let reply = expect_complete_ok(&mut raw, b"250 OK\r\n");
155        assert_eq!(reply, "250 OK\r\n");
156    }
157
158    #[test]
159    fn multiline_reply_is_returned_verbatim() {
160        let mut raw = SmtpRaw::new("EHLO host");
161        let _ = expect_wants_write(&mut raw, None);
162        expect_wants_read(&mut raw);
163
164        let reply = expect_complete_ok(&mut raw, b"250-host greets you\r\n250 HELP\r\n");
165        assert_eq!(reply, "250-host greets you\r\n250 HELP\r\n");
166    }
167
168    #[test]
169    fn error_reply_is_returned_not_failed() {
170        let mut raw = SmtpRaw::new("FOOBAR");
171        let _ = expect_wants_write(&mut raw, None);
172        expect_wants_read(&mut raw);
173
174        let reply = expect_complete_ok(&mut raw, b"500 command unrecognized\r\n");
175        assert_eq!(reply, "500 command unrecognized\r\n");
176    }
177
178    #[test]
179    fn eof_returns_eof_error() {
180        let mut raw = SmtpRaw::new("NOOP");
181        let _ = expect_wants_write(&mut raw, None);
182        expect_wants_read(&mut raw);
183
184        let err = expect_complete_err(&mut raw, b"");
185        assert!(matches!(err, SmtpRawError::Send(SmtpCommandSendError::Eof)));
186    }
187
188    fn expect_wants_write(cor: &mut SmtpRaw, arg: Option<&[u8]>) -> Vec<u8> {
189        match cor.resume(arg) {
190            SmtpCoroutineState::Yielded(SmtpYield::WantsWrite(bytes)) => bytes,
191            state => panic!("expected WantsWrite, got {state:?}"),
192        }
193    }
194
195    fn expect_wants_read(cor: &mut SmtpRaw) {
196        match cor.resume(None) {
197            SmtpCoroutineState::Yielded(SmtpYield::WantsRead) => {}
198            state => panic!("expected WantsRead, got {state:?}"),
199        }
200    }
201
202    fn expect_complete_ok(cor: &mut SmtpRaw, reply: &[u8]) -> String {
203        match cor.resume(Some(reply)) {
204            SmtpCoroutineState::Complete(Ok(out)) => out,
205            state => panic!("expected Complete(Ok), got {state:?}"),
206        }
207    }
208
209    fn expect_complete_err(cor: &mut SmtpRaw, reply: &[u8]) -> SmtpRawError {
210        match cor.resume(Some(reply)) {
211            SmtpCoroutineState::Complete(Err(err)) => err,
212            state => panic!("expected Complete(Err), got {state:?}"),
213        }
214    }
215}