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-negotiated, 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    /// The server rejected the command with a NO response.
63    #[error("IMAP NOOP failed: NO {0}")]
64    No(String),
65    /// The server rejected the command with a BAD response.
66    #[error("IMAP NOOP failed: BAD {0}")]
67    Bad(String),
68    /// The server closed the session with an untagged BYE.
69    #[error("IMAP NOOP failed: BYE {0}")]
70    Bye(String),
71    /// The exchange ended without a tagged response from the server.
72    #[error("IMAP NOOP failed: server did not return a tagged response")]
73    MissingTagged,
74    /// The underlying send/receive exchange failed (EOF, decode, framing).
75    #[error("IMAP NOOP failed: {0}")]
76    Send(#[from] ImapSendError),
77}
78
79/// I/O-free IMAP NOOP coroutine.
80pub struct ImapNoop {
81    state: State,
82}
83
84impl ImapNoop {
85    /// Builds a NOOP coroutine polling the server for pending updates
86    /// (or just keeping the session alive).
87    pub fn new() -> Self {
88        let command = Command {
89            tag: TagGenerator::new().generate(),
90            body: CommandBody::Noop,
91        };
92
93        trace!("send IMAP command {command:?}");
94
95        let state = State::Send(ImapSend::new(CommandCodec::new(), command));
96
97        Self { state }
98    }
99}
100
101impl Default for ImapNoop {
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107impl ImapCoroutine for ImapNoop {
108    type Yield = ImapYield;
109    type Return = Result<(), ImapNoopError>;
110
111    fn resume(
112        &mut self,
113        fragmentizer: &mut Fragmentizer,
114        arg: Option<&[u8]>,
115    ) -> ImapCoroutineState<Self::Yield, Self::Return> {
116        match &mut self.state {
117            State::Send(send) => {
118                let out = imap_try!(send, fragmentizer, arg);
119
120                if let Some(bye) = out.bye {
121                    let err = ImapNoopError::Bye(bye.text.to_string());
122                    return ImapCoroutineState::Complete(Err(err));
123                }
124
125                let Some(Tagged { body, .. }) = out.tagged else {
126                    let err = ImapNoopError::MissingTagged;
127                    return ImapCoroutineState::Complete(Err(err));
128                };
129
130                match body.kind {
131                    StatusKind::Ok => ImapCoroutineState::Complete(Ok(())),
132                    StatusKind::No => {
133                        let err = ImapNoopError::No(body.text.to_string());
134                        ImapCoroutineState::Complete(Err(err))
135                    }
136                    StatusKind::Bad => {
137                        let err = ImapNoopError::Bad(body.text.to_string());
138                        ImapCoroutineState::Complete(Err(err))
139                    }
140                }
141            }
142        }
143    }
144}
145
146enum State {
147    Send(ImapSend<CommandCodec>),
148}
149
150impl fmt::Display for State {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            Self::Send(_) => f.write_str("send noop"),
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use core::str;
161
162    use alloc::{borrow::ToOwned, format, vec::Vec};
163
164    use crate::rfc3501::noop::*;
165
166    #[test]
167    fn success_returns_ok() {
168        let mut noop = ImapNoop::new();
169        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
170
171        let bytes = expect_wants_write(&mut noop, &mut frag, None);
172        let line = str::from_utf8(&bytes).expect("utf8 command");
173        let tag = first_word(line).to_owned();
174        assert!(line.trim_end().ends_with("NOOP"));
175
176        expect_wants_read(&mut noop, &mut frag);
177
178        let reply = format!("{tag} OK NOOP completed\r\n");
179        expect_complete_ok(&mut noop, &mut frag, reply.as_bytes());
180    }
181
182    #[test]
183    fn tagged_bad_returns_bad_error() {
184        let mut noop = ImapNoop::new();
185        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
186
187        let bytes = expect_wants_write(&mut noop, &mut frag, None);
188        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
189
190        expect_wants_read(&mut noop, &mut frag);
191
192        let reply = format!("{tag} BAD NOOP syntax error\r\n");
193        let err = expect_complete_err(&mut noop, &mut frag, reply.as_bytes());
194        let ImapNoopError::Bad(text) = err else {
195            panic!("expected ImapNoopError::Bad, got {err:?}");
196        };
197        assert_eq!(text, "NOOP syntax error");
198    }
199
200    #[test]
201    fn bye_returns_bye_error() {
202        let mut noop = ImapNoop::new();
203        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
204
205        let _ = expect_wants_write(&mut noop, &mut frag, None);
206        expect_wants_read(&mut noop, &mut frag);
207
208        let err = expect_complete_err(&mut noop, &mut frag, b"* BYE going down\r\n");
209        let ImapNoopError::Bye(text) = err else {
210            panic!("expected ImapNoopError::Bye, got {err:?}");
211        };
212        assert_eq!(text, "going down");
213    }
214
215    fn expect_wants_write(
216        cor: &mut ImapNoop,
217        frag: &mut Fragmentizer,
218        arg: Option<&[u8]>,
219    ) -> Vec<u8> {
220        match cor.resume(frag, arg) {
221            ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
222            state => panic!("expected WantsWrite, got {state:?}"),
223        }
224    }
225
226    fn expect_wants_read(cor: &mut ImapNoop, frag: &mut Fragmentizer) {
227        match cor.resume(frag, None) {
228            ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
229            state => panic!("expected WantsRead, got {state:?}"),
230        }
231    }
232
233    fn expect_complete_ok(cor: &mut ImapNoop, frag: &mut Fragmentizer, reply: &[u8]) {
234        match cor.resume(frag, Some(reply)) {
235            ImapCoroutineState::Complete(Ok(())) => {}
236            state => panic!("expected Complete(Ok), got {state:?}"),
237        }
238    }
239
240    fn expect_complete_err(
241        cor: &mut ImapNoop,
242        frag: &mut Fragmentizer,
243        reply: &[u8],
244    ) -> ImapNoopError {
245        match cor.resume(frag, Some(reply)) {
246            ImapCoroutineState::Complete(Err(err)) => err,
247            state => panic!("expected Complete(Err), got {state:?}"),
248        }
249    }
250
251    fn first_word(line: &str) -> &str {
252        line.split_whitespace()
253            .next()
254            .expect("first whitespace-separated token")
255    }
256}