Skip to main content

io_imap/rfc3501/
logout.rs

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