1use 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
56pub struct SmtpRawCommand<'a> {
58 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#[derive(Clone, Debug, Error)]
72pub enum SmtpRawError {
73 #[error("SMTP raw command failed: {0}")]
75 Send(#[from] SmtpCommandSendError),
76}
77
78pub struct SmtpRaw {
80 state: State,
81}
82
83impl SmtpRaw {
84 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 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}