summaryrefslogtreecommitdiff
path: root/src/sync.rs
blob: 2d1b6b72eb1b1fd5e25e0742c0601b04d42f24e4 (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
use colored::*;
use std::path::Path;
use std::process::Command;
use crate::config::Config;

const REPOS_DIR: &str = "/var/ror/packages";

fn enforce_repo_https(url: &str) -> Result<(), String> {
    if url.starts_with("http://") {
        return Err(format!(
            "Insecure HTTP URL rejected: {}. Only HTTPS is allowed for repositories.",
            url
        ));
    }
    Ok(())
}

fn check_repo_permissions() {
    let repo_path = Path::new(REPOS_DIR);
    if !repo_path.exists() {
        return;
    }
    match std::fs::metadata(repo_path) {
        Ok(meta) => {
            use std::os::unix::fs::MetadataExt;
            let uid = meta.uid();
            if uid != 0 {
                eprintln!(
                    "{} WARNING: Repository directory '{}' is owned by UID {} (not root). \
                     This is a security risk — any user can modify packages.",
                    "[ror]".yellow().bold(),
                    REPOS_DIR,
                    uid
                );
            }
            let mode = meta.mode() & 0o7777;
            if mode & 0o002 != 0 {
                eprintln!(
                    "{} WARNING: Repository directory '{}' is world-writable (mode {:o}). \
                     This is a security risk — any user can inject malicious packages.",
                    "[ror]".yellow().bold(),
                    REPOS_DIR,
                    mode
                );
            }
        }
        Err(_) => {}
    }
}

pub fn run_sync(cfg: &Config) {
    if cfg.repositories.is_empty() {
        eprintln!("{} No repositories configured.", "[ror]".red().bold());
        return;
    }
    check_repo_permissions();
    for (name, repo) in &cfg.repositories {
        if let Err(e) = enforce_repo_https(&repo.url) {
            eprintln!("{} {}: {}", "[ror]".red().bold(), name, e);
            continue;
        }
        if let Some(ref mirror) = repo.mirror {
            if let Err(e) = enforce_repo_https(mirror) {
                eprintln!("{} {}: {}", "[ror]".red().bold(), name, e);
                continue;
            }
        }
        println!("{} Syncing repository '{}'...", "[ror]".blue().bold(), name);
        let repo_path = Path::new(REPOS_DIR).join(name);
        if repo_path.exists() {
            println!("{} Updating {}...", ">>>".green(), name);
            if let Err(e) = pull_repo(&repo_path, repo.mirror.as_deref()) {
                eprintln!("{} {}", "[ror]".red(), e);
            } else {
                println!("{} Repository updated.", ">>>".green());
            }
        } else {
            println!("{} Cloning {}...", ">>>".green(), name);
            if let Err(e) = clone_repo(name, &repo.url, repo.mirror.as_deref()) {
                eprintln!("{} {}", "[ror]".red(), e);
            } else {
                println!("{} Repository cloned.", ">>>".green());
            }
        }
    }
}

fn clone_repo(name: &str, primary: &str, mirror: Option<&str>) -> Result<(), String> {
    let path = Path::new(REPOS_DIR).join(name);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| format!("Failed to create repos dir: {}", e))?;
    }

    let status = Command::new("git")
        .args(["clone", primary, path.to_str().unwrap()])
        .status()
        .map_err(|e| format!("Failed to run git: {}", e))?;

    if status.success() {
        return Ok(());
    }

    if let Some(mirror_url) = mirror {
        eprintln!("{} Primary clone failed, trying mirror...", "[ror]".yellow());
        let mirror_status = Command::new("git")
            .args(["clone", mirror_url, path.to_str().unwrap()])
            .status()
            .map_err(|e| format!("Failed to run git clone for mirror: {}", e))?;

        if mirror_status.success() {
            return Ok(());
        }
    }

    Err(format!("Failed to clone repository '{}'", name))
}

fn pull_repo(repo_path: &Path, mirror: Option<&str>) -> Result<(), String> {
    let path_str = repo_path.to_str().ok_or("Invalid repo path")?;
    let status = Command::new("git")
        .args(["-C", path_str, "pull"])
        .status()
        .map_err(|e| format!("Failed to run git pull: {}", e))?;

    if status.success() {
        return Ok(());
    }

    if let Some(mirror_url) = mirror {
        eprintln!("{} Pull from primary failed, trying mirror...", "[ror]".yellow());
        let mirror_status = Command::new("git")
            .args(["-C", path_str, "pull", mirror_url])
            .status()
            .map_err(|e| format!("Failed to run git pull from mirror: {}", e))?;

        if mirror_status.success() {
            return Ok(());
        }
    }

    Err(format!("Failed to pull repository at '{}'", path_str))
}