1use core::fmt;
47
48use alloc::{string::String, string::ToString, vec::Vec};
49
50use imap_codec::{
51 CommandCodec,
52 fragmentizer::Fragmentizer,
53 imap_types::{
54 command::{Command, CommandBody},
55 core::{TagGenerator, Vec1},
56 extensions::enable::CapabilityEnable,
57 response::{Data, StatusKind, Tagged},
58 },
59};
60use log::trace;
61use thiserror::Error;
62
63use crate::{coroutine::*, imap_try, send::*};
64
65#[derive(Clone, Debug, Error)]
67pub enum ImapExtensionEnableError {
68 #[error("IMAP ENABLE failed: NO {0}")]
70 No(String),
71 #[error("IMAP ENABLE failed: BAD {0}")]
73 Bad(String),
74 #[error("IMAP ENABLE failed: BYE {0}")]
76 Bye(String),
77 #[error("IMAP ENABLE failed: server did not return a tagged response")]
79 MissingTagged,
80 #[error("IMAP ENABLE failed: {0}")]
82 Send(#[from] ImapSendError),
83}
84
85pub struct ImapExtensionEnable {
87 state: State,
88}
89
90impl ImapExtensionEnable {
91 pub fn new(capabilities: Vec1<CapabilityEnable<'static>>) -> Self {
94 let command = Command {
95 tag: TagGenerator::new().generate(),
96 body: CommandBody::Enable { capabilities },
97 };
98
99 trace!("send IMAP command {command:?}");
100
101 let state = State::Send(ImapSend::new(CommandCodec::new(), command));
102
103 Self { state }
104 }
105}
106
107impl ImapCoroutine for ImapExtensionEnable {
108 type Yield = ImapYield;
109 type Return = Result<Option<Vec<CapabilityEnable<'static>>>, ImapExtensionEnableError>;
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 = ImapExtensionEnableError::Bye(bye.text.to_string());
122 return ImapCoroutineState::Complete(Err(err));
123 }
124
125 let Some(Tagged { body, .. }) = out.tagged else {
126 let err = ImapExtensionEnableError::MissingTagged;
127 return ImapCoroutineState::Complete(Err(err));
128 };
129
130 let mut enabled = None;
131 for data in out.data {
132 if let Data::Enabled { capabilities } = data {
133 enabled = Some(capabilities);
134 }
135 }
136
137 match body.kind {
138 StatusKind::Ok => ImapCoroutineState::Complete(Ok(enabled)),
139 StatusKind::No => {
140 let err = ImapExtensionEnableError::No(body.text.to_string());
141 ImapCoroutineState::Complete(Err(err))
142 }
143 StatusKind::Bad => {
144 let err = ImapExtensionEnableError::Bad(body.text.to_string());
145 ImapCoroutineState::Complete(Err(err))
146 }
147 }
148 }
149 }
150 }
151}
152
153enum State {
154 Send(ImapSend<CommandCodec>),
155}
156
157impl fmt::Display for State {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 match self {
160 Self::Send(_) => f.write_str("send enable"),
161 }
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use core::str;
168
169 use alloc::{borrow::ToOwned, format, vec, vec::Vec};
170
171 use crate::rfc5161::enable::*;
172
173 fn caps() -> Vec1<CapabilityEnable<'static>> {
174 Vec1::try_from(vec![CapabilityEnable::CondStore]).expect("one cap")
175 }
176
177 #[test]
178 fn success_returns_enabled_list() {
179 let mut enable = ImapExtensionEnable::new(caps());
180 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
181
182 let bytes = expect_wants_write(&mut enable, &mut frag, None);
183 let line = str::from_utf8(&bytes).expect("utf8 command");
184 let tag = first_word(line).to_owned();
185 assert!(line.contains("ENABLE CONDSTORE"));
186
187 expect_wants_read(&mut enable, &mut frag);
188
189 let reply = format!("* ENABLED CONDSTORE\r\n{tag} OK ENABLE completed\r\n");
190 let enabled = expect_complete_ok(&mut enable, &mut frag, reply.as_bytes())
191 .expect("server returned ENABLED");
192 assert_eq!(1, enabled.len());
193 }
194
195 #[test]
196 fn success_without_enabled_returns_none() {
197 let mut enable = ImapExtensionEnable::new(caps());
198 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
199
200 let bytes = expect_wants_write(&mut enable, &mut frag, None);
201 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
202
203 expect_wants_read(&mut enable, &mut frag);
204
205 let reply = format!("{tag} OK ENABLE completed\r\n");
206 let enabled = expect_complete_ok(&mut enable, &mut frag, reply.as_bytes());
207 assert!(enabled.is_none());
208 }
209
210 #[test]
211 fn tagged_no_returns_no_error() {
212 let mut enable = ImapExtensionEnable::new(caps());
213 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
214
215 let bytes = expect_wants_write(&mut enable, &mut frag, None);
216 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
217
218 expect_wants_read(&mut enable, &mut frag);
219
220 let reply = format!("{tag} NO CONDSTORE not supported\r\n");
221 let err = expect_complete_err(&mut enable, &mut frag, reply.as_bytes());
222 let ImapExtensionEnableError::No(text) = err else {
223 panic!("expected ImapExtensionEnableError::No, got {err:?}");
224 };
225 assert_eq!(text, "CONDSTORE not supported");
226 }
227
228 #[test]
229 fn bye_returns_bye_error() {
230 let mut enable = ImapExtensionEnable::new(caps());
231 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
232
233 let _ = expect_wants_write(&mut enable, &mut frag, None);
234 expect_wants_read(&mut enable, &mut frag);
235
236 let err = expect_complete_err(&mut enable, &mut frag, b"* BYE going down\r\n");
237 let ImapExtensionEnableError::Bye(text) = err else {
238 panic!("expected ImapExtensionEnableError::Bye, got {err:?}");
239 };
240 assert_eq!(text, "going down");
241 }
242
243 fn expect_wants_write(
244 cor: &mut ImapExtensionEnable,
245 frag: &mut Fragmentizer,
246 arg: Option<&[u8]>,
247 ) -> Vec<u8> {
248 match cor.resume(frag, arg) {
249 ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
250 state => panic!("expected WantsWrite, got {state:?}"),
251 }
252 }
253
254 fn expect_wants_read(cor: &mut ImapExtensionEnable, frag: &mut Fragmentizer) {
255 match cor.resume(frag, None) {
256 ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
257 state => panic!("expected WantsRead, got {state:?}"),
258 }
259 }
260
261 fn expect_complete_ok(
262 cor: &mut ImapExtensionEnable,
263 frag: &mut Fragmentizer,
264 reply: &[u8],
265 ) -> Option<Vec<CapabilityEnable<'static>>> {
266 match cor.resume(frag, Some(reply)) {
267 ImapCoroutineState::Complete(Ok(value)) => value,
268 state => panic!("expected Complete(Ok), got {state:?}"),
269 }
270 }
271
272 fn expect_complete_err(
273 cor: &mut ImapExtensionEnable,
274 frag: &mut Fragmentizer,
275 reply: &[u8],
276 ) -> ImapExtensionEnableError {
277 match cor.resume(frag, Some(reply)) {
278 ImapCoroutineState::Complete(Err(err)) => err,
279 state => panic!("expected Complete(Err), got {state:?}"),
280 }
281 }
282
283 fn first_word(line: &str) -> &str {
284 line.split_whitespace()
285 .next()
286 .expect("first whitespace-separated token")
287 }
288}