1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::fmt::{Debug, Display};
use std::string::String;
use std::time::Duration;
use async_std::io::{self, BufReader, Read, Write};
use async_std::net::ToSocketAddrs;
use async_std::pin::Pin;
use async_std::prelude::*;
use log::debug;
use pin_project::pin_project;
use crate::smtp::authentication::{Credentials, Mechanism};
use crate::smtp::client::net::{ClientTlsParameters, Connector, NetworkStream};
use crate::smtp::client::ClientCodec;
use crate::smtp::commands::*;
use crate::smtp::error::{Error, SmtpResult};
use crate::smtp::response::parse_response;
fn escape_crlf(string: &str) -> String {
string.replace("\r\n", "<CRLF>")
}
#[pin_project]
#[derive(Debug)]
pub struct InnerClient<S: Write + Read = NetworkStream> {
#[pin]
pub(crate) stream: Option<S>,
timeout: Option<Duration>,
}
impl<S: Write + Read> Default for InnerClient<S> {
fn default() -> Self {
InnerClient {
stream: None,
timeout: None,
}
}
}
macro_rules! return_err (
($err: expr, $client: ident) => ({
return Err(From::from($err))
})
);
impl<S: Write + Read> InnerClient<S> {
pub fn new() -> InnerClient<S> {
InnerClient::default()
}
}
impl<S: Connector + Write + Read + Unpin> InnerClient<S> {
pub async fn close(mut self: Pin<&mut Self>) -> Result<(), Error> {
self.as_mut().command(QuitCommand).await?;
self.get_mut().stream = None;
Ok(())
}
pub fn set_stream(&mut self, stream: S) {
self.stream = Some(stream);
}
pub async fn upgrade_tls_stream(
self,
tls_parameters: &ClientTlsParameters,
) -> io::Result<Self> {
match self.stream {
Some(stream) => Ok(InnerClient {
stream: Some(stream.upgrade_tls(tls_parameters).await?),
timeout: self.timeout,
}),
None => Ok(self),
}
}
pub fn is_encrypted(&self) -> bool {
self.stream
.as_ref()
.map(|s| s.is_encrypted())
.unwrap_or(false)
}
pub fn set_timeout(&mut self, duration: Option<Duration>) {
self.timeout = duration;
}
pub fn timeout(&mut self) -> Option<&Duration> {
self.timeout.as_ref()
}
pub async fn connect<A: ToSocketAddrs>(
&mut self,
addr: &A,
timeout: Option<Duration>,
tls_parameters: Option<&ClientTlsParameters>,
) -> Result<(), Error> {
let mut addresses = addr.to_socket_addrs().await?;
let server_addr = match addresses.next() {
Some(addr) => addr,
None => return_err!("Could not resolve hostname", self),
};
self.connect_with_stream(Connector::connect(&server_addr, timeout, tls_parameters).await?).await
}
pub async fn connect_with_stream(
&mut self,
stream: S
) -> Result<(), Error> {
if self.stream.is_some() {
return_err!("The connection is already established", self);
}
self.set_stream(stream);
Ok(())
}
pub fn is_connected(&self) -> bool {
self.stream.is_some()
}
pub async fn auth(
mut self: Pin<&mut Self>,
mechanism: Mechanism,
credentials: &Credentials,
) -> SmtpResult {
let mut challenges = 10;
let mut response = self
.as_mut()
.command(AuthCommand::new(mechanism, credentials.clone(), None)?)
.await?;
while challenges > 0 && response.has_code(334) {
challenges -= 1;
response = self
.as_mut()
.command(AuthCommand::new_from_response(
mechanism,
credentials.clone(),
&response,
)?)
.await?;
}
if challenges == 0 {
Err(Error::ResponseParsing("Unexpected number of challenges"))
} else {
Ok(response)
}
}
pub async fn message<T: Read + Unpin>(mut self: Pin<&mut Self>, message: T) -> SmtpResult {
let mut codec = ClientCodec::new();
let mut message_reader = BufReader::new(message);
let mut message_bytes = Vec::new();
message_reader.read_to_end(&mut message_bytes).await?;
if self.stream.is_none() {
return Err(From::from("Connection closed"));
}
let this = self.as_mut().project();
let _: Pin<&mut Option<S>> = this.stream;
let mut stream = this.stream.as_pin_mut().ok_or(Error::NoStream)?;
with_timeout(this.timeout.as_ref(), async move {
codec.encode(&message_bytes, &mut stream).await?;
stream.write_all(b"\r\n.\r\n").await?;
Ok(())
})
.await?;
self.read_response().await
}
pub async fn command<C: Display>(mut self: Pin<&mut Self>, command: C) -> SmtpResult {
self.as_mut().write(command.to_string().as_bytes()).await?;
self.read_response().await
}
async fn write(mut self: Pin<&mut Self>, string: &[u8]) -> Result<(), Error> {
if self.stream.is_none() {
return Err(From::from("Connection closed"));
}
let this = self.as_mut().project();
let _: Pin<&mut Option<S>> = this.stream;
let mut stream = this.stream.as_pin_mut().ok_or(Error::NoStream)?;
with_timeout(this.timeout.as_ref(), async move {
stream.write_all(string).await?;
stream.flush().await?;
Ok(())
})
.await?;
debug!(
">> {}",
escape_crlf(String::from_utf8_lossy(string).as_ref())
);
Ok(())
}
pub async fn read_response(mut self: Pin<&mut Self>) -> SmtpResult {
let this = self.as_mut().project();
let stream = this.stream.as_pin_mut().ok_or(Error::NoStream)?;
let mut reader = BufReader::new(stream);
let mut buffer = String::with_capacity(100);
loop {
let read = with_timeout(this.timeout.as_ref(), reader.read_line(&mut buffer)).await?;
if read == 0 {
break;
}
debug!("<< {}", escape_crlf(&buffer));
match parse_response(&buffer) {
Ok((_remaining, response)) => {
if response.is_positive() {
return Ok(response);
}
return Err(response.into());
}
Err(nom::Err::Failure(e)) => {
return Err(Error::Parsing(e.1));
}
Err(nom::Err::Incomplete(_)) => { }
Err(nom::Err::Error(e)) => {
return Err(Error::Parsing(e.1));
}
}
}
Err(io::Error::new(io::ErrorKind::Other, "incomplete").into())
}
}
async fn with_timeout<T, F>(timeout: Option<&Duration>, f: F) -> Result<T, Error>
where
F: Future<Output = async_std::io::Result<T>>,
{
let r = if let Some(timeout) = timeout {
async_std::io::timeout(*timeout, f).await?
} else {
f.await?
};
Ok(r)
}
#[cfg(test)]
mod test {
use super::escape_crlf;
use crate::smtp::client::ClientCodec;
#[async_attributes::test]
async fn test_codec() {
let mut codec = ClientCodec::new();
let mut buf: Vec<u8> = vec![];
assert!(codec.encode(b"test\r\n", &mut buf).await.is_ok());
assert!(codec.encode(b".\r\n", &mut buf).await.is_ok());
assert!(codec.encode(b"\r\ntest", &mut buf).await.is_ok());
assert!(codec.encode(b"te\r\n.\r\nst", &mut buf).await.is_ok());
assert!(codec.encode(b"test", &mut buf).await.is_ok());
assert!(codec.encode(b"test.", &mut buf).await.is_ok());
assert!(codec.encode(b"test\n", &mut buf).await.is_ok());
assert!(codec.encode(b".test\n", &mut buf).await.is_ok());
assert!(codec.encode(b"test", &mut buf).await.is_ok());
assert_eq!(
String::from_utf8(buf).unwrap(),
"test\r\n..\r\n\r\ntestte\r\n..\r\nsttesttest.test\n.test\ntest"
);
}
#[test]
fn test_escape_crlf() {
assert_eq!(escape_crlf("\r\n"), "<CRLF>");
assert_eq!(escape_crlf("EHLO my_name\r\n"), "EHLO my_name<CRLF>");
assert_eq!(
escape_crlf("EHLO my_name\r\nSIZE 42\r\n"),
"EHLO my_name<CRLF>SIZE 42<CRLF>"
);
}
}