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
//! # vomit-sync
//!
//! `vomit-sync` aims to provide full two-way synchronization between IMAP and
//! a local maildir. Currently, only IMAP to maildir (i.e. one-way) is
//! implemented.
//!
//! It uses the [log][1] crate for logging, so you can receive logs from it by
//! using any of the compatible logging libraries.
//!
//! [1]: https://crates.io/crates/log
//!
//! [vsync][2] is small CLI wrapper around `vomit-sync`.
//!
//! [2]: https://git.sr.ht/~bitfehler/vomit-sync/tree/master/item/cli/
//!
//! As the name implies, `vomit-sync` is part of the [vomit project][3].
//!
//! [3]: https://sr.ht/~bitfehler/vomit

use std::collections::BTreeSet;
use std::io;
use std::iter::Iterator;
use std::path::PathBuf;
use std::thread;
use std::time::Instant;

use imap;
use log::{debug, error, info, trace, warn};
use maildir::Maildir;
use spmc;
use thiserror::Error;
use url::Url;

mod seqset;
mod state;

use seqset::SeqSet;

#[derive(Error, Debug)]
pub enum SyncError {
    #[error("IMAP error: {0}")]
    ProtocolError(#[from] imap::Error),
    #[error("failed to parse remote URL: {0}")]
    URLError(#[from] url::ParseError),
    #[error("invalid configuration: {0}")]
    ConfigError(&'static str),
    #[error("failed to load state: {0}")]
    StateError(#[from] state::StateError),
    #[error("IPC error: {0}")]
    IPCError(#[from] spmc::SendError<std::string::String>),
    #[error("error accessing maildir: {0}")]
    IOError(#[from] io::Error),
    #[error("error managing maildir: {0}")]
    MaildirError(#[from] maildir::MaildirError),
    #[error("error: {0}")]
    Error(&'static str),
    #[error("error: {0}")]
    E(String),
}

/// A set of options to control the synchronization process
#[derive(Clone, Debug)]
pub struct SyncOptions {
    /// The local maildir to sync to
    pub local: String,
    /// The IMAPS URL to sync from
    pub remote: String,
    /// The user for IMAP authentication
    pub user: String,
    /// The password for IMAP authentication
    pub password: String,
    /// Force reconciliation of state cache with disk/server (slow)
    ///
    /// This happens automatically if a mismatch is detected, but can be
    /// forced by setting this to `true`.
    pub reconcile: bool,
    /// The number of threads to use
    ///
    /// Each thread will use it's own IMAP session, so this must not be greater
    /// than the number of concurrent user sessions allowed by the IMAP server.
    pub threads: u8,
}

macro_rules! measure {
    ( $m:expr, $x:expr ) => {{
        let start = Instant::now();
        let result = $x;
        let duration = start.elapsed();
        debug!("{} in {}ms", $m, duration.as_millis());
        result
    }};
}

fn new_session(
    opts: &SyncOptions,
) -> Result<imap::Session<impl std::io::Read + std::io::Write>, SyncError> {
    let rurl = Url::parse(&opts.remote)?;
    if rurl.scheme() != "imaps" {
        return Err(SyncError::ConfigError("only IMAPS is supported"));
    }
    let host = rurl.host_str().ok_or(SyncError::ConfigError(
        "remote URL does not have a host part",
    ))?;
    let port = rurl.port().unwrap_or_else(|| 993);

    debug!("Connecting to {}:{}", host, port);
    let client = imap::ClientBuilder::new(host, port).native_tls()?;

    debug!("Logging in as {}", &opts.user);
    let session = client.login(&opts.user, &opts.password).map_err(|e| e.0)?;

    Ok(session)
}

fn check_server_capabilities_(opts: &SyncOptions) -> Result<(), SyncError> {
    let mut session = new_session(opts)?;
    let caps = session.capabilities()?;
    for cap in caps.iter() {
        trace!("Server capability: {:?}", cap);
    }
    session.logout()?;
    if !caps.has_str("QRESYNC") {
        return Err(SyncError::E(format!(
            "Server does not support QRESYNC (RFC 7162)"
        )));
    }
    Ok(())
}

/// Check if the configured server supports the required IMAP capabilities
///
/// Currently, at least the QRESYNC capability is required ([RFC 7162][1]).
///
/// [1]: https://www.rfc-editor.org/rfc/rfc7162.html
pub fn check_server_capabilities(opts: &SyncOptions) -> Result<(), SyncError> {
    measure!(
        format!("Checked capabilities for {}", opts.remote),
        check_server_capabilities_(opts)
    )
}

fn sync_mailbox<T: io::Read + io::Write>(
    maildir: &str,
    mailbox: &str,
    session: &mut imap::Session<T>,
    reconcile: bool,
) -> Result<(), SyncError> {
    let localname = if mailbox == "INBOX" {
        format!(".")
    } else {
        format!(".{}", mailbox)
    };
    let mbpath: PathBuf = [maildir, &localname].iter().collect();

    let maildir = Maildir::from(mbpath);
    maildir.create_dirs()?;

    let mut state = state::SyncState::load(maildir.path().as_ref(), reconcile)?;

    let s = session.select(mailbox)?;

    if let Some(val) = s.uid_validity {
        if let Some(hms) = s.highest_mod_seq {
            if hms == state.last_seen.highest_mod_seq && val == state.last_seen.uid_validity {
                trace!("Nothing to do for {}", mailbox);
                return Ok(());
            }
            state.last_seen.highest_mod_seq = hms;
        } else {
            warn!("No higest_mod_seq for mailbox {}", mailbox);
        }
        if val != state.last_seen.uid_validity && !reconcile {
            warn!("UID validity change forces state reconciliation");
            state = state::SyncState::load(maildir.path().as_ref(), true)?;
            state.last_seen.uid_validity = val;
        }
    }

    let fetch = if state.is_empty() {
        trace!("Performing full fetch for {}", mailbox);
        session.uid_fetch("1:*", "(FLAGS UID BODY.PEEK[])")?
    } else {
        trace!("Performing refresh fetch for {}", mailbox);
        let f = session.uid_fetch("1:*", "(FLAGS UID)")?;

        let mut to_fetch = SeqSet::new();
        let mut all_remote_uids: BTreeSet<u32> = BTreeSet::new();
        let all_local_uids: BTreeSet<u32> = state.keys().cloned().collect();

        for mail in f.iter() {
            let uid = mail
                .uid
                .ok_or(SyncError::Error("Server did not send UID, giving up"))?;
            all_remote_uids.insert(uid);
            match state.get(&uid) {
                Some(id) => {
                    // Compare flags etc..
                    let mut flags = String::from("");
                    for f in mail.flags() {
                        flags = flags
                            + match f {
                                imap::types::Flag::Answered => "R", // Replied
                                imap::types::Flag::Deleted => "T",  // Trashed
                                imap::types::Flag::Draft => "D",
                                imap::types::Flag::Flagged => "F",
                                imap::types::Flag::Seen => "S",
                                _ => "",
                            };
                    }
                    if let Err(_) = maildir.set_flags(id, &flags) {
                        // Maybe the message is still in new?
                        if let Err(_) = maildir.move_new_to_cur_with_flags(id, &flags) {
                            return Err(SyncError::E(format!(
                                "Failed to set flags for {} - reconcile state?",
                                id
                            )));
                        }
                    }
                }
                None => {
                    to_fetch.insert(uid);
                }
            }
        }

        for uid in all_local_uids.difference(&all_remote_uids) {
            let local = state
                .get(uid)
                .ok_or(SyncError::Error("something's broken - reconcile state?"))?;
            maildir.delete(&local)?
        }

        session.uid_fetch(format!("{}", to_fetch), "(FLAGS UID BODY.PEEK[])")?
    };

    for mail in fetch.iter() {
        let body = mail
            .body()
            .ok_or(SyncError::Error("downloaded message without content"))?;
        let uid = mail
            .uid
            .ok_or(SyncError::Error("Server did not send UID, giving up"))?;

        if uid > state.last_seen.uid {
            state.last_seen.uid = uid;
        }
        let recent = (mail.flags().len() == 0) || (mail.flags()[0] == imap::types::Flag::Recent);
        if !recent {
            let mut flags = String::from("");
            for f in mail.flags() {
                flags = flags
                    + match f {
                        imap::types::Flag::Answered => "R", // Replied
                        imap::types::Flag::Deleted => "T",  // Trashed
                        imap::types::Flag::Draft => "D",
                        imap::types::Flag::Flagged => "F",
                        imap::types::Flag::Seen => "S",
                        _ => "",
                    };
            }
            match maildir.store_cur_with_flags(body, &flags) {
                Ok(newid) => {
                    state.insert(uid, newid);
                }
                Err(e) => {
                    eprintln!("error saving new message: {}", e);
                    state.save()?;
                    return Err(SyncError::MaildirError(e));
                }
            };
        } else {
            match maildir.store_new(body) {
                Ok(newid) => {
                    state.insert(uid, newid);
                }
                Err(e) => {
                    eprintln!("error saving new message: {}", e);
                    state.save()?;
                    return Err(SyncError::MaildirError(e));
                }
            };
        }
    }
    state.save()?;
    Ok(())
}

fn worker_thread(
    i: u8,
    opts: &SyncOptions,
    rx: spmc::Receiver<std::string::String>,
) -> Result<(), SyncError> {
    let mut imap_session = new_session(&opts)?;
    let _ = imap_session.run_command_and_read_response("ENABLE QRESYNC")?;
    while let Ok(n) = rx.recv() {
        trace!("Syncing {} in workder thread {}", n, i);
        measure!(
            format!("Synced {}", n),
            sync_mailbox(&opts.local, &n, &mut imap_session, opts.reconcile)?
        );
    }
    let _ = imap_session.logout()?;
    Ok(())
}

fn pull_(opts: &SyncOptions) -> Result<(), SyncError> {
    info!("Syncing from {}", opts.remote);

    let mut imap_session = new_session(opts)?;
    let _ = imap_session.run_command_and_read_response("ENABLE QRESYNC")?;

    let names = imap_session.list(None, Some("*"))?;

    let mut threads = Vec::new();
    let (mut tx, rx) = spmc::channel::<String>();

    info!(
        "Using {} threads to sync {} mailboxes",
        opts.threads,
        names.len()
    );
    for i in 1..opts.threads {
        let rx = rx.clone();
        let opts = (*opts).clone();

        let t = thread::spawn(move || {
            if let Err(e) = worker_thread(i, &opts, rx) {
                error!("Error in worker thread {}: {}", i, e);
                std::process::exit(1);
            };
        });
        threads.push(t);
    }

    for name in names.iter() {
        tx.send(String::from(name.name()))?;
    }
    drop(tx);

    while let Ok(n) = rx.recv() {
        trace!("Syncing {} in main thread", n);
        measure!(
            format!("Synced {}", n),
            sync_mailbox(&opts.local, &n, &mut imap_session, opts.reconcile)?
        );
    }

    _ = imap_session.logout();

    for t in threads {
        t.join().unwrap();
    }
    info!("Sync successful");
    Ok(())
}

/// Apply all changes from IMAP to the local maildir
///
/// This includes fetching new mail, deleting expunged mails, updating tags, etc.
pub fn pull(opts: &SyncOptions) -> Result<(), SyncError> {
    measure!(format!("Pulled from {}", opts.remote), pull_(opts))
}