crymap 1.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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//-
// Copyright (c) 2020, 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::convert::TryInto;
use std::fs;
use std::io::{self, BufRead, Read, Seek, Write};
use std::path::Path;

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use chrono::prelude::*;
use log::info;
use rand::{rngs::OsRng, Rng};
use tempfile::{NamedTempFile, TempPath};

use super::defs::*;
use crate::account::model::*;
use crate::crypt::data_stream;
use crate::support::compression::{Compression, FinishWrite};
use crate::support::error::Error;
use crate::support::file_ops;

#[derive(Debug)]
pub struct BufferedMessage(TempPath);

impl StatelessMailbox {
    /// Open the identified message for reading.
    ///
    /// This doesn't correspond to any particular IMAP command (that would be
    /// too easy!) but is used to implement a number of them.
    ///
    /// On success, returns the length in bytes, the internal date, and a
    /// reader to access the content.
    pub fn open_message<'a>(
        &'a self,
        uid: Uid,
    ) -> Result<(MessageMetadata, Box<dyn BufRead + 'a>), Error> {
        let scheme = self.message_scheme();
        let mut file = match fs::File::open(
            scheme.access_path_for_id(uid.0.get()).assume_exists(),
        ) {
            Ok(f) => f,
            Err(e)
                if Some(nix::libc::ELOOP) == e.raw_os_error()
                    || io::ErrorKind::NotFound == e.kind() =>
            {
                return Err(Error::ExpungedMessage)
            }
            Err(e) => return Err(e.into()),
        };

        let size_xor = file.read_u32::<LittleEndian>()?;
        let stream = data_stream::Reader::new(file, |k| {
            let mut ks = self.key_store.lock().unwrap();
            ks.get_private_key(k)
        })?;
        let compression = stream.metadata.compression;
        let mut stream = compression.decompressor(stream)?;
        let metadata_length = stream.read_u16::<LittleEndian>()?;
        let mut metadata: MessageMetadata = serde_cbor::from_reader(
            stream.by_ref().take(metadata_length.into()),
        )?;
        metadata.size ^= size_xor;

        Ok((metadata, stream))
    }

    /// Append the message(s) from the request to the mailbox.
    ///
    /// This corresponds to the `APPEND` command from RFC 3501, the
    /// `MULTIAPPEND` extension from RFC 3502, and the `APPENDUID` response
    /// from RFC 4315.
    ///
    /// This does not handle the special case of 0-length inputs cancelling the
    /// request. That must be handled at the protocol level.
    pub fn multiappend(
        &self,
        request: AppendRequest,
    ) -> Result<AppendResponse, Error> {
        let mut response = AppendResponse {
            uid_validity: self.uid_validity()?,
            uids: SeqRange::new(),
        };

        let message_count = request.items.len() as u32;
        let base_uid = self.append_buffered(request.items)?;
        response.uids.insert(
            base_uid,
            Uid::of(base_uid.0.get() + message_count - 1).unwrap(),
        );

        Ok(response)
    }

    /// Append the given message to this mailbox.
    ///
    /// Returns the UID of the new message.
    ///
    /// This is not exactly the RFC 3501 `APPEND` command; see `multiappend`
    /// for that.
    pub fn append(
        &self,
        internal_date: DateTime<FixedOffset>,
        flags: impl IntoIterator<Item = Flag>,
        data: impl Read,
    ) -> Result<Uid, Error> {
        let buffer_file = self.buffer_message(internal_date, data)?;
        self.append_buffered(vec![AppendItem {
            buffer_file,
            flags: flags.into_iter().collect(),
        }])
    }

    /// Append a message which was buffered with `buffer_message` to this
    /// mailbox.
    ///
    /// Returns the UID of the first new message. If there was more than one
    /// message appended, later messages have successive UIDs.
    pub fn append_buffered(
        &self,
        items: Vec<AppendItem>,
    ) -> Result<Uid, Error> {
        let paths = items
            .iter()
            .map(|item| item.buffer_file.0.as_ref())
            .collect::<Vec<_>>();
        let uid = self.insert_messages(&paths)?;
        self.propagate_flags_best_effort(
            items
                .into_iter()
                .enumerate()
                .map(|(ix, item)| {
                    (Uid::of(uid.0.get() + ix as u32).unwrap(), item.flags)
                })
                .collect::<Vec<_>>(),
        );
        Ok(uid)
    }

    /// Buffer the given data stream into a file that can later be appended
    /// directly.
    ///
    /// This is used when reading `APPEND` commands to directly transfer the
    /// network input into the final file, instead of going through the extra
    /// time and memory use of the `crate::support::buffer` system.
    ///
    /// The returned object is a reference to a file in the temporary directory
    /// which will be deleted when dropped, but does not contain an actual file
    /// handle.
    pub fn buffer_message(
        &self,
        internal_date: DateTime<FixedOffset>,
        mut data: impl Read,
    ) -> Result<BufferedMessage, Error> {
        self.not_read_only()?;

        let mut buffer_file = NamedTempFile::new_in(&self.common_paths.tmp)?;

        let size_xor: u32;
        let metadata = MessageMetadata {
            size: OsRng.gen(),
            internal_date,
            email_id: OsRng.gen(),
        };
        let compression = Compression::DEFAULT_FOR_MESSAGE;

        buffer_file.write_u32::<LittleEndian>(0)?;
        {
            let mut crypt_writer = {
                let mut ks = self.key_store.lock().unwrap();
                let (key_name, pub_key) = ks.get_default_public_key()?;

                data_stream::Writer::new(
                    &mut buffer_file,
                    pub_key,
                    key_name.to_owned(),
                    compression,
                )?
            };
            {
                let mut compressor =
                    compression.compressor(&mut crypt_writer)?;
                let metadata_bytes = serde_cbor::to_vec(&metadata)?;
                compressor.write_u16::<LittleEndian>(
                    metadata_bytes.len().try_into().unwrap(),
                )?;
                compressor.write_all(&metadata_bytes)?;

                let size = io::copy(&mut data, &mut compressor)?;
                size_xor = metadata.size ^ size.try_into().unwrap_or(u32::MAX);
                compressor.finish()?;
            }
            crypt_writer.flush()?;
        }

        buffer_file.seek(io::SeekFrom::Start(0))?;
        buffer_file.write_u32::<LittleEndian>(size_xor)?;
        file_ops::chmod(buffer_file.path(), 0o440)?;
        buffer_file.as_file_mut().sync_all()?;
        Ok(BufferedMessage(buffer_file.into_temp_path()))
    }

    /// Insert `src` into this mailbox via a hard link.
    ///
    /// This is used for `COPY` and `MOVE`, though it is not exactly either of
    /// those.
    ///
    /// If `src` is more than 1 element long, the return value gives the UID of
    /// the first message, and subsequent messages have subsequent UIDs.
    fn insert_messages(&self, src: &[&Path]) -> Result<Uid, Error> {
        self.not_read_only()?;

        let scheme = self.message_scheme();

        if 1 == src.len() {
            for _ in 0..1000 {
                let uid = Uid::of(scheme.first_unallocated_id())
                    .ok_or(Error::MailboxFull)?;
                if scheme.emplace(src[0], uid.0.get())? {
                    info!(
                        "{} Delivered message to {}",
                        self.log_prefix,
                        uid.0.get()
                    );
                    self.notify_all_best_effort();
                    return Ok(uid);
                }

                // We could have failed because `src` is invalid.
                match fs::metadata(src[0]) {
                    Ok(_) => (),
                    Err(e)
                        if Some(nix::libc::ELOOP) == e.raw_os_error()
                            || io::ErrorKind::NotFound == e.kind() =>
                    {
                        return Err(Error::ExpungedMessage);
                    }
                    Err(e) => return Err(e.into()),
                }
            }

            Err(Error::GaveUpInsertion)
        } else {
            let base_id = scheme.emplace_many(
                src,
                &self.common_paths.tmp,
                Uid::MAX.0.get(),
            )?;
            info!(
                "{} Delivered messages to {}..={}",
                self.log_prefix,
                base_id,
                base_id + (src.len() - 1) as u32
            );
            self.notify_all_best_effort();
            Ok(Uid::of(base_id).unwrap())
        }
    }
}

impl StatefulMailbox {
    /// The RFC 3501 `COPY` command.
    pub fn seqnum_copy(
        &mut self,
        request: &CopyRequest<Seqnum>,
        dst: &StatelessMailbox,
    ) -> Result<CopyResponse, Error> {
        self.copy(
            &CopyRequest {
                ids: self.state.seqnum_range_to_uid(&request.ids, false)?,
            },
            dst,
        )
    }

    /// The RFC 3501 `UID COPY` command.
    pub fn copy(
        &mut self,
        request: &CopyRequest<Uid>,
        dst: &StatelessMailbox,
    ) -> Result<CopyResponse, Error> {
        let mut response = CopyResponse {
            uid_validity: dst.uid_validity()?,
            from_uids: SeqRange::new(),
            to_uids: SeqRange::new(),
        };

        let mut path_bufs = Vec::new();
        let mut flags = Vec::new();
        for uid in request.ids.items(self.state.max_uid_val()) {
            let status = match self.state.message_status(uid) {
                Some(status) => status,
                // RFC 3501 requires that non-existent UIDs are silently
                // ignored.
                None => continue,
            };

            response.from_uids.append(uid);
            flags.push(
                status
                    .flags()
                    .filter_map(|id| self.state.flag(id).cloned())
                    .collect::<Vec<_>>(),
            );
            path_bufs.push(
                self.s
                    .message_scheme()
                    .access_path_for_id(uid.0.get())
                    .assume_exists(),
            );
        }

        if path_bufs.is_empty() {
            return Ok(response);
        }

        let paths = path_bufs.iter().map(|p| p as &Path).collect::<Vec<_>>();
        let base_uid = dst.insert_messages(&paths)?;
        let message_count = paths.len() as u32;
        dst.propagate_flags_best_effort(
            flags
                .into_iter()
                .enumerate()
                .map(|(ix, f)| {
                    (Uid::of(base_uid.0.get() + ix as u32).unwrap(), f)
                })
                .collect(),
        );

        response.to_uids.insert(
            base_uid,
            Uid::of(base_uid.0.get() + message_count - 1).unwrap(),
        );
        Ok(response)
    }

    /// The RFC 6851 MOVE command.
    pub fn seqnum_moove(
        &mut self,
        request: &CopyRequest<Seqnum>,
        dst: &StatelessMailbox,
    ) -> Result<CopyResponse, Error> {
        self.moove(
            &CopyRequest {
                ids: self.state.seqnum_range_to_uid(&request.ids, false)?,
            },
            dst,
        )
    }

    /// The RFC 6851 UID MOVE command.
    pub fn moove(
        &mut self,
        request: &CopyRequest<Uid>,
        dst: &StatelessMailbox,
    ) -> Result<CopyResponse, Error> {
        // This is a simple COPY + VANQUISH. This does lead to a non-atomic
        // state where the messages were copied to dst but not expunged, but
        // this is permissible under RFC 6851 as a SHOULD NOT, and is only the
        // final state in extremely unusual circumstances.
        let response = self.copy(request, dst)?;
        self.vanquish(&request.ids)?;
        Ok(response)
    }
}

#[cfg(test)]
mod test {
    use std::iter;
    use std::sync::Arc;

    use chrono::prelude::*;

    use super::super::test_prelude::*;
    use super::*;
    use crate::account::mailbox_path::MailboxPath;

    fn destination(setup: &Setup) -> StatelessMailbox {
        let mbox2_path = MailboxPath::root(
            "archive".to_owned(),
            setup.root.path(),
            setup.root.path(),
        )
        .unwrap();
        mbox2_path.create(setup.root.path(), None).unwrap();
        StatelessMailbox::new(
            "mailbox".to_owned(),
            mbox2_path,
            false,
            Arc::clone(&setup.key_store),
            Arc::clone(&setup.common_paths),
        )
        .unwrap()
    }

    #[test]
    fn write_and_read_messages() {
        let setup = set_up();

        let zone = FixedOffset::east(3600);
        let now = zone.from_utc_datetime(&Utc::now().naive_local());

        assert_eq!(
            Uid::u(1),
            setup
                .stateless
                .append(now, iter::empty(), &mut "hello world".as_bytes())
                .unwrap()
        );
        assert_eq!(
            Uid::u(2),
            setup
                .stateless
                .append(now, iter::empty(), &mut "another message".as_bytes())
                .unwrap()
        );

        let mut content = String::new();
        let (md, mut r) = setup.stateless.open_message(Uid::u(1)).unwrap();
        assert_eq!(11, md.size);
        assert_eq!(now, md.internal_date);
        r.read_to_string(&mut content).unwrap();
        assert_eq!("hello world", &content);

        content.clear();
        let (md, mut r) = setup.stateless.open_message(Uid::u(2)).unwrap();
        assert_eq!(15, md.size);
        assert_eq!(now, md.internal_date);
        r.read_to_string(&mut content).unwrap();
        assert_eq!("another message", &content);
    }

    #[test]
    fn copy_into_self() {
        let setup = set_up();

        let (mut mb1, _) = setup.stateless.clone().select().unwrap();
        let (mut mb2, _) = setup.stateless.clone().select().unwrap();

        let uid1 = simple_append(mb1.stateless());
        let uid2 = simple_append(mb1.stateless());
        mb1.stateless()
            .set_flags_blind(vec![
                (uid1, vec![(true, Flag::Answered)]),
                (uid2, vec![(true, Flag::Draft)]),
            ])
            .unwrap();
        mb1.poll().unwrap();
        mb2.poll().unwrap();

        let uids3 = mb1
            .copy(
                &CopyRequest {
                    ids: SeqRange::just(uid1),
                },
                mb2.stateless(),
            )
            .unwrap()
            .to_uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(1, uids3.len());

        let poll = mb1.poll().unwrap();
        assert_eq!(Some(3), poll.exists);
        assert_eq!(0, poll.expunge.len());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(3), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb1.state.test_flag_o(&Flag::Answered, uids3[0]));
        assert!(!mb1.state.test_flag_o(&Flag::Draft, uids3[0]));
        assert!(mb2.state.test_flag_o(&Flag::Answered, uids3[0]));
        assert!(!mb2.state.test_flag_o(&Flag::Draft, uids3[0]));

        let uids4 = mb1
            .copy(
                &CopyRequest {
                    ids: SeqRange::range(uid1, uid2),
                },
                mb2.stateless(),
            )
            .unwrap()
            .to_uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(2, uids4.len());

        let poll = mb1.poll().unwrap();
        assert_eq!(Some(5), poll.exists);
        assert_eq!(0, poll.expunge.len());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(5), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb1.state.test_flag_o(&Flag::Answered, uids4[0]));
        assert!(!mb1.state.test_flag_o(&Flag::Draft, uids4[0]));
        assert!(mb2.state.test_flag_o(&Flag::Answered, uids4[0]));
        assert!(!mb2.state.test_flag_o(&Flag::Draft, uids4[0]));

        assert!(!mb1.state.test_flag_o(&Flag::Answered, uids4[1]));
        assert!(mb1.state.test_flag_o(&Flag::Draft, uids4[1]));
        assert!(!mb2.state.test_flag_o(&Flag::Answered, uids4[1]));
        assert!(mb2.state.test_flag_o(&Flag::Draft, uids4[1]));
    }

    #[test]
    fn copy_into_other() {
        let setup = set_up();

        let (mut mb1, _) = setup.stateless.clone().select().unwrap();

        let stateless2 = destination(&setup);
        let (mut mb2, _) = stateless2.select().unwrap();

        let uid1 = simple_append(mb1.stateless());
        let uid2 = simple_append(mb1.stateless());
        mb1.stateless()
            .set_flags_blind(vec![
                (uid1, vec![(true, Flag::Answered)]),
                (uid2, vec![(true, Flag::Draft)]),
            ])
            .unwrap();
        mb1.poll().unwrap();

        simple_append(mb2.stateless());
        mb2.poll().unwrap();

        let uids3 = mb1
            .copy(
                &CopyRequest {
                    ids: SeqRange::just(uid1),
                },
                mb2.stateless(),
            )
            .unwrap()
            .to_uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(1, uids3.len());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(2), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb2.state.test_flag_o(&Flag::Answered, uids3[0]));
        assert!(!mb2.state.test_flag_o(&Flag::Draft, uids3[0]));

        let uids4 = mb1
            .copy(
                &CopyRequest {
                    ids: SeqRange::range(uid1, uid2),
                },
                mb2.stateless(),
            )
            .unwrap()
            .to_uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(2, uids4.len());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(4), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb2.state.test_flag_o(&Flag::Answered, uids4[0]));
        assert!(!mb2.state.test_flag_o(&Flag::Draft, uids4[0]));

        assert!(!mb2.state.test_flag_o(&Flag::Answered, uids4[1]));
        assert!(mb2.state.test_flag_o(&Flag::Draft, uids4[1]));
    }

    #[test]
    fn bulk_copy_into_empty_other() {
        let setup = set_up();

        let (mut mb1, _) = setup.stateless.clone().select().unwrap();

        let stateless2 = destination(&setup);
        let (mut mb2, _) = stateless2.select().unwrap();

        let uid1 = simple_append(mb1.stateless());
        let uid2 = simple_append(mb1.stateless());
        mb1.stateless()
            .set_flags_blind(vec![
                (uid1, vec![(true, Flag::Answered)]),
                (uid2, vec![(true, Flag::Draft)]),
            ])
            .unwrap();
        mb1.poll().unwrap();

        let uids3 = mb1
            .copy(
                &CopyRequest {
                    ids: SeqRange::range(uid1, uid2),
                },
                mb2.stateless(),
            )
            .unwrap()
            .to_uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(2, uids3.len());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(2), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb2.state.test_flag_o(&Flag::Answered, uids3[0]));
        assert!(!mb2.state.test_flag_o(&Flag::Draft, uids3[0]));

        assert!(!mb2.state.test_flag_o(&Flag::Answered, uids3[1]));
        assert!(mb2.state.test_flag_o(&Flag::Draft, uids3[1]));
    }

    #[test]
    fn copy_expunged() {
        let setup = set_up();

        let (mut mb1, _) = setup.stateless.clone().select().unwrap();
        let (mut mb2, _) = setup.stateless.clone().select().unwrap();

        let uid1 = simple_append(mb1.stateless());
        let uid2 = simple_append(mb1.stateless());
        mb1.poll().unwrap();
        mb2.poll().unwrap();
        mb2.vanquish(&SeqRange::range(uid1, uid2)).unwrap();
        mb2.purge_all();

        assert_matches!(
            Err(Error::ExpungedMessage),
            mb1.copy(
                &CopyRequest {
                    ids: SeqRange::just(uid1),
                },
                &setup.stateless
            )
        );
        assert_matches!(
            Err(Error::ExpungedMessage),
            mb1.copy(
                &CopyRequest {
                    ids: SeqRange::range(uid1, uid2),
                },
                &setup.stateless
            )
        );
    }

    #[test]
    fn moove_into_other() {
        let setup = set_up();
        let (mut mb1, _) = setup.stateless.clone().select().unwrap();
        let stateless2 = destination(&setup);
        let (mut mb2, _) = stateless2.clone().select().unwrap();

        let _uid1 = simple_append(mb1.stateless());
        let uid2 = simple_append(mb1.stateless());
        let uid3 = simple_append(mb1.stateless());
        mb1.poll().unwrap();

        let response = mb1
            .moove(
                &CopyRequest {
                    ids: SeqRange::just(uid2),
                },
                &stateless2,
            )
            .unwrap();

        assert_eq!(1, response.from_uids.len());
        assert_eq!(1, response.to_uids.len());
        assert_eq!(uid2, response.from_uids.items(u32::MAX).next().unwrap());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(1), poll.exists);
        assert_eq!(
            vec![response.to_uids.items(u32::MAX).next().unwrap()],
            poll.fetch
        );

        let poll = mb1.poll().unwrap();
        assert_eq!(vec![(Seqnum::u(2), uid2)], poll.expunge);

        let response = mb1
            .seqnum_moove(
                &CopyRequest {
                    ids: SeqRange::just(Seqnum::u(2)),
                },
                &stateless2,
            )
            .unwrap();

        assert_eq!(1, response.from_uids.len());
        assert_eq!(1, response.to_uids.len());
        assert_eq!(uid3, response.from_uids.items(u32::MAX).next().unwrap());

        let poll = mb2.poll().unwrap();
        assert_eq!(Some(2), poll.exists);
        assert_eq!(
            vec![response.to_uids.items(u32::MAX).next().unwrap()],
            poll.fetch
        );

        let poll = mb1.poll().unwrap();
        assert_eq!(vec![(Seqnum::u(2), uid3)], poll.expunge);
    }

    #[test]
    fn moove_nx() {
        let setup = set_up();
        let (mut mb1, _) = setup.stateless.clone().select().unwrap();
        let stateless2 = destination(&setup);

        let uid1 = simple_append(mb1.stateless());
        let uid2 = simple_append(mb1.stateless());
        let uid3 = simple_append(mb1.stateless());
        mb1.poll().unwrap();

        mb1.vanquish(&SeqRange::just(uid2)).unwrap();
        mb1.poll().unwrap();

        let response = mb1
            .moove(
                &CopyRequest {
                    ids: SeqRange::range(uid1, uid3),
                },
                &stateless2,
            )
            .unwrap();

        assert_eq!(2, response.from_uids.len());
        assert_eq!(2, response.to_uids.len());
    }

    #[test]
    fn test_multiappend() {
        let setup = set_up();
        let (mut mb1, _) = setup.stateless.select().unwrap();

        let internal_date =
            FixedOffset::east(0).from_utc_datetime(&Utc::now().naive_local());
        let mut append_request = AppendRequest::default();
        append_request.items.push(AppendItem {
            buffer_file: mb1
                .stateless()
                .buffer_message(internal_date, b"foo" as &[u8])
                .unwrap(),
            flags: vec![Flag::Answered],
        });
        append_request.items.push(AppendItem {
            buffer_file: mb1
                .stateless()
                .buffer_message(internal_date, b"bar" as &[u8])
                .unwrap(),
            flags: vec![Flag::Draft],
        });

        let uids = mb1
            .stateless()
            .multiappend(append_request)
            .unwrap()
            .uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(2, uids.len());

        let poll = mb1.poll().unwrap();
        assert_eq!(Some(2), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb1.state.test_flag_o(&Flag::Answered, uids[0]));
        assert!(!mb1.state.test_flag_o(&Flag::Answered, uids[1]));
        assert!(!mb1.state.test_flag_o(&Flag::Draft, uids[0]));
        assert!(mb1.state.test_flag_o(&Flag::Draft, uids[1]));

        let mut append_request = AppendRequest::default();
        append_request.items.push(AppendItem {
            buffer_file: mb1
                .stateless()
                .buffer_message(internal_date, b"xyzzy" as &[u8])
                .unwrap(),
            flags: vec![Flag::Deleted],
        });
        append_request.items.push(AppendItem {
            buffer_file: mb1
                .stateless()
                .buffer_message(internal_date, b"plugh" as &[u8])
                .unwrap(),
            flags: vec![Flag::Seen],
        });

        let uids2 = mb1
            .stateless()
            .multiappend(append_request)
            .unwrap()
            .uids
            .items(u32::MAX)
            .collect::<Vec<_>>();
        assert_eq!(2, uids2.len());

        let poll = mb1.poll().unwrap();
        assert_eq!(Some(4), poll.exists);
        assert_eq!(0, poll.expunge.len());

        assert!(mb1.state.test_flag_o(&Flag::Deleted, uids2[0]));
        assert!(!mb1.state.test_flag_o(&Flag::Deleted, uids2[1]));
        assert!(!mb1.state.test_flag_o(&Flag::Seen, uids2[0]));
        assert!(mb1.state.test_flag_o(&Flag::Seen, uids2[1]));
    }
}