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
//! # 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::fs;
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};
use maildir::Maildir;
use native_tls;
use spmc;
use thiserror::Error;
use wildmatch::WildMatch;

mod flags;
mod mailboxes;
mod seqset;
mod state;
mod sync;

use vomit::Mailbox;

#[derive(Error, Debug)]
pub enum SyncError {
    #[error("IMAP error: {0}")]
    ProtocolError(#[from] imap::Error),
    #[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<mailboxes::SyncJob>),
    #[error("error accessing maildir: {0}")]
    IOError(#[from] io::Error),
    #[error("error managing maildir: {0}")]
    MaildirError(#[from] maildir::MaildirError),
    #[error("{0}")]
    Error(&'static str),
    #[error("{0}")]
    E(String),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SyncDirection {
    Pull,
    Push,
    TwoWay,
}

/// 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,
    /// 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,
    /// Disable TLS certificate checks (e.g. for self-signed certs)
    pub unsafe_tls: bool,
    /// Only log with info level what actions (sync, create, delete) would be taken on
    /// which mailboxes (taking include/exclude into account), then exit.
    pub list_mailbox_actions: bool,
    /// A list of wildcard patterns to include only folders that match any of them.
    ///
    /// The wildcard pattern only supports `?` and `*` and must match the full mailbox name.
    pub include: Vec<String>,
    /// A list of wildcard patterns to exclude all folders that match any of them.
    ///
    /// The wildcard pattern only supports `?` and `*` and must match the full mailbox name.
    /// If used together with `include` and both match, `exclude` takes precedence.
    pub exclude: Vec<String>,
}

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 get_hierarchy_delimiter(names: &imap::types::Names) -> Result<String, SyncError> {
    let delims: BTreeSet<&str> = names.iter().filter_map(|name| name.delimiter()).collect();
    if delims.len() != 1 {
        return Err(SyncError::E(format!(
            "Expected exactly on hierarchy delimiter, found {:?}",
            delims
        )));
    }
    Ok(String::from(delims.into_iter().next().unwrap()))
}

fn new_session(
    opts: &SyncOptions,
) -> Result<imap::Session<impl std::io::Read + std::io::Write>, SyncError> {
    let (host, port) = match opts.remote.rsplit_once(':') {
        Some((host, port)) => (host, port),
        None => (opts.remote.as_str(), "993"),
    };

    let port = match u16::from_str_radix(port, 10) {
        Ok(p) => p,
        Err(e) => {
            error!("failed to parse remote port: {}", e);
            return Err(SyncError::ConfigError("invalid port"));
        }
    };

    debug!("Connecting to {}:{}", host, port);
    let client = if opts.unsafe_tls {
        imap::ClientBuilder::new(host, port).connect(|domain, tcp| {
            let ssl_conn = native_tls::TlsConnector::builder()
                .danger_accept_invalid_certs(true)
                .danger_accept_invalid_hostnames(true)
                .build()?;
            Ok(native_tls::TlsConnector::connect(&ssl_conn, domain, tcp).unwrap())
        })?
    } else {
        imap::ClientBuilder::new(host, port).native_tls()?
    };

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

    session.run_command_and_read_response("ENABLE QRESYNC")?;

    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)"
        )));
    }
    if !caps.has_str("UIDPLUS") {
        return Err(SyncError::E(format!(
            "Server does not support UIDPLUS (RFC 4315)"
        )));
    }
    Ok(())
}

pub fn list_mailboxes(opts: &SyncOptions) -> Result<(), SyncError> {
    let mut session = new_session(opts)?;
    let names = session.list(None, Some("*"))?;
    if names.len() == 0 {
        return Err(SyncError::Error("No remote mailboxes found"));
    }

    let delimiter = get_hierarchy_delimiter(&names)?;
    let remote_mailboxes = mailboxes::load_remote(&names);
    let local_mailboxes = mailboxes::load_local(&opts.local, &delimiter);

    info!("Hierarchy delimiter: {}", delimiter);
    info!("Remote mailboxes:");
    for m in &remote_mailboxes {
        info!("  {}", m);
    }
    info!("Local mailboxes:");
    for m in &local_mailboxes {
        info!("  {}", m);
    }
    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_root: &str,
    sync_job: &mailboxes::SyncJob,
    direction: &SyncDirection,
    session: &mut imap::Session<T>,
) -> Result<(), SyncError> {
    let mailbox = &sync_job.name;
    let dirname = Mailbox::virtual_to_dir(mailbox, &sync_job.delimiter);
    let mbpath: PathBuf = [maildir_root, &dirname].iter().collect();

    match sync_job.action {
        mailboxes::SyncAction::Sync => (),
        mailboxes::SyncAction::CreateLocal => {
            trace!("Creating local mailbox {}", mailbox);
            // Local dir creation will happen automatically
        }
        mailboxes::SyncAction::CreateRemote => {
            trace!("Creating remote mailbox {}", mailbox);
            session.create(mailbox)?
        }
        mailboxes::SyncAction::DeleteLocal => {
            trace!("Deleting local mailbox {}", mailbox);
            return fs::remove_dir_all(&mbpath).map_err(|e| SyncError::IOError(e));
        }
        mailboxes::SyncAction::DeleteRemote => {
            trace!("Deleting remote mailbox {}", mailbox);
            return session
                .delete(mailbox)
                .map_err(|e| SyncError::ProtocolError(e));
        }
    };

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

    let state = measure!(
        format!("Loaded state for {}", mailbox),
        state::SyncState::load(&maildir.path())?
    );

    let remote = session.select(mailbox)?;

    match direction {
        SyncDirection::Pull => sync::pull(session, &sync_job, maildir, remote, state),
        SyncDirection::Push => sync::push(session, &sync_job, maildir, remote, state),
        SyncDirection::TwoWay => sync::sync(session, &sync_job, maildir, remote, state),
    }
    .map_err(|e| SyncError::E(format!("{}: {}", mailbox, e)))
}

fn worker_thread(
    i: u8,
    opts: &SyncOptions,
    direction: SyncDirection,
    rx: spmc::Receiver<mailboxes::SyncJob>,
) -> Result<(), SyncError> {
    let mut imap_session = new_session(&opts)?;
    while let Ok(job) = rx.recv() {
        trace!("Syncing {} in worker thread {}", job.name, i);
        measure!(
            format!("Synced {}", job.name),
            sync_mailbox(&opts.local, &job, &direction, &mut imap_session)?
        );
    }
    let _ = imap_session.logout()?;
    Ok(())
}

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

    let mut root_state = state::SyncState::load(&opts.local)?;

    let mut imap_session = new_session(opts)?;

    let names = imap_session.list(None, Some("*"))?;
    if names.len() == 0 {
        return Err(SyncError::Error("No remote mailboxes found, giving up"));
    }

    let includes: Vec<WildMatch> = opts.include.iter().map(|p| WildMatch::new(p)).collect();
    let excludes: Vec<WildMatch> = opts.exclude.iter().map(|p| WildMatch::new(p)).collect();

    let delimiter = get_hierarchy_delimiter(&names)?;
    let remote_mailboxes = mailboxes::load_remote(&names);
    let local_mailboxes = mailboxes::load_local(&opts.local, &delimiter);
    trace!("local: {:?}", local_mailboxes);
    trace!("remote: {:?}", remote_mailboxes);

    let only_local: BTreeSet<String> = local_mailboxes
        .difference(&remote_mailboxes)
        .cloned()
        .collect();
    trace!("Only local: {:?}", only_local);
    let only_remote: BTreeSet<String> = remote_mailboxes
        .difference(&local_mailboxes)
        .cloned()
        .collect();
    trace!("Only remote: {:?}", only_remote);
    let sync_jobs: Vec<mailboxes::SyncJob> = local_mailboxes
        .union(&remote_mailboxes)
        .cloned()
        .filter_map(|name| {
            // Apply user-provided include/exclude filter
            if includes.len() > 0 && !includes.iter().any(|e| e.matches(&name)) {
                trace!("Skipping {} due to include filter", name);
                return None;
            }
            if excludes.iter().any(|e| e.matches(&name)) {
                trace!("Skipping {} due to exclude filter", name);
                return None;
            }
            trace!("Processing mailbox {}", name);
            let delimiter = delimiter.clone();

            // We'll have to go through the tedious process of determining what to do
            // with mailboxes that are missing on one side.
            // trace!("Checking what to do with {}", name);
            if only_local.contains(&name) {
                match direction {
                    SyncDirection::Pull => {
                        // Delete locally, also from root state
                        mailboxes::sync_delete_local(name, delimiter, &mut root_state)
                    }
                    SyncDirection::Push => {
                        // Create remotely, add to root state
                        mailboxes::sync_create_remote(name, delimiter, &mut root_state)
                    }
                    SyncDirection::TwoWay => {
                        let dirname = Mailbox::virtual_to_dir(&name, &delimiter);
                        if root_state.last_seen.subdirs.contains(&dirname) {
                            // Exists locally only because removed on server side
                            // Delete locally, also from root state
                            mailboxes::sync_delete_local(name, delimiter, &mut root_state)
                        } else {
                            // Exists locally only because created here
                            // Create remotely, add to root state
                            mailboxes::sync_create_remote(name, delimiter, &mut root_state)
                        }
                    }
                }
            } else if only_remote.contains(&name) {
                match direction {
                    SyncDirection::Pull => {
                        // Create locally (already happening), add to root state (after sync?)
                        mailboxes::sync_create_local(name, delimiter, &mut root_state)
                    }
                    SyncDirection::Push => {
                        // Delete remotely, also from root state
                        mailboxes::sync_delete_remote(name, delimiter, &mut root_state)
                    }
                    SyncDirection::TwoWay => {
                        let dirname = Mailbox::virtual_to_dir(&name, &delimiter);
                        if root_state.last_seen.subdirs.contains(&dirname) {
                            // Exists remotely only because removed locally
                            // Delete remotely, also from root state
                            mailboxes::sync_delete_remote(name, delimiter, &mut root_state)
                        } else {
                            // Exists remotely only because created there
                            // Create locally (already happening), add to root state (after sync?)
                            mailboxes::sync_create_local(name, delimiter, &mut root_state)
                        }
                    }
                }
            } else {
                // Exists on both sides, just sync
                mailboxes::sync(name, delimiter)
            }
        })
        .collect();

    if opts.list_mailbox_actions {
        info!("The following actions would be performed:");
        for job in sync_jobs {
            info!("  {}: {:?}", job.name, job.action);
        }
        return Ok(());
    }

    root_state.save()?;
    drop(root_state);

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

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

        let t = thread::spawn(move || {
            if let Err(e) = worker_thread(i, &opts, dir, rx) {
                error!("Error in worker thread {}: {}", i, e);
            };
        });
        threads.push(t);
    }
    for job in sync_jobs {
        tx.send(job)?;
    }
    drop(tx);

    while let Ok(job) = rx.recv() {
        debug!("Syncing {} in main thread ({:?})", job.name, job.action);
        measure!(
            format!("Synced {}", job.name),
            sync_mailbox(&opts.local, &job, &direction, &mut imap_session)?
        );
    }

    _ = imap_session.logout();

    for t in threads {
        t.join().unwrap();
    }

    info!("Sync successful");
    Ok(())
}

/// Apply all changes from IMAP to the local maildir
///
/// This overwrites any changes that may have happened on the local side.
pub fn pull(opts: &SyncOptions) -> Result<(), SyncError> {
    measure!(
        format!("Pulled from {}", opts.remote),
        sync_(opts, SyncDirection::Pull)
    )
}

/// Apply all changes in local maildir to IMAP
///
/// This overwrites any changes that may have happened on the IMAP side.
pub fn push(opts: &SyncOptions) -> Result<(), SyncError> {
    measure!(
        format!("Pushed to {}", opts.remote),
        sync_(opts, SyncDirection::Push)
    )
}

/// Synchronize local and remote changes between IMAP and local maildir
///
/// This includes fetching new mail, deleting expunged mails, updating tags, etc.
pub fn sync(opts: &SyncOptions) -> Result<(), SyncError> {
    measure!(
        format!("Synced with {}", opts.remote),
        sync_(opts, SyncDirection::TwoWay)
    )
}