rsmtp 0.1.3

Utility functions for SMTP applications, no backwards compatibility guarantees.
Documentation
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// Copyright 2014 The Rustastic SMTP Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Tools for reading/writing from SMTP clients to SMTP servers and vice-versa.

#[cfg(test)]
use super::MIN_ALLOWED_LINE_SIZE;
#[cfg(test)]
use std::error::Error;
#[cfg(test)]
use std::fs::File;
#[cfg(test)]
use std::fs::OpenOptions;
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::io::{ErrorKind, Read, Write};
#[cfg(test)]
use std::iter::{repeat, FromIterator};
use std::ops::{IndexMut, RangeFrom};
use std::vec::Vec;

pub static LINE_TOO_LONG: &str = "line too long";

pub static DATA_TOO_LONG: &str = "message too long";

#[test]
fn test_static_vars() {
    // Already tested in the limits test further down.
}

/// A stream that reads lines of input.
///
/// # Example
/// ```no_run
/// use std::net::TcpStream;
/// use rsmtp::common::stream::InputStream;
/// use rsmtp::common::{
///     MIN_ALLOWED_LINE_SIZE,
/// };
///
/// let mut smtp = InputStream::new(
///     TcpStream::connect("127.0.0.1:25").unwrap(),
///     MIN_ALLOWED_LINE_SIZE,
///     false
/// );
///
/// println!("{:?}", smtp.read_line().unwrap());
/// ```
pub struct InputStream<S> {
    /// Underlying stream
    stream: S,
    /// Must be at least 1001 per RFC 5321, 1000 chars + 1 for transparency
    /// mechanism.
    max_line_size: usize,
    /// Buffer to make reading more efficient and allow pipelining
    buf: Vec<u8>,
    /// If `true`, will print debug messages of input and output to the console.
    debug: bool,
    /// The position of the `<CRLF>` found at the previous `read_line`.
    last_crlf: Option<usize>,
}

// The state of the `<CRLF>` search inside a buffer. See below.
enum CRLFState {
    // We are looking for `<CR>`.
    Cr,
    // We are looking for `<LF>`.
    Lf,
}

// Find the position of the first `<CRLF>` in a buffer.
fn position_crlf(buf: &[u8]) -> Option<usize> {
    let mut state = CRLFState::Cr;
    let mut index = 0;

    for byte in buf.iter() {
        match state {
            CRLFState::Cr => {
                if byte == &13 {
                    state = CRLFState::Lf;
                }
            }
            CRLFState::Lf => {
                if byte == &10 {
                    // Subtract 1 to account for the \r, seen previously.
                    return Some(index - 1);
                }
            }
        }
        index += 1;
    }

    None
}

impl<S: Read> InputStream<S> {
    /// Create a new `InputStream` from another stream.
    pub fn new(inner: S, max_line_size: usize, debug: bool) -> InputStream<S> {
        InputStream {
            stream: inner,
            max_line_size: max_line_size,
            // TODO: make line reading work even with a buffer smaller than the maximum line size.
            // Currently, this will not work because we only fill the buffer once per line, assuming
            // that the buffer is large enough.
            buf: Vec::with_capacity(max_line_size),
            debug: debug,
            last_crlf: None,
        }
    }

    /// Remove the previous line from the buffer when reading a new line.
    pub fn move_buf(&mut self) {
        // Remove the last line, since we've used it already by now.
        match self.last_crlf {
            Some(p) => {
                // TODO: This could probably be optimised by shifting bytes instead
                // of re-allocating.
                self.buf = self.buf[p + 2..].to_vec();
                self.buf.reserve(self.max_line_size);
            }
            _ => {}
        }

        self.last_crlf = None;
    }

    /// Fill the buffer to its limit.
    fn fill_buf(&mut self) -> IoResult<usize> {
        let len = self.buf.len();
        let cap = self.buf.capacity();

        // Leave as much space open at the end of the buffer so we can fill it using
        // a &mut reference. We'll set the right length again later.
        unsafe { self.buf.set_len(cap) };

        // Read as much data as the buffer can hold without re-allocation.
        match self
            .stream
            .read(self.buf.index_mut(RangeFrom { start: len }))
        {
            Ok(num_bytes) => {
                // Set the new known length for the buffer.
                unsafe { self.buf.set_len(len + num_bytes) };
                Ok(num_bytes)
            }
            Err(err) => {
                // Restore the previous length so we don't accidentally use outdated bytes.
                unsafe { self.buf.set_len(len) };
                Err(err)
            }
        }
    }

    /// Read an SMTP command. Ends with `<CRLF>`.
    pub fn read_line(&mut self) -> IoResult<&[u8]> {
        // Remove the previous line from the buffer before reading a new one.
        self.move_buf();

        let read_line = match position_crlf(self.buf.as_ref()) {
            // First, let's check if the buffer already contains a line. This
            // reduces the number of syscalls.
            Some(last_crlf) => {
                self.last_crlf = Some(last_crlf);
                Ok(&self.buf[..last_crlf])
            }
            // If we don't have a line in the buffer, we'll read more input
            // and try again.
            None => {
                match self.fill_buf() {
                    Ok(_) => {
                        match position_crlf(self.buf.as_ref()) {
                            Some(last_crlf) => {
                                self.last_crlf = Some(last_crlf);
                                Ok(&self.buf[..last_crlf])
                            }
                            None => {
                                // If we didn't find a line, it means we had
                                // no `<CRLF>` in the buffer, which means that
                                // the line is too long.
                                Err(IoError::new(ErrorKind::InvalidInput, LINE_TOO_LONG))
                            }
                        }
                    }
                    Err(err) => Err(err),
                }
            }
        };

        // If we read a line, we'll say so in the console, if debug mode is on.
        if let Ok(bytes) = read_line {
            if self.debug {
                println!("rsmtp: imsg: {}", String::from_utf8_lossy(bytes.as_ref()));
            }
        }

        read_line
    }
}

/// A stream that writes lines of output.
pub struct OutputStream<S> {
    /// Underlying stream
    stream: S,
    /// If `true`, will print debug messages of input and output to the console.
    debug: bool,
}

impl<S: Write> OutputStream<S> {
    /// Create a new `InputStream` from another stream.
    pub fn new(inner: S, debug: bool) -> OutputStream<S> {
        OutputStream {
            stream: inner,
            debug: debug,
        }
    }

    /// Write a line ended with `<CRLF>`.
    pub fn write_line(&mut self, s: &str) -> IoResult<()> {
        if self.debug {
            println!("rsmtp: omsg: {}", s);
        }
        // We use `format!()` instead of 2 calls to `write_str()` to reduce
        // the amount of syscalls and to send the string as a single packet.
        // I'm not sure if this is the right way to go though. If you think
        // this is wrong, please open a issue on Github.
        write!(&mut self.stream, "{}\r\n", s)
    }
}

#[test]
fn test_new() {
    // This method is already tested via `test_read_line()`.
}

#[test]
fn test_write_line() {
    // Use a block so the file gets closed at the end of it.
    {
        let file_write: File;
        let mut stream: OutputStream<File>;

        file_write = OpenOptions::new()
            .truncate(true)
            .write(true)
            .open("tests/stream/write_line")
            .unwrap();
        stream = OutputStream::new(file_write, false);
        stream.write_line("HelloWorld").unwrap();
        stream.write_line("ByeBye").unwrap();
    }
    let mut file_read: File;
    let mut expected = String::new();

    file_read = OpenOptions::new()
        .read(true)
        .open("tests/stream/write_line")
        .unwrap();
    file_read.read_to_string(&mut expected).unwrap();
    assert_eq!("HelloWorld\r\nByeBye\r\n", expected.as_str());
}

#[test]
fn test_limits() {
    let file: File;
    let mut stream: InputStream<File>;

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/1line1")
        .unwrap();
    stream = InputStream::new(file, 3, false);
    match stream.read_line() {
        Ok(_) => panic!(),
        Err(err) => {
            assert_eq!("line too long", err.to_string());
            assert_eq!(ErrorKind::InvalidInput, err.kind());
        }
    }
}

#[test]
fn test_read_line() {
    let mut file: File;
    let mut stream: InputStream<File>;
    let expected: String;

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/0line1")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert!(!stream.read_line().is_ok());

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/0line2")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert!(!stream.read_line().is_ok());

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/0line3")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert!(!stream.read_line().is_ok());

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/1line1")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref())
            .to_owned()
            .as_ref(),
        "hello world!"
    );
    assert!(!stream.read_line().is_ok());

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/1line2")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref())
            .to_owned()
            .as_ref(),
        "hello world!"
    );
    assert!(!stream.read_line().is_ok());

    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/2lines1")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref())
            .to_owned()
            .as_ref(),
        "hello world!"
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref())
            .to_owned()
            .as_ref(),
        "bye bye world!"
    );
    assert!(!stream.read_line().is_ok());

    expected = String::from_iter(repeat('x').take(62));
    file = OpenOptions::new()
        .read(true)
        .open("tests/stream/xlines1")
        .unwrap();
    stream = InputStream::new(file, MIN_ALLOWED_LINE_SIZE, false);
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert_eq!(
        String::from_utf8_lossy(stream.read_line().unwrap().as_ref()).to_owned(),
        expected
    );
    assert!(!stream.read_line().is_ok());
}