Skip to main content

io_imap/rfc3691/
unselect.rs

1//! IMAP UNSELECT coroutine: like CLOSE but without expunging \Deleted.
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//!     rfc3691::unselect::ImapMailboxUnselect,
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 = ImapMailboxUnselect::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 UNSELECT flow.
60#[derive(Clone, Debug, Error)]
61pub enum ImapMailboxUnselectError {
62    /// The server rejected the UNSELECT command with a NO response.
63    #[error("IMAP UNSELECT failed: NO {0}")]
64    No(String),
65    /// The server rejected the UNSELECT command with a BAD response.
66    #[error("IMAP UNSELECT failed: BAD {0}")]
67    Bad(String),
68    /// The server closed the connection with a BYE response.
69    #[error("IMAP UNSELECT failed: BYE {0}")]
70    Bye(String),
71    /// The server never answered with a tagged response.
72    #[error("IMAP UNSELECT failed: server did not return a tagged response")]
73    MissingTagged,
74    /// The underlying send sub-coroutine failed.
75    #[error("IMAP UNSELECT failed: {0}")]
76    Send(#[from] ImapSendError),
77}
78
79/// I/O-free IMAP UNSELECT coroutine.
80pub struct ImapMailboxUnselect {
81    state: State,
82}
83
84impl ImapMailboxUnselect {
85    /// Creates a coroutine that UNSELECTs the current mailbox without
86    /// expunging its \Deleted messages.
87    pub fn new() -> Self {
88        let command = Command {
89            tag: TagGenerator::new().generate(),
90            body: CommandBody::Unselect,
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 ImapMailboxUnselect {
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107impl ImapCoroutine for ImapMailboxUnselect {
108    type Yield = ImapYield;
109    type Return = Result<(), ImapMailboxUnselectError>;
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 = ImapMailboxUnselectError::Bye(bye.text.to_string());
122                    return ImapCoroutineState::Complete(Err(err));
123                }
124
125                let Some(Tagged { body, .. }) = out.tagged else {
126                    let err = ImapMailboxUnselectError::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 = ImapMailboxUnselectError::No(body.text.to_string());
134                        ImapCoroutineState::Complete(Err(err))
135                    }
136                    StatusKind::Bad => {
137                        let err = ImapMailboxUnselectError::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 unselect"),
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::rfc3691::unselect::*;
165
166    #[test]
167    fn success_returns_ok() {
168        let mut unselect = ImapMailboxUnselect::new();
169        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
170
171        let bytes = expect_wants_write(&mut unselect, &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("UNSELECT"));
175
176        expect_wants_read(&mut unselect, &mut frag);
177
178        let reply = format!("{tag} OK UNSELECT completed\r\n");
179        expect_complete_ok(&mut unselect, &mut frag, reply.as_bytes());
180    }
181
182    #[test]
183    fn tagged_no_returns_no_error() {
184        let mut unselect = ImapMailboxUnselect::new();
185        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
186
187        let bytes = expect_wants_write(&mut unselect, &mut frag, None);
188        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
189
190        expect_wants_read(&mut unselect, &mut frag);
191
192        let reply = format!("{tag} NO no mailbox selected\r\n");
193        let err = expect_complete_err(&mut unselect, &mut frag, reply.as_bytes());
194        let ImapMailboxUnselectError::No(text) = err else {
195            panic!("expected ImapMailboxUnselectError::No, got {err:?}");
196        };
197        assert_eq!(text, "no mailbox selected");
198    }
199
200    #[test]
201    fn tagged_bad_returns_bad_error() {
202        let mut unselect = ImapMailboxUnselect::new();
203        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
204
205        let bytes = expect_wants_write(&mut unselect, &mut frag, None);
206        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
207
208        expect_wants_read(&mut unselect, &mut frag);
209
210        let reply = format!("{tag} BAD UNSELECT not supported\r\n");
211        let err = expect_complete_err(&mut unselect, &mut frag, reply.as_bytes());
212        let ImapMailboxUnselectError::Bad(text) = err else {
213            panic!("expected ImapMailboxUnselectError::Bad, got {err:?}");
214        };
215        assert_eq!(text, "UNSELECT not supported");
216    }
217
218    #[test]
219    fn bye_returns_bye_error() {
220        let mut unselect = ImapMailboxUnselect::new();
221        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
222
223        let _ = expect_wants_write(&mut unselect, &mut frag, None);
224        expect_wants_read(&mut unselect, &mut frag);
225
226        let err = expect_complete_err(&mut unselect, &mut frag, b"* BYE going down\r\n");
227        let ImapMailboxUnselectError::Bye(text) = err else {
228            panic!("expected ImapMailboxUnselectError::Bye, got {err:?}");
229        };
230        assert_eq!(text, "going down");
231    }
232
233    fn expect_wants_write(
234        cor: &mut ImapMailboxUnselect,
235        frag: &mut Fragmentizer,
236        arg: Option<&[u8]>,
237    ) -> Vec<u8> {
238        match cor.resume(frag, arg) {
239            ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
240            state => panic!("expected WantsWrite, got {state:?}"),
241        }
242    }
243
244    fn expect_wants_read(cor: &mut ImapMailboxUnselect, frag: &mut Fragmentizer) {
245        match cor.resume(frag, None) {
246            ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
247            state => panic!("expected WantsRead, got {state:?}"),
248        }
249    }
250
251    fn expect_complete_ok(cor: &mut ImapMailboxUnselect, frag: &mut Fragmentizer, reply: &[u8]) {
252        match cor.resume(frag, Some(reply)) {
253            ImapCoroutineState::Complete(Ok(())) => {}
254            state => panic!("expected Complete(Ok), got {state:?}"),
255        }
256    }
257
258    fn expect_complete_err(
259        cor: &mut ImapMailboxUnselect,
260        frag: &mut Fragmentizer,
261        reply: &[u8],
262    ) -> ImapMailboxUnselectError {
263        match cor.resume(frag, Some(reply)) {
264            ImapCoroutineState::Complete(Err(err)) => err,
265            state => panic!("expected Complete(Err), got {state:?}"),
266        }
267    }
268
269    fn first_word(line: &str) -> &str {
270        line.split_whitespace()
271            .next()
272            .expect("first whitespace-separated token")
273    }
274}