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
use crate::common::*;
use crate::model::io::ReadControl;
use crate::service::parser::Parser;

pub trait IntoParse
where
    Self: Sized,
{
    fn parse<P>(self, parser: P) -> Parse<Self, P> {
        Parse::new(self, parser)
    }
}

impl<S> IntoParse for S where S: Stream<Item = Result<ReadControl>> {}

#[pin_project(project=ParseProjection)]
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Parse<S, P> {
    #[pin]
    stream: S,
    parser: P,
    input: Vec<Option<Result<ReadControl>>>,
}

impl<S, P> Parse<S, P> {
    pub fn new(stream: S, parser: P) -> Self {
        Self {
            stream,
            parser,
            input: vec![],
        }
    }
}

impl<S, P> Stream for Parse<S, P>
where
    S: Stream<Item = Result<ReadControl>>,
    P: Parser,
{
    type Item = S::Item;
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let ParseProjection {
            mut stream,
            parser,
            input,
        } = self.project();
        loop {
            let tail = match input.first() {
                Some(Some(Ok(ReadControl::Raw(ref bytes)))) if !bytes.ends_with(b"\n") => {
                    // this is a line without LF, we'll concat with the next
                    if let Some(Ok(ReadControl::Raw(bytes))) = input.remove(0) {
                        Some(bytes)
                    } else {
                        unreachable!("checked in previous match")
                    }
                }
                _ => {
                    // it is not an open ended raw line, leave it put
                    None
                }
            };

            if !input.is_empty() {
                assert!(
                    tail.is_none(),
                    "In previous code block, tail is some only if it is the last element"
                );
                // return previously parsed items
                return Poll::Ready(input.remove(0));
            }

            match ready!(stream.as_mut().poll_next(cx)) {
                Some(Ok(ReadControl::Raw(mut bytes))) => {
                    if let Some(tail) = tail {
                        let mut bytes2 = tail.to_vec();
                        bytes2.extend_from_slice(&bytes[..]);
                        // concat previous open ended line with new raw
                        bytes = bytes2;
                    }

                    trace!("Parsing {} raw bytes as a script", bytes.len());
                    match parser.script(&bytes[..]) {
                        Ok(script) => {
                            trace!("Parsed a script of {} inputs", script.len());
                            input.extend(script.into_iter().map(|i| Some(Ok(i))))
                        }
                        _ => {
                            warn!("Parsing the script failed, passing as is.");
                            input.push(Some(Ok(ReadControl::Raw(bytes))));
                        }
                    }
                }
                other => {
                    if let Some(bytes) = tail {
                        trace!("Passing server control {:?} after the tail", other);
                        input.insert(0, other);
                        return Poll::Ready(Some(Ok(ReadControl::Raw(bytes))));
                    } else {
                        trace!("Passing server control {:?}", other);
                        return Poll::Ready(other);
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod parse_tests {
    use crate::model::io::ReadControl::*;
    use crate::model::smtp::SmtpCommand::{self, *};
    use crate::service::parser::Parser;
    use crate::test_util::*;

    use super::*;

    struct FakeParser<T>(T);
    impl Parser for FakeParser<SmtpCommand> {
        fn command(&self, _input: &[u8]) -> Result<SmtpCommand> {
            Ok(self.0.clone())
        }
        fn script(&self, input: &[u8]) -> Result<Vec<ReadControl>> {
            Ok(vec![ReadControl::Command(self.0.clone(), Vec::from(input))])
        }
    }
    impl Parser for FakeParser<ReadControl> {
        fn command(&self, _input: &[u8]) -> Result<SmtpCommand> {
            if let ReadControl::Command(c, _) = self.0.clone() {
                Ok(c)
            } else {
                Err("wrong".into())
            }
        }
        fn script(&self, _input: &[u8]) -> Result<Vec<ReadControl>> {
            Ok(vec![self.0.clone()])
        }
    }
    impl Parser for FakeParser<Vec<ReadControl>> {
        fn command(&self, _input: &[u8]) -> Result<SmtpCommand> {
            Err("wrong".into())
        }
        fn script(&self, _input: &[u8]) -> Result<Vec<ReadControl>> {
            Ok(self.0.clone())
        }
    }
    impl Parser for FakeParser<()> {
        fn command(&self, _input: &[u8]) -> Result<SmtpCommand> {
            Err("fail".into())
        }
        fn script(&self, _input: &[u8]) -> Result<Vec<ReadControl>> {
            Err("fail".into())
        }
    }

    #[test]
    fn poll_next_handles_partial_input_with_pending() -> Result<()> {
        let setup = TestStream::from(vec![Poll::Ready(Some(Ok(Raw(b("uhu"))))), Poll::Pending]);
        let mut sut = setup.parse(FakeParser(()));
        let res = Pin::new(&mut sut).poll_next(&mut cx());

        assert_eq!(res?, Poll::Pending);
        Ok(())
    }

    #[test]
    fn poll_next_handles_partial_input_with_concatenation() -> Result<()> {
        let setup = TestStream::from(vec![
            Poll::Ready(Some(Ok(Raw(b("qu"))))),
            Poll::Ready(Some(Ok(Raw(b("it"))))),
            Poll::Ready(Some(Ok(Raw(b("\r\n"))))),
        ]);
        let mut sut = setup.parse(FakeParser(Quit));
        let res = Pin::new(&mut sut).poll_next(&mut cx());
        //todo: test concatenation
        //assert_eq!(res?, Poll::Ready(Some(Command(Quit, b("quit\r\n")))));
        Ok(())
    }

    #[test]
    fn poll_next_handles_pipelining() -> Result<()> {
        let setup = TestStream::from(vec![Poll::Ready(Some(Ok(Raw(b("quit\r\nquit\r\n")))))]);
        let mut sut = setup.parse(FakeParser(vec![
            Command(Quit, b("quit\r\n")),
            Command(Quit, b("quit\r\n")),
        ]));

        let res = Pin::new(&mut sut).poll_next(&mut cx());
        if let Poll::Ready(Some(Ok(Command(Quit, _)))) = res {
            //cool
        } else {
            panic!("Expected Quit command, got {:?}", res)
        }

        let res = Pin::new(&mut sut).poll_next(&mut cx());
        if let Poll::Ready(Some(Ok(Command(Quit, _)))) = res {
            //cool
        } else {
            panic!("Expected Quit command, got {:?}", res)
        }

        Ok(())
    }
}