Skip to main content

io_imap/rfc3501/
noop.rs

1//! IMAP NOOP coroutine, useful as keep-alive or update poll.
2//!
3//! # Example
4//!
5//! ```rust,no_run
6//! use std::{
7//!     io::{Read, Write},
8//!     net::TcpStream,
9//! };
10//!
11//! use io_imap::{
12//!     codec::fragmentizer::Fragmentizer,
13//!     coroutine::{ImapCoroutine, ImapCoroutineState, ImapYield},
14//!     rfc3501::noop::ImapNoop,
15//! };
16//!
17//! // Ready stream needed (TCP-connected, TLS-negociated, IMAP-authenticated)
18//! let mut stream = TcpStream::connect("localhost:143").unwrap();
19//!
20//! let mut fragmentizer = Fragmentizer::new(50 * 1024 * 1024);
21//! let mut buf = [0u8; 4096];
22//!
23//! let mut coroutine = ImapNoop::new();
24//! let mut arg = None;
25//!
26//! loop {
27//!     match coroutine.resume(&mut fragmentizer, arg.take()) {
28//!         ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => {
29//!             stream.write_all(&bytes).unwrap();
30//!         }
31//!         ImapCoroutineState::Yielded(ImapYield::WantsRead) => {
32//!             let n = stream.read(&mut buf).unwrap();
33//!             arg = Some(&buf[..n]);
34//!         }
35//!         ImapCoroutineState::Complete(Ok(())) => break,
36//!         ImapCoroutineState::Complete(Err(err)) => panic!("{err}"),
37//!     }
38//! }
39//! ```
40
41use core::fmt;
42
43use alloc::string::{String, ToString};
44
45use imap_codec::{
46    CommandCodec,
47    fragmentizer::Fragmentizer,
48    imap_types::{
49        command::{Command, CommandBody},
50        core::TagGenerator,
51        response::{StatusKind, Tagged},
52    },
53};
54use log::trace;
55use thiserror::Error;
56
57use crate::{coroutine::*, imap_try, send::*};
58
59/// Failure causes during the IMAP NOOP flow.
60#[derive(Clone, Debug, Error)]
61pub enum ImapNoopError {
62    #[error("IMAP NOOP failed: NO {0}")]
63    No(String),
64    #[error("IMAP NOOP failed: BAD {0}")]
65    Bad(String),
66    #[error("IMAP NOOP failed: BYE {0}")]
67    Bye(String),
68
69    #[error("IMAP NOOP failed: server did not return a tagged response")]
70    MissingTagged,
71
72    #[error("IMAP NOOP failed: {0}")]
73    Send(#[from] SendImapCommandError),
74}
75
76/// I/O-free IMAP NOOP coroutine.
77pub struct ImapNoop {
78    state: State,
79}
80
81impl ImapNoop {
82    pub fn new() -> Self {
83        let command = Command {
84            tag: TagGenerator::new().generate(),
85            body: CommandBody::Noop,
86        };
87
88        trace!("send IMAP command {command:?}");
89
90        let state = State::Send(SendImapCommand::new(CommandCodec::new(), command));
91
92        Self { state }
93    }
94}
95
96impl Default for ImapNoop {
97    fn default() -> Self {
98        Self::new()
99    }
100}
101
102impl ImapCoroutine for ImapNoop {
103    type Yield = ImapYield;
104    type Return = Result<(), ImapNoopError>;
105
106    fn resume(
107        &mut self,
108        fragmentizer: &mut Fragmentizer,
109        arg: Option<&[u8]>,
110    ) -> ImapCoroutineState<Self::Yield, Self::Return> {
111        loop {
112            trace!("noop: {}", self.state);
113
114            match &mut self.state {
115                State::Send(send) => {
116                    let out = imap_try!(send, fragmentizer, arg);
117
118                    if let Some(bye) = out.bye {
119                        let err = ImapNoopError::Bye(bye.text.to_string());
120                        return ImapCoroutineState::Complete(Err(err));
121                    }
122
123                    let Some(Tagged { body, .. }) = out.tagged else {
124                        let err = ImapNoopError::MissingTagged;
125                        return ImapCoroutineState::Complete(Err(err));
126                    };
127
128                    return match body.kind {
129                        StatusKind::Ok => ImapCoroutineState::Complete(Ok(())),
130                        StatusKind::No => {
131                            let err = ImapNoopError::No(body.text.to_string());
132                            ImapCoroutineState::Complete(Err(err))
133                        }
134                        StatusKind::Bad => {
135                            let err = ImapNoopError::Bad(body.text.to_string());
136                            ImapCoroutineState::Complete(Err(err))
137                        }
138                    };
139                }
140            }
141        }
142    }
143}
144
145enum State {
146    Send(SendImapCommand<CommandCodec>),
147}
148
149impl fmt::Display for State {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        match self {
152            Self::Send(_) => f.write_str("send noop"),
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use core::str;
160
161    use alloc::{borrow::ToOwned, vec::Vec};
162
163    use super::*;
164
165    #[test]
166    fn success_returns_ok() {
167        let mut noop = ImapNoop::new();
168        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
169
170        let bytes = expect_wants_write(&mut noop, &mut frag, None);
171        let line = str::from_utf8(&bytes).expect("utf8 command");
172        let tag = first_word(line).to_owned();
173        assert!(line.trim_end().ends_with("NOOP"));
174
175        expect_wants_read(&mut noop, &mut frag);
176
177        let reply = format!("{tag} OK NOOP completed\r\n");
178        expect_complete_ok(&mut noop, &mut frag, reply.as_bytes());
179    }
180
181    #[test]
182    fn tagged_bad_returns_bad_error() {
183        let mut noop = ImapNoop::new();
184        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
185
186        let bytes = expect_wants_write(&mut noop, &mut frag, None);
187        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
188
189        expect_wants_read(&mut noop, &mut frag);
190
191        let reply = format!("{tag} BAD NOOP syntax error\r\n");
192        let err = expect_complete_err(&mut noop, &mut frag, reply.as_bytes());
193        let ImapNoopError::Bad(text) = err else {
194            panic!("expected ImapNoopError::Bad, got {err:?}");
195        };
196        assert_eq!(text, "NOOP syntax error");
197    }
198
199    #[test]
200    fn bye_returns_bye_error() {
201        let mut noop = ImapNoop::new();
202        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
203
204        let _ = expect_wants_write(&mut noop, &mut frag, None);
205        expect_wants_read(&mut noop, &mut frag);
206
207        let err = expect_complete_err(&mut noop, &mut frag, b"* BYE going down\r\n");
208        let ImapNoopError::Bye(text) = err else {
209            panic!("expected ImapNoopError::Bye, got {err:?}");
210        };
211        assert_eq!(text, "going down");
212    }
213
214    // --- utils
215
216    fn expect_wants_write(
217        cor: &mut ImapNoop,
218        frag: &mut Fragmentizer,
219        arg: Option<&[u8]>,
220    ) -> Vec<u8> {
221        match cor.resume(frag, arg) {
222            ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
223            state => panic!("expected WantsWrite, got {state:?}"),
224        }
225    }
226
227    fn expect_wants_read(cor: &mut ImapNoop, frag: &mut Fragmentizer) {
228        match cor.resume(frag, None) {
229            ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
230            state => panic!("expected WantsRead, got {state:?}"),
231        }
232    }
233
234    fn expect_complete_ok(cor: &mut ImapNoop, frag: &mut Fragmentizer, reply: &[u8]) {
235        match cor.resume(frag, Some(reply)) {
236            ImapCoroutineState::Complete(Ok(())) => {}
237            state => panic!("expected Complete(Ok), got {state:?}"),
238        }
239    }
240
241    fn expect_complete_err(
242        cor: &mut ImapNoop,
243        frag: &mut Fragmentizer,
244        reply: &[u8],
245    ) -> ImapNoopError {
246        match cor.resume(frag, Some(reply)) {
247            ImapCoroutineState::Complete(Err(err)) => err,
248            state => panic!("expected Complete(Err), got {state:?}"),
249        }
250    }
251
252    fn first_word(line: &str) -> &str {
253        line.split_whitespace()
254            .next()
255            .expect("first whitespace-separated token")
256    }
257}