Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

14.9 KB
Raw Blame
//! Small on-disk caches that make launches and channel switches feel instant:
//! the latest page of each recently opened channel is kept, shown at once
//! when the channel opens again, then replaced by the fresh page from Discord;
//! and a snapshot of the account from the last READY (servers, channels, DMs,
//! friends, read states), shown while the gateway is still connecting.
//! (Images have their own cache in `net_images`.)
//!
//! Both are kept per account (`accounts/<user ID>/` in the cache folder).
//! Messages and the account's servers and friends are private: on Windows
//! they are sealed before they touch the disk (see [`seal`]), as a file in the
//! cache folder is otherwise readable by whoever gets hold of the disk. On
//! Linux and macOS they are stored as is, in a folder only this user can open
//! (see [`make_folders_private`]).

use discord::model::{Id, Message};
use serde_json::Value;
use std::io::{Read, Write};
use std::path::PathBuf;

/// How many channels' latest pages to keep.
const MAX_CHANNELS: usize = 200;
/// Messages kept per channel: at least one page, and all of today's
/// (up to `MAX_PER_CHANNEL`).
const PER_CHANNEL: usize = 50;
const MAX_PER_CHANNEL: usize = 1000;
/// The READY snapshot (zlib-compressed JSON, sealed). Bump when its shape changes.
const READY_FILE: &str = "ready-v2.bin";
/// Where channels' pages go (sealed JSON).
const MESSAGES_DIR: &str = "msgs-v2";
/// What earlier versions left at the top of the cache folder, removed at
/// start: files written unsealed, and the single account's snapshot and
/// messages from before accounts had folders of their own (taken over at
/// the first start, see `accounts::Saved::load`; an older RustCord run since
/// may have written them again).
const STALE: [&str; 4] = ["msgs-v1", "ready-v1.json.z", READY_FILE, MESSAGES_DIR];

/// Sealing with Windows' data protection (DPAPI): what is written can only be
/// read back by this Windows account on this PC. A copied disk, a backup or
/// another account sees nothing. (A program running as you can still ask
/// Windows to open it, exactly as with the saved login.)
mod seal {
    /// Starts every sealed file (and names the format).
    const MAGIC: &[u8; 4] = b"RCS1";

    pub fn seal(plain: &[u8]) -> Option<Vec<u8>> {
        let body = protect(plain, true)?;
        let mut out = Vec::with_capacity(MAGIC.len() + body.len());
        out.extend_from_slice(MAGIC);
        out.extend_from_slice(&body);
        Some(out)
    }

    /// None for anything that isn't a file sealed by this account.
    pub fn open(sealed: &[u8]) -> Option<Vec<u8>> {
        protect(sealed.strip_prefix(MAGIC)?, false)
    }

    #[cfg(windows)]
    fn protect(data: &[u8], seal: bool) -> Option<Vec<u8>> {
        use windows_sys::Win32::Foundation::LocalFree;
        use windows_sys::Win32::Security::Cryptography::{CryptProtectData, CryptUnprotectData, CRYPTPROTECT_UI_FORBIDDEN, CRYPT_INTEGER_BLOB};
        let input = CRYPT_INTEGER_BLOB { cbData: u32::try_from(data.len()).ok()?, pbData: data.as_ptr() as *mut u8 };
        let mut output = CRYPT_INTEGER_BLOB { cbData: 0, pbData: std::ptr::null_mut() };
        // SAFETY: `input` describes `data` (only read); Windows allocates
        // `output`, which is copied out and freed with LocalFree as documented.
        unsafe {
            let ok = if seal {
                CryptProtectData(&input, std::ptr::null(), std::ptr::null(), std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut output)
            } else {
                CryptUnprotectData(&input, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut output)
            };
            if ok == 0 || output.pbData.is_null() {
                return None;
            }
            let out = std::slice::from_raw_parts(output.pbData, output.cbData as usize).to_vec();
            LocalFree(output.pbData.cast());
            Some(out)
        }
    }

    /// (Other systems have no equivalent wired up yet: stored as is, in a
    /// folder only this user can open, see `make_folders_private`.)
    #[cfg(not(windows))]
    fn protect(data: &[u8], _seal: bool) -> Option<Vec<u8>> {
        Some(data.to_vec())
    }
}

/// Create RustCord's two folders, this cache folder and the config folder
/// (saved accounts, settings, the log), and let only this user open them,
/// before anything is written there. Everything RustCord keeps is below them,
/// so nothing inside needs its own mode, and folders made by an earlier
/// version are tightened at the next start. Without this they get whatever
/// the umask gives, usually readable by every account on the machine. (On
/// Windows the profile folder is already the user's own, and the caches are
/// sealed, see [`seal`].)
pub fn make_folders_private() {
    #[cfg(unix)]
    {
        if let Some(d) = directories::ProjectDirs::from("dev", "RustCord", "RustCord") {
            for root in [d.cache_dir(), d.config_dir()] {
                make_private(root);
            }
        }
    }
}

/// Create `dir` if needed and set it to 0700 (best effort: RustCord still
/// starts if it can't).
#[cfg(unix)]
fn make_private(dir: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::create_dir_all(dir);
    let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
}

/// Remove what earlier versions left behind (at start-up, after the saved
/// accounts were read).
pub fn remove_stale() {
    // API responses saved by the RUSTCORD_DUMP_API developer hook (account
    // data, in plain JSON): gone unless that hook is in use right now.
    if crate::diagnostics::dev_var_os("RUSTCORD_DUMP_API").is_none() {
        if let Some(d) = directories::ProjectDirs::from("dev", "RustCord", "RustCord") {
            remove_tree(&d.config_dir().join("api-dump"));
        }
    }
    let Some(root) = cache_root() else { return };
    for name in STALE {
        remove_tree(&root.join(name));
    }
}

/// Delete a file or a whole folder; true once nothing is left of it.
/// `remove_dir_all` refuses a folder reached through a redirected path (it
/// answers "reparse point encountered" where the profile folder is mapped from
/// elsewhere), so what it leaves is deleted piece by piece: private data is
/// never kept just because the quick way was refused.
pub fn remove_tree(path: &std::path::Path) -> bool {
    if path.is_dir() && std::fs::remove_dir_all(path).is_err() {
        if let Ok(rd) = std::fs::read_dir(path) {
            for e in rd.flatten() {
                remove_tree(&e.path());
            }
        }
        let _ = std::fs::remove_dir(path);
    } else if path.is_file() {
        let _ = std::fs::remove_file(path);
    }
    !path.exists()
}

fn cache_root() -> Option<PathBuf> {
    Some(directories::ProjectDirs::from("dev", "RustCord", "RustCord")?.cache_dir().to_path_buf())
}

fn account_root(account: Id) -> Option<PathBuf> {
    Some(cache_root()?.join("accounts").join(account.to_string()))
}

fn dir(account: Id) -> Option<PathBuf> {
    let d = account_root(account)?.join(MESSAGES_DIR);
    std::fs::create_dir_all(&d).ok()?;
    Some(d)
}

/// Move a single-login version's snapshot and messages under its account.
pub fn adopt_legacy(account: Id) {
    let (Some(root), Some(new)) = (cache_root(), account_root(account)) else { return };
    if std::fs::create_dir_all(&new).is_err() {
        return;
    }
    for name in [READY_FILE, MESSAGES_DIR] {
        if root.join(name).exists() {
            let _ = std::fs::rename(root.join(name), new.join(name));
        }
    }
}

/// The channel's last cached page (oldest → newest), if any.
pub fn load_messages(account: Id, channel: Id) -> Option<Vec<Message>> {
    let bytes = seal::open(&std::fs::read(dir(account)?.join(format!("{channel}.bin"))).ok()?)?;
    let mut list: Vec<Message> = serde_json::from_slice(&bytes).ok()?;
    list.sort_by_key(|m| m.id);
    (!list.is_empty()).then_some(list)
}

/// Write then rename, so a half-written file is never read.
fn write_atomically(path: &std::path::Path, bytes: &[u8]) {
    let tmp = path.with_extension("part");
    if std::fs::write(&tmp, bytes).is_ok() {
        let _ = std::fs::rename(&tmp, path);
    }
}

/// Remember a channel's newest messages (in the background): a page, or
/// everything from today if there's more.
pub fn save_messages(account: Id, channel: Id, list: &[Message]) {
    let today = crate::store::today_start_id();
    let keep: Vec<Message> = list
        .iter()
        .rev()
        .filter(|m| !m.meta.pending && !m.meta.failed)
        .enumerate()
        .take_while(|(i, m)| *i < PER_CHANNEL || m.id >= today)
        .map(|(_, m)| m.clone())
        .take(MAX_PER_CHANNEL)
        .collect();
    if keep.is_empty() {
        return;
    }
    let _ = std::thread::Builder::new().name("rustcord-cache".into()).spawn(move || {
        let Some(d) = dir(account) else { return };
        let Some(sealed) = serde_json::to_vec(&keep).ok().and_then(|json| seal::seal(&json)) else { return };
        write_atomically(&d.join(format!("{channel}.bin")), &sealed);
        prune(&d);
    });
}

/// Keep only the most recently written channels.
fn prune(d: &std::path::Path) {
    let Ok(rd) = std::fs::read_dir(d) else { return };
    let mut files: Vec<(std::time::SystemTime, PathBuf)> =
        rd.flatten().filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path()))).collect();
    if files.len() <= MAX_CHANNELS {
        return;
    }
    files.sort_by_key(|f| std::cmp::Reverse(f.0));
    for (_, p) in files.into_iter().skip(MAX_CHANNELS) {
        let _ = std::fs::remove_file(p);
    }
}

// ---- READY snapshot ---------------------------------------------------------

fn ready_path(account: Id) -> Option<PathBuf> {
    let root = account_root(account)?;
    std::fs::create_dir_all(&root).ok()?;
    Some(root.join(READY_FILE))
}

/// Keep the account snapshot from a READY payload (in the background).
/// Presences, voice states and the session are left out: they're stale by
/// the next launch, and the live gateway brings them anyway.
pub fn save_ready(account: Id, mut d: Value) {
    if let Value::Object(m) = &mut d {
        for k in ["merged_presences", "presences", "sessions", "session_id", "resume_gateway_url"] {
            m.remove(k);
        }
        if let Some(Value::Object(u)) = m.get_mut("user") {
            // Nothing the UI shows; keep private details off the disk.
            for k in ["email", "phone", "mfa_enabled", "nsfw_allowed", "verified"] {
                u.remove(k);
            }
        }
        if let Some(Value::Array(guilds)) = m.get_mut("guilds") {
            for g in guilds.iter_mut() {
                if let Value::Object(g) = g {
                    g.remove("presences");
                    g.remove("voice_states");
                }
            }
        }
    }
    let _ = std::thread::Builder::new().name("rustcord-cache".into()).spawn(move || {
        let Some(path) = ready_path(account) else { return };
        let Ok(json) = serde_json::to_vec(&d) else { return };
        drop(d);
        let mut enc = flate2::write::ZlibEncoder::new(Vec::with_capacity(json.len() / 4), flate2::Compression::fast());
        if enc.write_all(&json).is_err() {
            return;
        }
        if let Some(bytes) = enc.finish().ok().and_then(|z| seal::seal(&z)) {
            write_atomically(&path, &bytes);
            log::info!("cache: account snapshot saved ({} KB)", bytes.len() / 1024);
        }
    });
}

/// The account as of the last READY, if a snapshot exists.
pub fn load_ready(account: Id) -> Option<Value> {
    let bytes = seal::open(&std::fs::read(ready_path(account)?).ok()?)?;
    let mut json = Vec::with_capacity(bytes.len() * 6);
    flate2::read::ZlibDecoder::new(&bytes[..]).read_to_end(&mut json).ok()?;
    let v: Value = serde_json::from_slice(&json).ok()?;
    (v["user"]["id"].as_str() == Some(account.to_string().as_str())).then_some(v)
}

/// Forget what is kept for one account (it logged out, or its login was rejected).
pub fn forget_account(account: Id) {
    if let Some(root) = account_root(account) {
        remove_tree(&root);
    }
}

/// Forget what the accounts share (the last one logged out): the pictures
/// and clips kept on disk (avatars, attachments from DMs) and the provider
/// players' sign-ins.
pub fn clear_shared() {
    // (Thousands of small files: off the UI thread.)
    let _ = std::thread::Builder::new().name("rustcord-cache".into()).spawn(|| {
        crate::net_images::clear_disk();
        crate::video_player::clear_temp();
        // The provider players' profile: their cookies, so a Spotify or YouTube
        // sign-in. Its browser lets go of the files a moment after the player
        // closes, hence the retries.
        if let Some(players) = cache_root().map(|r| r.join("embed-player")) {
            for _ in 0..12 {
                if remove_tree(&players) {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(500));
            }
        }
    });
}

#[cfg(test)]
mod tests {
    use super::seal;

    #[test]
    fn folders_are_removed_whole() {
        let root = std::env::temp_dir().join(format!("rustcord-cache-test-{}", std::process::id()));
        std::fs::create_dir_all(root.join("a").join("b")).unwrap();
        std::fs::write(root.join("a").join("b").join("1.bin"), b"x").unwrap();
        std::fs::write(root.join("2.bin"), b"x").unwrap();
        assert!(super::remove_tree(&root) && !root.exists());
        // Nothing there is nothing left.
        assert!(super::remove_tree(&root));
    }

    #[cfg(unix)]
    #[test]
    fn folders_are_private_to_this_user() {
        use std::os::unix::fs::PermissionsExt;
        fn mode(p: &std::path::Path) -> u32 {
            std::fs::metadata(p).unwrap().permissions().mode() & 0o777
        }
        let root = std::env::temp_dir().join(format!("rustcord-private-test-{}", std::process::id()));
        let dir = root.join("rustcord");
        super::make_private(&dir);
        assert_eq!(mode(&dir), 0o700);
        // A folder an earlier version left open is closed too.
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
        super::make_private(&dir);
        assert_eq!(mode(&dir), 0o700);
        assert!(super::remove_tree(&root));
    }

    #[test]
    fn sealed_data_opens_again_and_is_not_readable_on_disk() {
        let plain = br#"[{"id":"1","content":"a private message"}]"#;
        let sealed = seal::seal(plain).expect("sealing");
        assert_eq!(seal::open(&sealed).as_deref(), Some(&plain[..]));
        // Unsealed files (an older version's) are not read.
        assert_eq!(seal::open(plain), None);
        #[cfg(windows)]
        {
            assert!(!sealed.windows(7).any(|w| w == b"private"));
            // Nor are damaged ones.
            let mut damaged = sealed.clone();
            let last = damaged.len() - 1;
            damaged[last] ^= 0xff;
            assert_eq!(seal::open(&damaged), None);
            assert_eq!(seal::open(b"RCS1"), None);
        }
    }
}