crymap 2.0.1

A simple, secure IMAP server with encrypted data at rest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//-
// Copyright (c) 2020, 2023, 2024, Jason Lingle
//
// This file is part of Crymap.
//
// Crymap is free software: you can  redistribute it and/or modify it under the
// terms of  the GNU General Public  License as published by  the Free Software
// Foundation, either version  3 of the License, or (at  your option) any later
// version.
//
// Crymap is distributed  in the hope that  it will be useful,  but WITHOUT ANY
// WARRANTY; without  even the implied  warranty of MERCHANTABILITY  or FITNESS
// FOR  A PARTICULAR  PURPOSE.  See the  GNU General  Public  License for  more
// details.
//
// You should have received a copy of the GNU General Public License along with
// Crymap. If not, see <http://www.gnu.org/licenses/>.

use std::borrow::Cow;
use std::convert::TryInto;

use log::{error, info};

use super::defs::*;
use crate::{
    account::model::{PollResponse, SeqRange},
    imap::response_writer::{OutputControl, OutputEvent},
    support::error::Error,
};

impl CommandProcessor {
    /// Return the greeting line to return to the client.
    pub fn greet(&self) -> s::ResponseLine<'static> {
        s::ResponseLine {
            tag: None,
            response: s::Response::Cond(s::CondResponse {
                cond: s::RespCondType::Ok,
                code: Some(s::RespTextCode::Capability(capability_data())),
                quip: Some(Cow::Borrowed(TAGLINE)),
            }),
        }
    }

    /// Handles a regular command, i.e., one that the protocol level does not
    /// give special treatment to.
    ///
    /// `sender` can passed secondary responses as needed.
    ///
    /// Returns the final, tagged response. If the response condition is `BYE`,
    /// the connection will be closed after sending it.
    pub async fn handle_command(
        &mut self,
        command_line: s::CommandLine<'_>,
        mut sender: SendResponse,
    ) -> s::ResponseLine<'static> {
        let sender = &mut sender;
        let allow_full_poll = match command_line.cmd {
            // FETCH, STORE, and SEARCH (the non-UID versions) are the only
            // cursed commands that don't allow us to update the message state
            // in response.
            s::Command::Fetch(..)
            | s::Command::Store(..)
            | s::Command::Search(..) => false,
            _ => true,
        };

        // If this gets set to true and QRESYNC is enabled, a HIGHESTMODSEQ
        // response code must be stapled onto the tagged response if it doesn't
        // already have a response code.
        //
        // This is used to implement RFC 7162's requirement that the tagged
        // `OK` response to `[UID] EXPUNGE` include this response code, unlike
        // every other situation where the data is sent on an untagged
        // response. (Note we still send the untagged response as well, but
        // only if anything actually changed --- but the case for [UID] EXPUNGE
        // is unconditional for simplicity.)
        let mut staple_highest_modseq = false;

        let res = match command_line.cmd {
            s::Command::Simple(s::SimpleCommand::Capability) => {
                self.cmd_capability(sender).await
            },
            s::Command::Simple(s::SimpleCommand::Check) => {
                self.cmd_noop("Nothing exciting")
            },
            s::Command::Simple(s::SimpleCommand::Close) => self.cmd_close(),
            s::Command::Simple(s::SimpleCommand::Compress) => {
                panic!("COMPRESS DEFLATE should be handled by server.rs")
            },
            s::Command::Simple(s::SimpleCommand::Expunge) => {
                staple_highest_modseq = self.qresync_enabled;
                self.cmd_expunge()
            },
            s::Command::Simple(s::SimpleCommand::Idle) => {
                panic!("IDLE should be dispatched by server.rs")
            },
            s::Command::Simple(s::SimpleCommand::LogOut) => {
                self.cmd_log_out(sender).await
            },
            s::Command::Simple(s::SimpleCommand::Namespace) => {
                self.cmd_namespace(sender).await
            },
            s::Command::Simple(s::SimpleCommand::Noop) => {
                self.cmd_noop("NOOP OK")
            },
            s::Command::Simple(s::SimpleCommand::StartTls) => {
                self.cmd_start_tls()
            },
            s::Command::Simple(s::SimpleCommand::Unselect) => {
                self.cmd_unselect()
            },
            s::Command::Simple(s::SimpleCommand::XCryFlagsOff) => {
                self.flag_responses_enabled = false;
                success()
            },
            s::Command::Simple(s::SimpleCommand::XCryFlagsOn) => {
                self.flag_responses_enabled = true;
                success()
            },
            s::Command::Simple(s::SimpleCommand::XCryPurge) => {
                self.cmd_xcry_purge()
            },
            s::Command::Simple(s::SimpleCommand::XCryGetUserConfig) => {
                self.cmd_xcry_get_user_config(sender).await
            },
            s::Command::Simple(s::SimpleCommand::XCryZstdTrain) => {
                self.cmd_xcry_zstd_train()
            },
            s::Command::Simple(s::SimpleCommand::Xyzzy) => {
                self.cmd_noop("Nothing happens")
            },
            s::Command::Simple(s::SimpleCommand::XAppendFinishedNoop) => {
                self.cmd_noop("APPEND OK")
            },

            s::Command::Create(cmd) => self.cmd_create(cmd),
            s::Command::Delete(cmd) => self.cmd_delete(cmd),
            s::Command::Examine(cmd) => self.cmd_examine(cmd, sender).await,
            s::Command::List(cmd) => self.cmd_list(cmd, sender).await,
            s::Command::Lsub(cmd) => self.cmd_lsub(cmd, sender).await,
            s::Command::Xlist(cmd) => self.cmd_xlist(cmd, sender).await,
            s::Command::Rename(cmd) => self.cmd_rename(cmd),
            s::Command::Select(cmd) => self.cmd_select(cmd, sender).await,
            s::Command::Status(cmd) => self.cmd_status(cmd, sender).await,
            s::Command::Subscribe(cmd) => self.cmd_subscribe(cmd),
            s::Command::Unsubscribe(cmd) => self.cmd_unsubscribe(cmd),
            s::Command::LogIn(cmd) => self.cmd_log_in(cmd),
            s::Command::Copy(cmd) => self.cmd_copy(cmd, sender).await,
            s::Command::Move(cmd) => self.cmd_move(cmd, sender).await,
            s::Command::Fetch(cmd) => self.cmd_fetch(cmd, sender).await,
            s::Command::Store(cmd) => self.cmd_store(cmd, sender).await,
            s::Command::Search(cmd) => {
                self.cmd_search(cmd, &command_line.tag, sender).await
            },
            s::Command::XVanquish(uids) => self.cmd_vanquish(uids),

            s::Command::Uid(s::UidCommand::Copy(cmd)) => {
                self.cmd_uid_copy(cmd, sender).await
            },
            s::Command::Uid(s::UidCommand::Move(cmd)) => {
                self.cmd_uid_move(cmd, sender).await
            },
            s::Command::Uid(s::UidCommand::Fetch(cmd)) => {
                self.cmd_uid_fetch(cmd, sender).await
            },
            s::Command::Uid(s::UidCommand::Search(cmd)) => {
                self.cmd_uid_search(cmd, &command_line.tag, sender).await
            },
            s::Command::Uid(s::UidCommand::Store(cmd)) => {
                self.cmd_uid_store(cmd, sender).await
            },
            s::Command::Uid(s::UidCommand::Expunge(uids)) => {
                staple_highest_modseq = self.qresync_enabled;
                self.cmd_uid_expunge(uids)
            },

            s::Command::Id(parms) => self.cmd_id(parms, sender).await,

            s::Command::Enable(exts) => self.cmd_enable(exts, sender).await,

            s::Command::XCrySetUserConfig(configs) => {
                self.cmd_xcry_set_user_config(configs, sender).await
            },

            s::Command::XCryForeignSmtpTls(cmd) => {
                self.cmd_xcry_foreign_smtp_tls(cmd, sender).await
            },
            s::Command::XCrySmtpSpoolExecute(ids) => {
                self.cmd_xcry_smtp_spool_execute(ids).await
            },
        };

        if res.is_ok() {
            let poll_res = if allow_full_poll {
                self.full_poll(sender).await
            } else {
                self.mini_poll(sender).await
            };

            if let Err(err) = poll_res {
                error!("{} Poll failed: {}", self.log_prefix, err);
            }
        } else if let Some(selected) = self.selected.as_ref() {
            // If an error occurred and we have a selected mailbox, check that
            // the mailbox still exists. If not, disconnect the client instead
            // of letting them continue to flail in confusion.
            if !self
                .account
                .as_mut()
                .is_some_and(|a| a.is_usable_mailbox(selected))
            {
                return s::ResponseLine {
                    tag: None,
                    response: s::Response::Cond(s::CondResponse {
                        cond: s::RespCondType::Bye,
                        code: None,
                        quip: Some(Cow::Borrowed("Mailbox renamed or deleted")),
                    }),
                };
            }
        }

        if let Some(ref mut account) = self.account {
            account.clear_cache();
        }

        let mut res = match res {
            Ok(res) => res,
            Err(res) => res,
        };

        if staple_highest_modseq {
            if let (&Some(ref selected), &mut s::Response::Cond(ref mut cr)) =
                (&self.selected, &mut res)
            {
                if s::RespCondType::Ok == cr.cond && cr.code.is_none() {
                    cr.code = Some(s::RespTextCode::HighestModseq(
                        selected.snapshot_modseq().raw(),
                    ));
                }
            }
        }

        // For a cond response, if we have nothing better to say as far as a
        // "response code" goes and there's a pending unapplied expunge, tell
        // the client about it.
        if let s::Response::Cond(ref mut cr) = res {
            if cr.code.is_none()
                && self
                    .selected
                    .as_ref()
                    .map(|s| s.has_pending_expunge())
                    .unwrap_or(false)
            {
                cr.code = Some(s::RespTextCode::ExpungeIssued(()));
            }
        }

        maybe_tagged_response(command_line.tag, res)
    }

    async fn cmd_capability(&mut self, sender: &mut SendResponse) -> CmdResult {
        send_response(sender, s::Response::Capability(capability_data())).await;
        success()
    }

    async fn cmd_enable(
        &mut self,
        exts: Vec<Cow<'_, str>>,
        sender: &mut SendResponse,
    ) -> CmdResult {
        let mut enabled = Vec::new();
        // Per RFC 5161, we silently ignore any extension which isn't
        // ENABLE-able or known.
        for ext in exts {
            let ext = Cow::Owned(ext.clone().into_owned());
            if "XYZZY".eq_ignore_ascii_case(&ext) {
                enabled.push(ext);
            } else if "UTF8=ACCEPT".eq_ignore_ascii_case(&ext) {
                self.unicode_aware = true;
                self.utf8_enabled = true;
                send_event(sender, OutputEvent::EnableUnicode).await;
                enabled.push(ext);
            } else if "CONDSTORE".eq_ignore_ascii_case(&ext) {
                self.enable_condstore(sender, false).await;
                enabled.push(ext);
            } else if "QRESYNC".eq_ignore_ascii_case(&ext) {
                // RFC 7162 says:
                //
                // > A server compliant with this specification is REQUIRED to
                // > support "ENABLE QRESYNC" and "ENABLE QRESYNC CONDSTORE"
                // > (which are "CONDSTORE enabling commands", see Section 3.1,
                // > and have identical results).
                // > ...
                // > Clarified that ENABLE QRESYNC CONDSTORE and ENABLE
                // > CONDSTORE QRESYNC are equivalent.
                //
                // This would imply that `ENABLE QRESYNC` would need to include
                // an `ENABLED CONDSTORE` response, which is pretty strange.
                // Based on the trace in this (otherwise unrelated) post:
                // https://forum.vivaldi.net/topic/44076/can-t-add-email-account-to-mailspring-can-t-connect-to-smtp
                // it looks like Dovecot's approach is the more reasonable one:
                // `ENABLE QRESYNC` and `ENABLE QRESYNC CONDSTORE` are *not*
                // equivalent, but `ENABLE QRESYNC` enables a superset of
                // behaviours that `ENABLE CONDSTORE` does.
                //
                // That is, Dovecot answers
                //   . ENABLE QRESYNC
                // with
                //   * ENABLED QRESYNC
                // and not
                //   * ENABLED CONDSTORE QRESYNC
                //
                // This is what we do here as well.
                self.enable_condstore(sender, false).await;
                self.qresync_enabled = true;
                enabled.push(ext);
            } else if "IMAP4rev2".eq_ignore_ascii_case(&ext) {
                self.unicode_aware = true;
                self.imap4rev2_enabled = true;
                send_event(sender, OutputEvent::EnableUnicode).await;
                enabled.push(ext);
            }
        }

        let quip = if enabled.is_empty() {
            "Nothing enabled"
        } else {
            "The future is now"
        };

        send_response(sender, s::Response::Enabled(enabled)).await;
        Ok(s::Response::Cond(s::CondResponse {
            cond: s::RespCondType::Ok,
            code: None,
            quip: Some(Cow::Borrowed(quip)),
        }))
    }

    pub(super) async fn enable_condstore(
        &mut self,
        sender: &mut SendResponse,
        implicit: bool,
    ) {
        if self.condstore_enabled {
            return;
        }

        self.condstore_enabled = true;

        let highest_modseq =
            self.selected.as_ref().map(|s| s.snapshot_modseq().raw());

        // Only send an untagged OK if there's something interesting to say
        if implicit || highest_modseq.is_some() {
            send_response(
                sender,
                s::Response::Cond(s::CondResponse {
                    cond: s::RespCondType::Ok,
                    code: highest_modseq.map(s::RespTextCode::HighestModseq),
                    quip: Some(Cow::Borrowed(if implicit {
                        "CONDSTORE enabled implicitly"
                    } else {
                        "CONDSTORE enabled while already selected"
                    })),
                }),
            )
            .await;
        }
    }

    async fn cmd_id(
        &mut self,
        ids: Vec<Option<Cow<'_, str>>>,
        sender: &mut SendResponse,
    ) -> CmdResult {
        // Only take action on the first ID exchange so we don't keep
        // accumulating stuff in the log prefix.
        if !self.id_exchanged {
            let mut user_agent_name = String::new();
            let mut user_agent_version = String::new();
            let mut message = String::new();

            for pair in ids.chunks(2) {
                if 2 != pair.len() {
                    continue;
                }

                if let (&Some(ref name), &Some(ref value)) =
                    (&pair[0], &pair[1])
                {
                    if name.eq_ignore_ascii_case("name") {
                        user_agent_name = value.to_string();
                    }
                    if name.eq_ignore_ascii_case("version") {
                        user_agent_version = value.to_string();
                    }

                    message.push_str(" \"");
                    message.push_str(name);
                    message.push_str("\" = \"");
                    message.push_str(value);
                    message.push_str("\";");
                }
            }

            if !user_agent_name.is_empty() {
                self.log_prefix.set_user_agent(
                    Some(user_agent_name),
                    Some(user_agent_version).filter(|v| !v.is_empty()),
                );
            }

            info!(
                "{} ID exchanged; client says it is{}",
                self.log_prefix, message
            );
            self.id_exchanged = true;
        }

        let mut id_info = vec![
            Some(Cow::Borrowed("name")),
            Some(Cow::Borrowed(env!("CARGO_PKG_NAME"))),
            Some(Cow::Borrowed("version")),
            Some(Cow::Borrowed(concat!(
                env!("CARGO_PKG_VERSION_MAJOR"),
                ".",
                env!("CARGO_PKG_VERSION_MINOR"),
                ".",
                env!("CARGO_PKG_VERSION_PATCH")
            ))),
        ];

        for (name, value) in &self.system_config.identification {
            // Silently replace _ with - since it's easy to accidentally use _
            // in the config but _ is never used in these parameters.
            id_info.push(Some(Cow::Owned(name.replace('_', "-"))));
            id_info.push(Some(Cow::Owned(value.clone())));
        }

        send_response(sender, s::Response::Id(id_info)).await;
        success()
    }

    async fn cmd_namespace(&mut self, sender: &mut SendResponse) -> CmdResult {
        send_response(sender, s::Response::Namespace(())).await;
        success()
    }

    fn cmd_noop(&mut self, quip: &'static str) -> CmdResult {
        // Nothing to do here; shared command processing takes care of the
        // actual poll operation.
        Ok(s::Response::Cond(s::CondResponse {
            cond: s::RespCondType::Ok,
            code: None,
            quip: Some(Cow::Borrowed(quip)),
        }))
    }

    async fn cmd_log_out(&mut self, sender: &mut SendResponse) -> CmdResult {
        self.selected = None;
        self.account = None;

        // LOGOUT is a bit weird because RFC 3501 requires sending an OK
        // response *AFTER* the BYE.
        self.logged_out = true;
        send_event(
            sender,
            OutputEvent::ResponseLine {
                line: s::ResponseLine {
                    tag: None,
                    response: s::Response::Cond(s::CondResponse {
                        cond: s::RespCondType::Bye,
                        code: None,
                        quip: Some(Cow::Borrowed("BYE")),
                    }),
                },
                ctl: OutputControl::Buffer,
            },
        )
        .await;
        success()
    }

    fn cmd_start_tls(&mut self) -> CmdResult {
        Err(s::Response::Cond(s::CondResponse {
            cond: s::RespCondType::Bad,
            code: None,
            quip: Some(Cow::Borrowed("Already using TLS")),
        }))
    }

    #[cfg(not(feature = "dev-tools"))]
    fn cmd_xcry_zstd_train(&mut self) -> CmdResult {
        Err(s::Response::Cond(s::CondResponse {
            cond: s::RespCondType::No,
            code: None,
            quip: Some(Cow::Borrowed("dev-tools not enabled")),
        }))
    }

    #[cfg(feature = "dev-tools")]
    fn cmd_xcry_zstd_train(&mut self) -> CmdResult {
        use chrono::prelude::*;

        let data = account!(self)?
            .zstd_train(selected!(self)?)
            .map_err(map_error!(self))?;
        let data = base64::encode(&data);
        let mut wrapped_data = String::new();
        for chunk in data.as_bytes().chunks(72) {
            wrapped_data.push_str(std::str::from_utf8(chunk).unwrap());
            wrapped_data.push_str("\n");
        }

        let message = format!(
            "\
From: Crymap <crymap@localhost>
Date: {}
Subject: Zstd training data
Content-Type: multipart/mixed; boundary=bound
Message-ID: <{}.zstdtrain@localhost>
MIME-Version: 1.0

--bound
Content-Type: text/plain

Attached is the result of zstd training.

--bound
Content-Type: application/octet-stream
Content-Disposition: attachment; filename=\"zstddict.dat\"
Content-Transfer-Encoding: base64

{}
--bound--
",
            Utc::now().to_rfc2822(),
            Utc::now().to_rfc3339(),
            wrapped_data
        );

        account!(self)?
            .append(
                "INBOX",
                Utc::now().into(),
                vec![],
                message.replace('\n', "\r\n").as_bytes(),
            )
            .map_err(map_error!(self))?;

        success()
    }

    async fn full_poll(
        &mut self,
        sender: &mut SendResponse,
    ) -> Result<(), Error> {
        let Some(ref mut account) = self.account else {
            return Ok(());
        };

        account.drain_deliveries();

        let Some(ref mut selected) = self.selected.as_mut() else {
            return Ok(());
        };

        let poll = account.poll(selected)?;
        self.send_full_poll_responses(sender, poll).await;
        Ok(())
    }

    async fn send_full_poll_responses(
        &mut self,
        sender: &mut SendResponse,
        poll: PollResponse,
    ) {
        if self.qresync_enabled {
            if !poll.expunge.is_empty() {
                let mut sr = SeqRange::new();
                for (_, uid) in poll.expunge {
                    sr.append(uid);
                }
                send_response(
                    sender,
                    s::Response::Vanished(s::VanishedResponse {
                        earlier: false,
                        uids: Cow::Owned(sr.to_string()),
                    }),
                )
                .await;
            }
        } else {
            for (seqnum, _) in poll.expunge.into_iter().rev() {
                send_response(sender, s::Response::Expunge(seqnum.0.get()))
                    .await;
            }
        }
        if let Some(exists) = poll.exists {
            send_response(
                sender,
                s::Response::Exists(exists.try_into().unwrap_or(u32::MAX)),
            )
            .await;
        }
        if let Some(recent) = poll.recent {
            send_response(
                sender,
                s::Response::Recent(recent.try_into().unwrap_or(u32::MAX)),
            )
            .await;
        }

        self.fetch_for_background_update(sender, poll.fetch).await;

        // This must come after fetch_for_background_update so that we can
        // override the client's own calculation of HIGHESTMODSEQ
        if let Some(max_modseq) = poll.max_modseq {
            if self.condstore_enabled {
                send_response(
                    sender,
                    s::Response::Cond(s::CondResponse {
                        cond: s::RespCondType::Ok,
                        code: Some(s::RespTextCode::HighestModseq(
                            max_modseq.raw(),
                        )),
                        quip: None,
                    }),
                )
                .await;
            }
        }
    }

    async fn mini_poll(
        &mut self,
        sender: &mut SendResponse,
    ) -> Result<(), Error> {
        let Some(ref mut account) = self.account else {
            return Ok(());
        };

        let Some(ref mut selected) = self.selected else {
            return Ok(());
        };

        let poll = account.mini_poll(selected)?;
        let uids_empty = poll.fetch.is_empty();

        self.fetch_for_background_update(sender, poll.fetch).await;

        // If the true max modseq is not the same as the reported max modseq,
        // we need to also send a HIGHESTMODSEQ response (after the fetches
        // above) to override the client's own calculation of that value based
        // on looking at the FETCH responses, since the value from FETCH could
        // be greater than of an expungement the client hasn't seen.
        if !uids_empty && self.condstore_enabled {
            if let Some(divergent_modseq) = poll.divergent_modseq {
                send_response(
                    sender,
                    s::Response::Cond(s::CondResponse {
                        cond: s::RespCondType::Ok,
                        code: Some(s::RespTextCode::HighestModseq(
                            divergent_modseq.raw(),
                        )),
                        quip: Some(Cow::Borrowed(
                            "Snapshot diverged from reality",
                        )),
                    }),
                )
                .await;
            }
        }

        Ok(())
    }

    /// Performs preflight checks before idling.
    ///
    /// If this returns a response, IDLE is not currently possible. That
    /// response should be sent as the response to IDLE and the IDLE workflow
    /// must be aborted.
    ///
    /// If this returns no response, the `+ idling` continuation line should be
    /// sent, then `cmd_idle` invoked to perform idling.
    pub fn cmd_idle_preflight(
        &mut self,
        tag: &str,
    ) -> Option<s::ResponseLine<'static>> {
        if let Err(e) = account!(self) {
            return Some(maybe_tagged_response(Cow::Owned(tag.to_owned()), e));
        }

        if let Err(e) = selected!(self) {
            return Some(maybe_tagged_response(Cow::Owned(tag.to_owned()), e));
        }

        None
    }

    /// The IDLE command.
    ///
    /// This idles on the currently selected mailbox until `cancel` completes
    /// or an error occurs. Data is sent through `sender` as it becomes
    /// available.
    ///
    /// This is not cancel-safe if the connection is expected to continue being
    /// used. Dropping the future before it completes may result in updates to
    /// the mailbox state that have not been sent to the client.
    ///
    /// The returned response should be sent as a tagged response line.
    pub async fn cmd_idle(
        &mut self,
        tag: &str,
        mut sender: SendResponse,
        mut cancel: tokio::sync::oneshot::Receiver<()>,
    ) -> s::ResponseLine<'static> {
        let result = loop {
            let account = self
                .account
                .as_mut()
                .expect("account was validated by cmd_idle_preflight");
            let selected = self
                .selected
                .as_mut()
                .expect("selected was validated by cmd_idle_preflight");

            tokio::select! {
                _ = &mut cancel => break Ok(()),
                r = account.idle(selected) => match r {
                    Ok(poll) => {
                        self.send_full_poll_responses(&mut sender, poll).await;
                        send_event(&mut sender, OutputEvent::Flush).await;
                    },

                    Err(e) => break Err(e),
                },
            }
        };

        let result = result.map_err(map_error!(
            self,
            NxMailbox => (Bye, None),
            MailboxUnselectable => (Bye, None),
        ));
        let response = match result {
            Ok(()) => s::Response::Cond(s::CondResponse {
                cond: s::RespCondType::Ok,
                code: None,
                quip: None,
            }),
            Err(mut e) => {
                if let s::Response::Cond(s::CondResponse {
                    ref mut cond, ..
                }) = e
                {
                    // We aren't allowed to send a tagged NO response once
                    // we've sent the continuation line, so we need to commit
                    // to hanging up the connection instead.
                    *cond = s::RespCondType::Bye;
                }

                e
            },
        };

        maybe_tagged_response(Cow::Owned(tag.to_owned()), response)
    }
}

pub(super) fn capability_data() -> s::CapabilityData<'static> {
    s::CapabilityData {
        capabilities: CAPABILITIES.iter().copied().map(Cow::Borrowed).collect(),
    }
}

fn maybe_tagged_response(
    tag: Cow<'_, str>,
    res: s::Response<'static>,
) -> s::ResponseLine<'static> {
    if matches!(
        res,
        s::Response::Cond(s::CondResponse {
            cond: s::RespCondType::Bye,
            ..
        })
    ) {
        // BYE is never tagged
        s::ResponseLine {
            tag: None,
            response: res,
        }
    } else {
        s::ResponseLine {
            tag: Some(Cow::Owned(tag.into_owned())),
            response: res,
        }
    }
}