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
use chrono::{DateTime, FixedOffset};
use mailparsing::{Header, HeaderMap, HeaderParseResult, MailParsingError, MimePart};
use std::io::prelude::*;
use std::io::ErrorKind;
use std::ops::Deref;
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(windows)]
use std::os::windows::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{error, fmt, fs, time};

static COUNTER: AtomicUsize = AtomicUsize::new(0);

#[cfg(unix)]
const INFORMATIONAL_SUFFIX_SEPARATOR: &str = ":";
#[cfg(windows)]
const INFORMATIONAL_SUFFIX_SEPARATOR: &str = ";";

#[derive(Debug)]
pub enum MailEntryError {
    IOError(std::io::Error),
    ParseError(MailParsingError),
    DateError(&'static str),
    ChronoError(chrono::format::ParseError),
}

impl fmt::Display for MailEntryError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MailEntryError::IOError(ref err) => write!(f, "IO error: {err}"),
            MailEntryError::ParseError(ref err) => write!(f, "Parse error: {err}"),
            MailEntryError::DateError(ref msg) => write!(f, "Date error: {msg}"),
            MailEntryError::ChronoError(ref err) => write!(f, "Date error: {err:#}"),
        }
    }
}

impl error::Error for MailEntryError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match *self {
            MailEntryError::IOError(ref err) => Some(err),
            MailEntryError::ParseError(ref err) => Some(err),
            MailEntryError::DateError(_) => None,
            MailEntryError::ChronoError(ref err) => Some(err),
        }
    }
}

impl From<chrono::format::ParseError> for MailEntryError {
    fn from(err: chrono::format::ParseError) -> MailEntryError {
        MailEntryError::ChronoError(err)
    }
}

impl From<std::io::Error> for MailEntryError {
    fn from(err: std::io::Error) -> MailEntryError {
        MailEntryError::IOError(err)
    }
}

impl From<MailParsingError> for MailEntryError {
    fn from(err: MailParsingError) -> MailEntryError {
        MailEntryError::ParseError(err)
    }
}

impl From<&'static str> for MailEntryError {
    fn from(err: &'static str) -> MailEntryError {
        MailEntryError::DateError(err)
    }
}

enum MailData {
    None,
    #[cfg(not(feature = "mmap"))]
    Bytes(Vec<u8>),
    #[cfg(feature = "mmap")]
    File(memmap2::Mmap),
}

impl MailData {
    fn is_none(&self) -> bool {
        match self {
            MailData::None => true,
            _ => false,
        }
    }

    fn data(&self) -> Option<&[u8]> {
        match self {
            Self::None => None,
            #[cfg(not(feature = "mmap"))]
            MailData::Bytes(ref b) => Some(b),
            #[cfg(feature = "mmap")]
            MailData::File(ref m) => Some(m),
        }
    }
}

/// This struct represents a single email message inside
/// the maildir. Creation of the struct does not automatically
/// load the content of the email file into memory - however,
/// that may happen upon calling functions that require parsing
/// the email.
pub struct MailEntry {
    id: String,
    flags: String,
    path: PathBuf,
    data: MailData,
}

impl MailEntry {
    pub fn id(&self) -> &str {
        &self.id
    }

    fn read_data(&mut self) -> std::io::Result<()> {
        if self.data.is_none() {
            #[cfg(feature = "mmap")]
            {
                let f = fs::File::open(&self.path)?;
                let mmap = unsafe { memmap2::MmapOptions::new().map(&f)? };
                self.data = MailData::File(mmap);
            }

            #[cfg(not(feature = "mmap"))]
            {
                let mut f = fs::File::open(&self.path)?;
                let mut d = Vec::<u8>::new();
                f.read_to_end(&mut d)?;
                self.data = MailData::Bytes(d);
            }
        }
        Ok(())
    }

    pub fn parsed(&mut self) -> Result<MimePart, MailEntryError> {
        self.read_data()?;
        let bytes = self
            .data
            .data()
            .expect("read_data should have returned an Err!");

        MimePart::parse(bytes).map_err(MailEntryError::ParseError)
    }

    pub fn headers(&mut self) -> Result<HeaderMap, MailEntryError> {
        self.read_data()?;
        let bytes = self
            .data
            .data()
            .expect("read_data should have returned an Err!");

        let HeaderParseResult { headers, .. } =
            Header::parse_headers(bytes).map_err(MailEntryError::ParseError)?;

        Ok(headers)
    }

    pub fn received(&mut self) -> Result<DateTime<FixedOffset>, MailEntryError> {
        self.read_data()?;
        let headers = self.headers()?;
        let received = headers.get_first("Received");
        match received {
            Some(v) => v
                .get_raw_value()
                .rsplit(';')
                .nth(0)
                .ok_or_else(|| MailEntryError::DateError("Unable to split Received header"))
                .and_then(|ts| DateTime::parse_from_rfc2822(ts).map_err(MailEntryError::from)),
            None => Err("No Received header found")?,
        }
    }

    pub fn date(&mut self) -> Result<DateTime<FixedOffset>, MailEntryError> {
        self.read_data()?;
        let headers = self.headers()?;
        let date = headers.get_first("Date");
        match date {
            Some(ts) => ts.as_date().map_err(MailEntryError::from),
            None => Err("No Date header found")?,
        }
    }

    pub fn flags(&self) -> &str {
        &self.flags
    }

    pub fn is_draft(&self) -> bool {
        self.flags.contains('D')
    }

    pub fn is_flagged(&self) -> bool {
        self.flags.contains('F')
    }

    pub fn is_passed(&self) -> bool {
        self.flags.contains('P')
    }

    pub fn is_replied(&self) -> bool {
        self.flags.contains('R')
    }

    pub fn is_seen(&self) -> bool {
        self.flags.contains('S')
    }

    pub fn is_trashed(&self) -> bool {
        self.flags.contains('T')
    }

    pub fn path(&self) -> &PathBuf {
        &self.path
    }
}

enum Subfolder {
    New,
    Cur,
}

/// An iterator over the email messages in a particular
/// maildir subfolder (either `cur` or `new`). This iterator
/// produces a `std::io::Result<MailEntry>`, which can be an
/// `Err` if an error was encountered while trying to read
/// file system properties on a particular entry, or if an
/// invalid file was found in the maildir. Files starting with
/// a dot (.) character in the maildir folder are ignored.
pub struct MailEntries {
    path: PathBuf,
    subfolder: Subfolder,
    readdir: Option<fs::ReadDir>,
}

impl MailEntries {
    fn new(path: PathBuf, subfolder: Subfolder) -> MailEntries {
        MailEntries {
            path,
            subfolder,
            readdir: None,
        }
    }
}

impl Iterator for MailEntries {
    type Item = std::io::Result<MailEntry>;

    fn next(&mut self) -> Option<std::io::Result<MailEntry>> {
        if self.readdir.is_none() {
            let mut dir_path = self.path.clone();
            dir_path.push(match self.subfolder {
                Subfolder::New => "new",
                Subfolder::Cur => "cur",
            });
            self.readdir = match fs::read_dir(dir_path) {
                Err(_) => return None,
                Ok(v) => Some(v),
            };
        }

        loop {
            // we need to skip over files starting with a '.'
            let dir_entry = self.readdir.iter_mut().next().unwrap().next();
            let result = dir_entry.map(|e| {
                let entry = e?;
                let filename = String::from(entry.file_name().to_string_lossy().deref());
                if filename.starts_with('.') {
                    return Ok(None);
                }
                let (id, flags) = match self.subfolder {
                    Subfolder::New => (Some(filename.as_str()), Some("")),
                    Subfolder::Cur => {
                        let delim = format!("{}2,", INFORMATIONAL_SUFFIX_SEPARATOR);
                        let mut iter = filename.split(&delim);
                        (iter.next(), iter.next())
                    }
                };
                if id.is_none() || flags.is_none() {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "Non-maildir file found in maildir",
                    ));
                }
                Ok(Some(MailEntry {
                    id: String::from(id.unwrap()),
                    flags: String::from(flags.unwrap()),
                    path: entry.path(),
                    data: MailData::None,
                }))
            });
            return match result {
                None => None,
                Some(Err(e)) => Some(Err(e)),
                Some(Ok(None)) => continue,
                Some(Ok(Some(v))) => Some(Ok(v)),
            };
        }
    }
}

#[derive(Debug)]
pub enum MaildirError {
    Io(std::io::Error),
    Utf8(std::str::Utf8Error),
    Time(std::time::SystemTimeError),
}

impl fmt::Display for MaildirError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use MaildirError::*;

        match *self {
            Io(ref e) => write!(f, "IO Error: {}", e),
            Utf8(ref e) => write!(f, "UTF8 Encoding Error: {}", e),
            Time(ref e) => write!(f, "Time Error: {}", e),
        }
    }
}

impl error::Error for MaildirError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        use MaildirError::*;

        match *self {
            Io(ref e) => Some(e),
            Utf8(ref e) => Some(e),
            Time(ref e) => Some(e),
        }
    }
}

impl From<std::io::Error> for MaildirError {
    fn from(e: std::io::Error) -> MaildirError {
        MaildirError::Io(e)
    }
}
impl From<std::str::Utf8Error> for MaildirError {
    fn from(e: std::str::Utf8Error) -> MaildirError {
        MaildirError::Utf8(e)
    }
}
impl From<std::time::SystemTimeError> for MaildirError {
    fn from(e: std::time::SystemTimeError) -> MaildirError {
        MaildirError::Time(e)
    }
}

/// An iterator over the maildir subdirectories. This iterator
/// produces a `std::io::Result<Maildir>`, which can be an
/// `Err` if an error was encountered while trying to read
/// file system properties on a particular entry. Only
/// subdirectories starting with a single period are included.
pub struct MaildirEntries {
    path: PathBuf,
    readdir: Option<fs::ReadDir>,
}

impl MaildirEntries {
    fn new(path: PathBuf) -> MaildirEntries {
        MaildirEntries {
            path,
            readdir: None,
        }
    }
}

impl Iterator for MaildirEntries {
    type Item = std::io::Result<Maildir>;

    fn next(&mut self) -> Option<std::io::Result<Maildir>> {
        if self.readdir.is_none() {
            self.readdir = match fs::read_dir(&self.path) {
                Err(_) => return None,
                Ok(v) => Some(v),
            };
        }

        loop {
            let dir_entry = self.readdir.iter_mut().next().unwrap().next();
            let result = dir_entry.map(|e| {
                let entry = e?;

                // a dir name should start by one single period
                let filename = String::from(entry.file_name().to_string_lossy().deref());
                if !filename.starts_with('.') || filename.starts_with("..") {
                    return Ok(None);
                }

                // the entry should be a directory
                let is_dir = entry.metadata().map(|m| m.is_dir()).unwrap_or_default();
                if !is_dir {
                    return Ok(None);
                }

                Ok(Some(Maildir {
                    path: self.path.join(filename),
                }))
            });

            return match result {
                None => None,
                Some(Err(e)) => Some(Err(e)),
                Some(Ok(None)) => continue,
                Some(Ok(Some(v))) => Some(Ok(v)),
            };
        }
    }
}

/// The main entry point for this library. This struct can be
/// instantiated from a path using the `from` implementations.
/// The path passed in to the `from` should be the root of the
/// maildir (the folder containing `cur`, `new`, and `tmp`).
pub struct Maildir {
    path: PathBuf,
}

impl Maildir {
    /// Returns the path of the maildir base folder.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Returns the number of messages found inside the `new`
    /// maildir folder.
    pub fn count_new(&self) -> usize {
        self.list_new().count()
    }

    /// Returns the number of messages found inside the `cur`
    /// maildir folder.
    pub fn count_cur(&self) -> usize {
        self.list_cur().count()
    }

    /// Returns an iterator over the messages inside the `new`
    /// maildir folder. The order of messages in the iterator
    /// is not specified, and is not guaranteed to be stable
    /// over multiple invocations of this method.
    pub fn list_new(&self) -> MailEntries {
        MailEntries::new(self.path.clone(), Subfolder::New)
    }

    /// Returns an iterator over the messages inside the `cur`
    /// maildir folder. The order of messages in the iterator
    /// is not specified, and is not guaranteed to be stable
    /// over multiple invocations of this method.
    pub fn list_cur(&self) -> MailEntries {
        MailEntries::new(self.path.clone(), Subfolder::Cur)
    }

    /// Returns an iterator over the maildir subdirectories.
    /// The order of subdirectories in the iterator
    /// is not specified, and is not guaranteed to be stable
    /// over multiple invocations of this method.
    pub fn list_subdirs(&self) -> MaildirEntries {
        MaildirEntries::new(self.path.clone())
    }

    /// Moves a message from the `new` maildir folder to the
    /// `cur` maildir folder. The id passed in should be
    /// obtained from the iterator produced by `list_new`.
    pub fn move_new_to_cur(&self, id: &str) -> std::io::Result<()> {
        self.move_new_to_cur_with_flags(id, "")
    }

    /// Moves a message from the `new` maildir folder to the `cur` maildir folder, and sets the
    /// given flags. The id passed in should be obtained from the iterator produced by `list_new`.
    ///
    /// The possible flags are described e.g. at <https://cr.yp.to/proto/maildir.html> or
    /// <http://www.courier-mta.org/maildir.html>.
    pub fn move_new_to_cur_with_flags(&self, id: &str, flags: &str) -> std::io::Result<()> {
        let src = self.path.join("new").join(id);
        let dst = self.path.join("cur").join(format!(
            "{}{}2,{}",
            id,
            INFORMATIONAL_SUFFIX_SEPARATOR,
            Self::normalize_flags(flags)
        ));
        fs::rename(src, dst)
    }

    /// Copies a message from the current maildir to the targetted maildir.
    pub fn copy_to(&self, id: &str, target: &Maildir) -> std::io::Result<()> {
        let entry = self.find(id).ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotFound, "Mail entry not found")
        })?;
        let filename = entry.path().file_name().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid mail entry file name",
            )
        })?;

        let src_path = entry.path();
        let dst_path = target.path().join("cur").join(filename);
        if src_path == &dst_path {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "Target maildir needs to be different from the source",
            ));
        }

        fs::copy(src_path, dst_path)?;
        Ok(())
    }

    /// Moves a message from the current maildir to the targetted maildir.
    pub fn move_to(&self, id: &str, target: &Maildir) -> std::io::Result<()> {
        let entry = self.find(id).ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotFound, "Mail entry not found")
        })?;
        let filename = entry.path().file_name().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid mail entry file name",
            )
        })?;
        fs::rename(entry.path(), target.path().join("cur").join(filename))?;
        Ok(())
    }

    /// Tries to find the message with the given id in the
    /// maildir. This searches both the `new` and the `cur`
    /// folders.
    pub fn find(&self, id: &str) -> Option<MailEntry> {
        let filter = |entry: &std::io::Result<MailEntry>| match *entry {
            Err(_) => false,
            Ok(ref e) => e.id() == id,
        };

        self.list_new()
            .find(&filter)
            .or_else(|| self.list_cur().find(&filter))
            .map(|e| e.unwrap())
    }

    fn normalize_flags(flags: &str) -> String {
        let mut flag_chars = flags.chars().collect::<Vec<char>>();
        flag_chars.sort();
        flag_chars.dedup();
        flag_chars.into_iter().collect()
    }

    fn update_flags<F>(&self, id: &str, flag_op: F) -> std::io::Result<()>
    where
        F: Fn(&str) -> String,
    {
        let filter = |entry: &std::io::Result<MailEntry>| match *entry {
            Err(_) => false,
            Ok(ref e) => e.id() == id,
        };

        match self.list_cur().find(&filter).map(|e| e.unwrap()) {
            Some(m) => {
                let src = m.path();
                let mut dst = m.path().clone();
                dst.pop();
                dst.push(format!(
                    "{}{}2,{}",
                    m.id(),
                    INFORMATIONAL_SUFFIX_SEPARATOR,
                    flag_op(m.flags())
                ));
                fs::rename(src, dst)
            }
            None => Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "Mail entry not found",
            )),
        }
    }

    /// Updates the flags for the message with the given id in the
    /// maildir. This only searches the `cur` folder, because that's
    /// the folder where messages have flags. Returns an error if the
    /// message was not found. All existing flags are overwritten with
    /// the new flags provided.
    pub fn set_flags(&self, id: &str, flags: &str) -> std::io::Result<()> {
        self.update_flags(id, |_old_flags| Self::normalize_flags(flags))
    }

    /// Adds the given flags to the message with the given id in the maildir.
    /// This only searches the `cur` folder, because that's the folder where
    /// messages have flags. Returns an error if the message was not found.
    /// Flags are deduplicated, so setting a already-set flag has no effect.
    pub fn add_flags(&self, id: &str, flags: &str) -> std::io::Result<()> {
        let flag_merge = |old_flags: &str| {
            let merged = String::from(old_flags) + flags;
            Self::normalize_flags(&merged)
        };
        self.update_flags(id, &flag_merge)
    }

    /// Removes the given flags to the message with the given id in the maildir.
    /// This only searches the `cur` folder, because that's the folder where
    /// messages have flags. Returns an error if the message was not found.
    /// If the message doesn't have the flag(s) to be removed, those flags are
    /// ignored.
    pub fn remove_flags(&self, id: &str, flags: &str) -> std::io::Result<()> {
        let flag_strip =
            |old_flags: &str| old_flags.chars().filter(|c| !flags.contains(*c)).collect();
        self.update_flags(id, &flag_strip)
    }

    /// Deletes the message with the given id in the maildir.
    /// This searches both the `new` and the `cur` folders,
    /// and deletes the file from the filesystem. Returns an
    /// error if no message was found with the given id.
    pub fn delete(&self, id: &str) -> std::io::Result<()> {
        match self.find(id) {
            Some(m) => fs::remove_file(m.path()),
            None => Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "Mail entry not found",
            )),
        }
    }

    /// Creates all neccessary directories if they don't exist yet. It is the library user's
    /// responsibility to call this before using `store_new`.
    pub fn create_dirs(&self) -> std::io::Result<()> {
        let mut path = self.path.clone();
        for d in &["cur", "new", "tmp"] {
            path.push(d);
            fs::create_dir_all(path.as_path())?;
            path.pop();
        }
        Ok(())
    }

    /// Stores the given message data as a new message file in the Maildir `new` folder. Does not
    /// create the neccessary directories, so if in doubt call `create_dirs` before using
    /// `store_new`.
    /// Returns the Id of the inserted message on success.
    pub fn store_new(&self, data: &[u8]) -> std::result::Result<String, MaildirError> {
        self.store(Subfolder::New, data, "")
    }

    /// Stores the given message data as a new message file in the Maildir `cur` folder, adding the
    /// given `flags` to it. The possible flags are explained e.g. at
    /// <https://cr.yp.to/proto/maildir.html> or <http://www.courier-mta.org/maildir.html>.
    /// Returns the Id of the inserted message on success.
    pub fn store_cur_with_flags(
        &self,
        data: &[u8],
        flags: &str,
    ) -> std::result::Result<String, MaildirError> {
        self.store(
            Subfolder::Cur,
            data,
            &format!(
                "{}2,{}",
                INFORMATIONAL_SUFFIX_SEPARATOR,
                Self::normalize_flags(flags)
            ),
        )
    }

    fn store(
        &self,
        subfolder: Subfolder,
        data: &[u8],
        info: &str,
    ) -> std::result::Result<String, MaildirError> {
        // try to get some uniquenes, as described at http://cr.yp.to/proto/maildir.html
        // dovecot and courier IMAP use <timestamp>.M<usec>P<pid>.<hostname> for tmp-files and then
        // move to <timestamp>.M<usec>P<pid>V<dev>I<ino>.<hostname>,S=<size_in_bytes> when moving
        // to new dir. see for example http://www.courier-mta.org/maildir.html.
        let pid = std::process::id();
        let hostname = gethostname::gethostname()
            .into_string()
            // the hostname is always ASCII in order to be a valid DNS
            // name, so into_string() will always succeed. The error case
            // here is to satisfy the compiler which doesn't know this.
            .unwrap_or_else(|_| "localhost".to_string());

        // loop when conflicting filenames occur, as described at
        // http://www.courier-mta.org/maildir.html
        // this assumes that pid and hostname don't change.
        let mut tmppath = self.path.clone();
        tmppath.push("tmp");

        let mut file;
        let mut secs;
        let mut nanos;
        let mut counter;

        loop {
            let ts = time::SystemTime::now().duration_since(time::UNIX_EPOCH)?;
            secs = ts.as_secs();
            nanos = ts.subsec_nanos();
            counter = COUNTER.fetch_add(1, Ordering::SeqCst);

            tmppath.push(format!("{secs}.#{counter:x}M{nanos}P{pid}.{hostname}"));

            match std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&tmppath)
            {
                Ok(f) => {
                    file = f;
                    break;
                }
                Err(err) => {
                    if err.kind() != ErrorKind::AlreadyExists {
                        return Err(err.into());
                    }
                    tmppath.pop();
                }
            }
        }

        /// At this point, `file` is our new file at `tmppath`.
        /// If we leave the scope of this function prior to
        /// successfully writing the file to its final location,
        /// we need to ensure that we remove the temporary file.
        /// This struct takes care of that detail.
        struct UnlinkOnError {
            path_to_unlink: Option<PathBuf>,
        }

        impl Drop for UnlinkOnError {
            fn drop(&mut self) {
                if let Some(path) = self.path_to_unlink.take() {
                    // Best effort to remove it
                    std::fs::remove_file(path).ok();
                }
            }
        }

        // Ensure that we remove the temporary file on failure
        let mut unlink_guard = UnlinkOnError {
            path_to_unlink: Some(tmppath.clone()),
        };

        file.write_all(data)?;
        file.sync_all()?;

        let meta = file.metadata()?;
        let mut newpath = self.path.clone();
        newpath.push(match subfolder {
            Subfolder::New => "new",
            Subfolder::Cur => "cur",
        });

        #[cfg(unix)]
        let dev = meta.dev();
        #[cfg(windows)]
        let dev: u64 = 0;

        #[cfg(unix)]
        let ino = meta.ino();
        #[cfg(windows)]
        let ino: u64 = 0;

        #[cfg(unix)]
        let size = meta.size();
        #[cfg(windows)]
        let size = meta.file_size();

        let id = format!("{secs}.#{counter:x}M{nanos}P{pid}V{dev}I{ino}.{hostname},S={size}");
        newpath.push(format!("{}{}", id, info));

        std::fs::rename(&tmppath, &newpath)?;
        unlink_guard.path_to_unlink.take();
        Ok(id)
    }
}

impl From<PathBuf> for Maildir {
    fn from(p: PathBuf) -> Maildir {
        Maildir { path: p }
    }
}

impl From<String> for Maildir {
    fn from(s: String) -> Maildir {
        Maildir::from(PathBuf::from(s))
    }
}

impl<'a> From<&'a str> for Maildir {
    fn from(s: &str) -> Maildir {
        Maildir::from(PathBuf::from(s))
    }
}