Skip to main content

io_imap/rfc3501/
unsubscribe.rs

1//! IMAP UNSUBSCRIBE coroutine removing a mailbox from the subscription list.
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::unsubscribe::ImapMailboxUnsubscribe,
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 mailbox = "Archive".try_into().unwrap();
24//! let mut coroutine = ImapMailboxUnsubscribe::new(mailbox);
25//! let mut arg = None;
26//!
27//! loop {
28//!     match coroutine.resume(&mut fragmentizer, arg.take()) {
29//!         ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => {
30//!             stream.write_all(&bytes).unwrap();
31//!         }
32//!         ImapCoroutineState::Yielded(ImapYield::WantsRead) => {
33//!             let n = stream.read(&mut buf).unwrap();
34//!             arg = Some(&buf[..n]);
35//!         }
36//!         ImapCoroutineState::Complete(Ok(())) => break,
37//!         ImapCoroutineState::Complete(Err(err)) => panic!("{err}"),
38//!     }
39//! }
40//! ```
41
42use core::fmt;
43
44use alloc::string::{String, ToString};
45
46use imap_codec::{
47    CommandCodec,
48    fragmentizer::Fragmentizer,
49    imap_types::{
50        command::{Command, CommandBody},
51        core::TagGenerator,
52        mailbox::Mailbox,
53        response::{StatusKind, Tagged},
54    },
55};
56use log::trace;
57use thiserror::Error;
58
59use crate::{coroutine::*, imap_try, rfc3501::mailbox::encode_inplace, send::*};
60
61/// Failure causes during the IMAP UNSUBSCRIBE flow.
62#[derive(Clone, Debug, Error)]
63pub enum ImapMailboxUnsubscribeError {
64    /// The server rejected the command with a NO response.
65    #[error("IMAP UNSUBSCRIBE failed: NO {0}")]
66    No(String),
67    /// The server rejected the command with a BAD response.
68    #[error("IMAP UNSUBSCRIBE failed: BAD {0}")]
69    Bad(String),
70    /// The server closed the session with an untagged BYE.
71    #[error("IMAP UNSUBSCRIBE failed: BYE {0}")]
72    Bye(String),
73    /// The exchange ended without a tagged response from the server.
74    #[error("IMAP UNSUBSCRIBE failed: server did not return a tagged response")]
75    MissingTagged,
76    /// The underlying send/receive exchange failed (EOF, decode, framing).
77    #[error("IMAP UNSUBSCRIBE failed: {0}")]
78    Send(#[from] ImapSendError),
79}
80
81/// I/O-free IMAP UNSUBSCRIBE coroutine.
82pub struct ImapMailboxUnsubscribe {
83    state: State,
84}
85
86impl ImapMailboxUnsubscribe {
87    /// Builds an UNSUBSCRIBE coroutine removing `mailbox` from the
88    /// subscription list.
89    pub fn new(mut mailbox: Mailbox<'static>) -> Self {
90        encode_inplace(&mut mailbox);
91
92        let command = Command {
93            tag: TagGenerator::new().generate(),
94            body: CommandBody::Unsubscribe { mailbox },
95        };
96
97        trace!("send IMAP command {command:?}");
98
99        let state = State::Send(ImapSend::new(CommandCodec::new(), command));
100
101        Self { state }
102    }
103}
104
105impl ImapCoroutine for ImapMailboxUnsubscribe {
106    type Yield = ImapYield;
107    type Return = Result<(), ImapMailboxUnsubscribeError>;
108
109    fn resume(
110        &mut self,
111        fragmentizer: &mut Fragmentizer,
112        arg: Option<&[u8]>,
113    ) -> ImapCoroutineState<Self::Yield, Self::Return> {
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 = ImapMailboxUnsubscribeError::Bye(bye.text.to_string());
120                    return ImapCoroutineState::Complete(Err(err));
121                }
122
123                let Some(Tagged { body, .. }) = out.tagged else {
124                    let err = ImapMailboxUnsubscribeError::MissingTagged;
125                    return ImapCoroutineState::Complete(Err(err));
126                };
127
128                match body.kind {
129                    StatusKind::Ok => ImapCoroutineState::Complete(Ok(())),
130                    StatusKind::No => {
131                        let err = ImapMailboxUnsubscribeError::No(body.text.to_string());
132                        ImapCoroutineState::Complete(Err(err))
133                    }
134                    StatusKind::Bad => {
135                        let err = ImapMailboxUnsubscribeError::Bad(body.text.to_string());
136                        ImapCoroutineState::Complete(Err(err))
137                    }
138                }
139            }
140        }
141    }
142}
143
144enum State {
145    Send(ImapSend<CommandCodec>),
146}
147
148impl fmt::Display for State {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        match self {
151            Self::Send(_) => f.write_str("send unsubscribe"),
152        }
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use core::str;
159
160    use alloc::{borrow::ToOwned, format, vec::Vec};
161
162    use crate::rfc3501::unsubscribe::*;
163
164    #[test]
165    fn success_returns_ok() {
166        let mut unsub = ImapMailboxUnsubscribe::new("Archive".try_into().expect("valid mailbox"));
167        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
168
169        let bytes = expect_wants_write(&mut unsub, &mut frag, None);
170        let line = str::from_utf8(&bytes).expect("utf8 command");
171        let tag = first_word(line).to_owned();
172        assert!(line.contains("UNSUBSCRIBE Archive"));
173
174        expect_wants_read(&mut unsub, &mut frag);
175
176        let reply = format!("{tag} OK UNSUBSCRIBE completed\r\n");
177        expect_complete_ok(&mut unsub, &mut frag, reply.as_bytes());
178    }
179
180    #[test]
181    fn tagged_no_returns_no_error() {
182        let mut unsub = ImapMailboxUnsubscribe::new("Archive".try_into().expect("valid mailbox"));
183        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
184
185        let bytes = expect_wants_write(&mut unsub, &mut frag, None);
186        let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
187
188        expect_wants_read(&mut unsub, &mut frag);
189
190        let reply = format!("{tag} NO not subscribed\r\n");
191        let err = expect_complete_err(&mut unsub, &mut frag, reply.as_bytes());
192        let ImapMailboxUnsubscribeError::No(text) = err else {
193            panic!("expected ImapMailboxUnsubscribeError::No, got {err:?}");
194        };
195        assert_eq!(text, "not subscribed");
196    }
197
198    #[test]
199    fn bye_returns_bye_error() {
200        let mut unsub = ImapMailboxUnsubscribe::new("Archive".try_into().expect("valid mailbox"));
201        let mut frag = Fragmentizer::new(50 * 1024 * 1024);
202
203        let _ = expect_wants_write(&mut unsub, &mut frag, None);
204        expect_wants_read(&mut unsub, &mut frag);
205
206        let err = expect_complete_err(&mut unsub, &mut frag, b"* BYE going down\r\n");
207        let ImapMailboxUnsubscribeError::Bye(text) = err else {
208            panic!("expected ImapMailboxUnsubscribeError::Bye, got {err:?}");
209        };
210        assert_eq!(text, "going down");
211    }
212
213    fn expect_wants_write(
214        cor: &mut ImapMailboxUnsubscribe,
215        frag: &mut Fragmentizer,
216        arg: Option<&[u8]>,
217    ) -> Vec<u8> {
218        match cor.resume(frag, arg) {
219            ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
220            state => panic!("expected WantsWrite, got {state:?}"),
221        }
222    }
223
224    fn expect_wants_read(cor: &mut ImapMailboxUnsubscribe, frag: &mut Fragmentizer) {
225        match cor.resume(frag, None) {
226            ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
227            state => panic!("expected WantsRead, got {state:?}"),
228        }
229    }
230
231    fn expect_complete_ok(cor: &mut ImapMailboxUnsubscribe, frag: &mut Fragmentizer, reply: &[u8]) {
232        match cor.resume(frag, Some(reply)) {
233            ImapCoroutineState::Complete(Ok(())) => {}
234            state => panic!("expected Complete(Ok), got {state:?}"),
235        }
236    }
237
238    fn expect_complete_err(
239        cor: &mut ImapMailboxUnsubscribe,
240        frag: &mut Fragmentizer,
241        reply: &[u8],
242    ) -> ImapMailboxUnsubscribeError {
243        match cor.resume(frag, Some(reply)) {
244            ImapCoroutineState::Complete(Err(err)) => err,
245            state => panic!("expected Complete(Err), got {state:?}"),
246        }
247    }
248
249    fn first_word(line: &str) -> &str {
250        line.split_whitespace()
251            .next()
252            .expect("first whitespace-separated token")
253    }
254}