summaryrefslogtreecommitdiff
path: root/src/check.rs
blob: 530814f2d7675caa2a8a1e59232df400e400ec3e (plain)
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
use colored::Colorize;
use sha2::{Sha256, Digest};
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path};
use tempfile::tempdir;

use crate::config::Config;
use crate::install::{
    InstalledDB, load_package, select_binary_for_arch, BinaryPackage,
    download_and_verify, extract_native, extract_ror, extract_sror, extract_deb,
};

fn compute_sha256(path: &Path) -> Result<String, std::io::Error> {
    let mut file = fs::File::open(path)?;
    let mut hasher = Sha256::new();
    std::io::copy(&mut file, &mut hasher)?;
    Ok(format!("{:x}", hasher.finalize()))
}

fn load_expected_hashes(
    _pkg_name: &str,
    binary: &BinaryPackage,
    cfg: &Config,
) -> Result<HashMap<String, String>, String> {
    let effective_filename = crate::install::resolve_filename(
        &crate::install::load_package(_pkg_name).unwrap(),
        binary,
    );

    let urls = if !binary.url.is_empty() {
        vec![binary.url.clone()]
    } else {
        binary
            .mirrors
            .iter()
            .map(|m| m.replace("{filename}", &effective_filename))
            .collect()
    };

    if urls.is_empty() {
        return Err("No download URLs".to_string());
    }

    let archive_path = download_and_verify(&urls[0], &binary.sha256, cfg)?;

    let temp_dir = tempdir().map_err(|e| e.to_string())?;
    let work_dir = temp_dir.path();

    let pkg_type = binary.pkg_type.as_deref().unwrap_or("tar.xz");
    let files = if pkg_type == "ror" {
        let dict_url = binary
            .dict
            .as_ref()
            .ok_or_else(|| "Missing dict URL for .ror".to_string())?;
        let dict_path = download_and_verify(dict_url, "", cfg)?;
        let res = extract_ror(&archive_path, work_dir);
        let _ = fs::remove_file(&dict_path);
        res
    } else if pkg_type == "sror" {
        extract_sror(&archive_path, work_dir)
    } else if pkg_type == "deb" {
        extract_deb(&archive_path, work_dir)
    } else {
        extract_native(&archive_path, work_dir)
    }
    .map_err(|e| format!("Extraction failed: {}", e))?;

    let mut hashes = HashMap::new();
    for rel_path in files {
        let full = work_dir.join(&rel_path);
        if full.is_file() {
            if let Ok(h) = compute_sha256(&full) {
                hashes.insert(rel_path, h);
            }
        }
    }

    let _ = fs::remove_file(&archive_path);
    Ok(hashes)
}

pub fn check_integrity(cfg: &Config) {
    println!("{} Checking package integrity...", "[ror]".blue().bold());

    let db = InstalledDB::load();
    if db.packages.is_empty() {
        println!("{} No packages installed.", "[ror]".yellow());
        return;
    }

    let mut total_ok = 0;
    let mut total_missing = 0;
    let mut total_modified = 0;
    let mut broken_packages = Vec::new();

    for (name, installed) in &db.packages {
        if installed.files.is_empty() {
            continue;
        }

        print!("  {} ... ", name);
        std::io::stdout().flush().ok();

        let pkg = match load_package(name) {
            Some(p) => p,
            None => {
                println!("{}", "SKIP (not in repo)".yellow());
                continue;
            }
        };

        let binary = match select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc, None) {
            Ok(b) => b,
            Err(_) => {
                println!("{}", "SKIP (no binary)".yellow());
                continue;
            }
        };

        let expected_hashes = match load_expected_hashes(name, binary, cfg) {
            Ok(map) => map,
            Err(e) => {
                println!("{} ({})", "ERROR".red(), e);
                broken_packages.push(name.clone());
                continue;
            }
        };

        let mut missing = Vec::new();
        let mut modified = Vec::new();
        let mut ok = 0;

        for rel_path in &installed.files {
            let full_path = Path::new("/").join(rel_path);
            match fs::metadata(&full_path) {
                Ok(meta) if meta.is_file() => {
                    match compute_sha256(&full_path) {
                        Ok(hash) => {
                            if let Some(expected) = expected_hashes.get(rel_path) {
                                if &hash == expected {
                                    ok += 1;
                                } else {
                                    modified.push(rel_path.clone());
                                }
                            }
                        }
                        Err(_) => {
                            modified.push(rel_path.clone());
                        }
                    }
                }
                Ok(_) => {} 
                Err(_) => {
                    missing.push(rel_path.clone());
                }
            }
        }

        if missing.is_empty() && modified.is_empty() {
            println!("{}", "OK".green());
        } else {
            println!(
                "{} (missing: {}, modified: {})",
                "WARN".yellow(),
                missing.len(),
                modified.len()
            );
            broken_packages.push(name.clone());
        }

        total_ok += ok;
        total_missing += missing.len();
        total_modified += modified.len();
    }

    println!(
        "\n{} Summary: {} files OK, {} missing, {} modified",
        "[ror]".blue().bold(),
        total_ok,
        total_missing,
        total_modified
    );

    if !broken_packages.is_empty() {
        println!(
            "\n{} Broken packages: {}",
            "[ror]".yellow().bold(),
            broken_packages.join(", ")
        );
        print!("{} Reinstall them? [y/N]: ", "[ror]".blue().bold());
        std::io::stdout().flush().ok();
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer).ok();
        if answer.trim().eq_ignore_ascii_case("y") {
            for pkg in broken_packages {
                println!("{} Reinstalling {} ...", ">>>".cyan(), pkg);
                crate::install::install_package(&pkg, cfg);
            }
        }
    }
}