Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function to allow writing old emails into the maildir #39

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 53 additions & 27 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -671,22 +671,16 @@ impl Maildir {
data: &[u8],
flags: &str,
) -> std::result::Result<String, MaildirError> {
self.store(
Subfolder::Cur,
data,
&format!(
"{}2,{}",
INFORMATIONAL_SUFFIX_SEPARATOR,
Self::normalize_flags(flags)
),
)
self.store(Subfolder::Cur, data, &Self::normalize_flags(flags))
}

// https://doc.dovecot.org/admin_manual/mailbox_formats/maildir/#maildir-filename-extensions
// The standard filename definition is: <base filename>:2,<flags>
fn store(
&self,
subfolder: Subfolder,
data: &[u8],
info: &str,
flags: &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
Expand All @@ -706,13 +700,14 @@ impl Maildir {
let mut tmppath = self.path.clone();
tmppath.push("tmp");

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

loop {
let ts = time::SystemTime::now().duration_since(time::UNIX_EPOCH)?;
let now = time::SystemTime::now();
ts = now.duration_since(time::UNIX_EPOCH)?;
secs = ts.as_secs();
nanos = ts.subsec_nanos();
counter = COUNTER.fetch_add(1, Ordering::SeqCst);
Expand All @@ -724,9 +719,21 @@ impl Maildir {
.create_new(true)
.open(&tmppath)
{
Ok(f) => {
file = f;
break;
Ok(file) => {
return self.store_with_unique_settings(
match subfolder {
Subfolder::New => "new",
Subfolder::Cur => "cur",
},
&counter,
&now.duration_since(time::UNIX_EPOCH)?,
&pid,
&hostname,
&tmppath.into(),
&file,
data,
if flags.len() == 0 { None } else { Some(flags) },
);
}
Err(err) => {
if err.kind() != ErrorKind::AlreadyExists {
Expand All @@ -736,8 +743,21 @@ impl Maildir {
}
}
}
}

/// At this point, `file` is our new file at `tmppath`.
pub fn store_with_unique_settings(
&self,
subfolder: &str,
sequence_number: &usize,
timestamp: &time::Duration,
pid: &u32,
hostname: &str,
tmp_file_path: &PathBuf,
mut tmp_file: &std::fs::File,
data: &[u8],
flags: Option<&str>,
) -> std::result::Result<String, MaildirError> {
/// At this point, `file` is our new file at `tmp_file_path`.
/// 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.
Expand All @@ -757,18 +777,15 @@ impl Maildir {

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

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

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

#[cfg(unix)]
let dev = meta.dev();
Expand All @@ -785,10 +802,19 @@ impl Maildir {
#[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));
let secs = timestamp.as_secs();
let nanos = timestamp.subsec_nanos();

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

let flags_str = match flags {
Some(flags) => format!("{}2,{}", INFORMATIONAL_SUFFIX_SEPARATOR, flags),
None => "".to_string(),
};
newpath.push(format!("{}{}", id, flags_str));

std::fs::rename(&tmppath, &newpath)?;
std::fs::rename(&tmp_file_path, &newpath)?;
unlink_guard.path_to_unlink.take();
Ok(id)
}
Expand Down
110 changes: 110 additions & 0 deletions tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::fs;
use std::os::unix::ffi::OsStrExt;
#[cfg(windows)]
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::time;

use mailparse::MailHeaderMap;
use percent_encoding::percent_decode;
Expand Down Expand Up @@ -333,6 +334,115 @@ fn check_store_new() {
});
}

#[test]
fn check_store_with_unique_settings() {
let tmp_dir = tempdir().expect("could not create temporary directory");
let mut tmp_file_path = tmp_dir.into_path();
tmp_file_path.push(format!(
"maildir-temp-file.{}",
time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.expect("Duration should work")
.as_secs()
));

let tmp_file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_file_path)
.expect("The temp file should create");

with_maildir_empty("maildir3", |maildir| {
maildir.create_dirs().unwrap();

assert_eq!(maildir.count_new(), 0);
let mut id = maildir.store_with_unique_settings(
"new",
&1,
&time::Duration::new(1721749101, 266173535),
&12345,
"mail-server.intranet",
&tmp_file_path,
&tmp_file,
TEST_MAIL_BODY,
None, // No flags
);

assert!(id.is_ok());
let message_id = id.as_mut().unwrap();
assert!(message_id.contains("1721749101.#1M266173535P12345V"));
// The Inode part is not checked
assert!(message_id.contains(".mail-server.intranet,S=900"));
assert_eq!(maildir.count_new(), 1);

let id = id.unwrap();
let msg = maildir.find(&id);
assert!(msg.is_some());

assert_eq!(
msg.unwrap().parsed().unwrap().get_body_raw().unwrap(),
b"Today is Boomtime, the 59th day of Discord in the YOLD 3183".as_ref()
);
});
}

#[test]
fn check_store_with_unique_settings_and_flags() {
let tmp_dir = tempdir().expect("could not create temporary directory");
let mut tmp_file_path = tmp_dir.into_path();
tmp_file_path.push(format!(
"maildir-temp-file.{}",
time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.expect("Duration should work")
.as_secs()
));

let tmp_file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_file_path)
.expect("The temp file should create");

with_maildir_empty("maildir4", |maildir| {
maildir.create_dirs().unwrap();

assert_eq!(maildir.count_new(), 0);
let mut id = maildir.store_with_unique_settings(
"cur",
&1,
&time::Duration::new(1721749101, 266173535),
&12345,
"mail-server.intranet",
&tmp_file_path,
&tmp_file,
TEST_MAIL_BODY,
// https://doc.dovecot.org/admin_manual/mailbox_formats/maildir/#usage-of-timestamps
Some("STln"),
);

assert!(id.is_ok());
let message_id = id.as_mut().unwrap();
assert!(message_id.contains("1721749101.#1M266173535P12345V"));
// The Inode part is not checked
assert!(message_id.contains(".mail-server.intranet,S=900"));
// Does not contain flags
assert!(!message_id.contains(":2,STln"));
assert_eq!(maildir.count_cur(), 1);

let id = id.unwrap();
let msg = maildir.find(&id);
assert!(&msg.is_some());
let mut final_message = msg.unwrap();
assert_eq!(final_message.flags(), "STln");

assert_eq!(
final_message.parsed().unwrap().get_body_raw().unwrap(),
b"Today is Boomtime, the 59th day of Discord in the YOLD 3183".as_ref()
);
});
}

#[test]
fn check_store_cur() {
with_maildir_empty("maildir2", |maildir| {
Expand Down