smirrors 0.1.0

Automatic mirror list updater for Linux distributions
Documentation
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Pacman package manager handler for Arch Linux and derivatives
//!
//! Handles mirror management for Pacman-based distributions including:
//! - Parsing /etc/pacman.d/mirrorlist
//! - Fetching available mirrors from Arch Linux mirror status API
//! - Updating mirrorlist configuration
//! - Backup and restore functionality

use super::DistroHandler;
use crate::core::Mirror;
use anyhow::{Context, Result};
use async_trait::async_trait;
use regex::Regex;
use reqwest::Client;
use serde::Deserialize;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use tracing::{debug, info, warn};
use url::Url;

/// Pacman handler for Arch Linux and derivatives
pub struct PacmanHandler {
    mirrorlist_file: PathBuf,
    pacman_conf: PathBuf,
    backup_dir: PathBuf,
}

/// Arch Linux mirror status API response
#[derive(Debug, Deserialize)]
struct MirrorStatusResponse {
    #[serde(default)]
    urls: Vec<MirrorUrl>,
}

#[derive(Debug, Deserialize)]
struct MirrorUrl {
    url: String,
    #[serde(default)]
    country: Option<String>,
    #[serde(default)]
    protocol: Option<String>,
    #[serde(default)]
    last_sync: Option<String>,
    #[serde(default)]
    completion_pct: Option<f64>,
    #[serde(default)]
    delay: Option<i64>,
    #[serde(default)]
    score: Option<f64>,
    #[serde(default)]
    active: Option<bool>,
}

/// Represents a mirror entry in mirrorlist
#[derive(Debug, Clone)]
struct MirrorListEntry {
    enabled: bool,
    url: String,
    line_number: usize,
}

impl PacmanHandler {
    /// Create a new Pacman handler
    pub fn new() -> Self {
        Self {
            mirrorlist_file: PathBuf::from("/etc/pacman.d/mirrorlist"),
            pacman_conf: PathBuf::from("/etc/pacman.conf"),
            backup_dir: PathBuf::from("/var/backups/smirrors/pacman"),
        }
    }

    /// Parse mirrorlist file
    fn parse_mirrorlist(&self) -> Result<Vec<Mirror>> {
        let content = fs::read_to_string(&self.mirrorlist_file)
            .context("Failed to read mirrorlist")?;

        let entries = self.parse_mirrorlist_content(&content)?;

        let mut mirrors = Vec::new();
        let mut seen_urls = std::collections::HashSet::new();

        for entry in entries {
            if !entry.enabled {
                continue;
            }

            // Expand $repo and $arch variables
            let url_str = self.expand_variables(&entry.url);

            if let Ok(url) = Url::parse(&url_str) {
                let url_key = url.as_str().trim_end_matches('/');

                if !seen_urls.contains(url_key) {
                    seen_urls.insert(url_key.to_string());

                    let mut mirror = Mirror::new(url);

                    // Try to extract country from URL
                    if let Some(country) = Self::extract_country_from_url(&entry.url) {
                        mirror.country = Some(country);
                    }

                    mirrors.push(mirror);
                }
            }
        }

        Ok(mirrors)
    }

    /// Parse mirrorlist content
    fn parse_mirrorlist_content(&self, content: &str) -> Result<Vec<MirrorListEntry>> {
        let mut entries = Vec::new();

        // Regex to match Server = URL lines
        let re = Regex::new(r"(?x)
            ^\s*
            (?P<comment>\#?)     # Optional comment
            \s*
            Server\s*=\s*
            (?P<url>\S+)         # URL
            \s*$
        ")?;

        for (line_num, line) in content.lines().enumerate() {
            if let Some(caps) = re.captures(line) {
                let is_commented = caps.name("comment").map_or(false, |m| !m.as_str().is_empty());
                let url = caps["url"].to_string();

                entries.push(MirrorListEntry {
                    enabled: !is_commented,
                    url,
                    line_number: line_num,
                });
            }
        }

        Ok(entries)
    }

    /// Expand Pacman variables in URLs
    fn expand_variables(&self, url: &str) -> String {
        let mut expanded = url.to_string();

        // For testing purposes, we'll use common defaults
        // In real usage, these would come from active repositories
        expanded = expanded.replace("$repo", "core");
        expanded = expanded.replace("$arch", &self.get_arch());

        expanded
    }

    /// Get system architecture
    fn get_arch(&self) -> String {
        let output = std::process::Command::new("uname")
            .arg("-m")
            .output();

        if let Ok(output) = output {
            String::from_utf8_lossy(&output.stdout).trim().to_string()
        } else {
            "x86_64".to_string()
        }
    }

    /// Extract country code from mirror URL
    fn extract_country_from_url(url: &str) -> Option<String> {
        if let Ok(parsed_url) = Url::parse(url) {
            if let Some(host) = parsed_url.host_str() {
                // Look for country code patterns
                let parts: Vec<&str> = host.split('.').collect();
                for part in parts {
                    if part.len() == 2 && part.chars().all(|c| c.is_ascii_alphabetic()) {
                        return Some(part.to_uppercase());
                    }
                }
            }
        }
        None
    }

    /// Fetch mirrors from Arch Linux mirror status API
    async fn fetch_arch_mirrors(&self) -> Result<Vec<Mirror>> {
        let client = Client::new();
        let url = "https://archlinux.org/mirrors/status/json/";

        debug!("Fetching Arch mirrors from: {}", url);

        let response = client
            .get(url)
            .send()
            .await
            .context("Failed to fetch Arch mirror status")?;

        let status: MirrorStatusResponse = response
            .json()
            .await
            .context("Failed to parse Arch mirror status")?;

        self.parse_mirror_status(status)
    }

    /// Parse mirror status response
    fn parse_mirror_status(&self, status: MirrorStatusResponse) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();

        for mirror_url in status.urls {
            // Skip inactive mirrors
            if !mirror_url.active.unwrap_or(false) {
                continue;
            }

            // Skip if completion is too low
            if let Some(completion) = mirror_url.completion_pct {
                if completion < 99.0 {
                    continue;
                }
            }

            // Prefer HTTPS mirrors
            let url_str = &mirror_url.url;

            if let Ok(url) = Url::parse(url_str) {
                let mut mirror = Mirror::new(url);

                if let Some(country) = mirror_url.country {
                    mirror.country = Some(country);
                }

                // Store mirror score from API
                if let Some(score) = mirror_url.score {
                    // API score is in seconds (delay), lower is better
                    // Convert to our 0-1 scale where higher is better
                    let normalized_score = (1.0 / (1.0 + score / 10.0)).min(1.0);
                    mirror.score = Some(normalized_score);
                }

                mirrors.push(mirror);
            }
        }

        // If no mirrors found, use fallback
        if mirrors.is_empty() {
            mirrors = self.get_fallback_mirrors();
        }

        Ok(mirrors)
    }

    /// Get fallback mirrors
    fn get_fallback_mirrors(&self) -> Vec<Mirror> {
        let mirror_urls = vec![
            "https://geo.mirror.pkgbuild.com/$repo/os/$arch",
            "https://mirror.rackspace.com/archlinux/$repo/os/$arch",
            "https://mirrors.kernel.org/archlinux/$repo/os/$arch",
            "https://mirror.math.princeton.edu/pub/archlinux/$repo/os/$arch",
            "https://mirrors.mit.edu/archlinux/$repo/os/$arch",
        ];

        mirror_urls
            .into_iter()
            .filter_map(|url_str| Url::parse(url_str).ok().map(Mirror::new))
            .collect()
    }

    /// Update mirrorlist file with new mirrors
    fn update_mirrorlist(&self, mirrors: &[Mirror]) -> Result<()> {
        if mirrors.is_empty() {
            anyhow::bail!("No mirrors provided for update");
        }

        let mut new_content = String::new();

        // Add header comment
        new_content.push_str("##\n");
        new_content.push_str("## Arch Linux repository mirrorlist\n");
        new_content.push_str("## Generated by SMirrors\n");
        new_content.push_str(&format!(
            "## Updated: {}\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
        ));
        new_content.push_str("##\n\n");

        // Add mirrors (sorted by score, best first)
        for (i, mirror) in mirrors.iter().enumerate() {
            let url = mirror.url.as_str();

            // Restore variables in URL
            let url = url.replace("/core/os/", "/$repo/os/");
            let url = url.replace(&format!("/{}/", self.get_arch()), "/$arch/");

            if i < 5 {
                // Enable top 5 mirrors
                new_content.push_str(&format!("Server = {}\n", url));
            } else {
                // Comment out the rest for reference
                new_content.push_str(&format!("#Server = {}\n", url));
            }
        }

        // Write atomically using temporary file
        let temp_file = self.mirrorlist_file.with_extension("tmp");
        let mut file = fs::File::create(&temp_file)
            .context("Failed to create temporary mirrorlist")?;

        file.write_all(new_content.as_bytes())
            .context("Failed to write temporary mirrorlist")?;

        file.sync_all()
            .context("Failed to sync temporary mirrorlist")?;

        drop(file);

        // Atomic rename
        fs::rename(&temp_file, &self.mirrorlist_file)
            .context("Failed to replace mirrorlist")?;

        info!("Updated mirrorlist with {} mirrors", mirrors.len());

        Ok(())
    }

    /// Get most recent backup
    fn get_latest_backup(&self) -> Result<PathBuf> {
        if !self.backup_dir.exists() {
            anyhow::bail!("No backups found");
        }

        let mut backups: Vec<_> = fs::read_dir(&self.backup_dir)?
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path()
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(|n| n.starts_with("mirrorlist."))
                    .unwrap_or(false)
            })
            .collect();

        backups.sort_by_key(|e| e.metadata().and_then(|m| m.modified()).ok());

        backups
            .last()
            .map(|e| e.path())
            .ok_or_else(|| anyhow::anyhow!("No backup files found"))
    }
}

impl Default for PacmanHandler {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DistroHandler for PacmanHandler {
    fn name(&self) -> &str {
        "Arch Linux Pacman"
    }

    fn detect(&self) -> bool {
        self.pacman_conf.exists()
            && std::process::Command::new("pacman")
                .arg("--version")
                .output()
                .is_ok()
    }

    async fn get_available_mirrors(&self) -> Result<Vec<Mirror>> {
        debug!("Fetching available mirrors for Pacman");
        self.fetch_arch_mirrors().await
    }

    fn get_current_mirrors(&self) -> Result<Vec<Mirror>> {
        debug!("Reading current mirrors from mirrorlist");
        self.parse_mirrorlist()
    }

    fn update_mirrors(&self, mirrors: &[Mirror]) -> Result<()> {
        info!("Updating Pacman mirrors");

        if !nix::unistd::geteuid().is_root() {
            anyhow::bail!("Root privileges required to update Pacman mirrorlist");
        }

        // Create backup first
        self.backup()?;

        // Update mirrorlist
        self.update_mirrorlist(mirrors)?;

        // Validate
        if !self.validate()? {
            warn!("Validation failed, restoring backup");
            self.restore_backup()?;
            anyhow::bail!("Mirror update validation failed");
        }

        // Refresh package databases
        info!("Refreshing package databases");
        let output = std::process::Command::new("pacman")
            .arg("-Sy")
            .arg("--noconfirm")
            .output();

        if let Err(e) = output {
            warn!("Failed to refresh package databases: {}", e);
        }

        info!("Successfully updated Pacman mirrors");
        Ok(())
    }

    fn backup(&self) -> Result<()> {
        debug!("Creating backup of mirrorlist");

        fs::create_dir_all(&self.backup_dir)
            .context("Failed to create backup directory")?;

        let timestamp = chrono::Utc::now().timestamp();
        let backup_file = self
            .backup_dir
            .join(format!("mirrorlist.{}", timestamp));

        fs::copy(&self.mirrorlist_file, &backup_file)
            .context("Failed to copy mirrorlist to backup")?;

        info!("Created backup: {:?}", backup_file);

        // Keep only last 10 backups
        let mut backups: Vec<_> = fs::read_dir(&self.backup_dir)?
            .filter_map(|e| e.ok())
            .collect();

        if backups.len() > 10 {
            backups.sort_by_key(|e| e.metadata().and_then(|m| m.modified()).ok());

            for entry in backups.iter().take(backups.len() - 10) {
                let _ = fs::remove_file(entry.path());
            }
        }

        Ok(())
    }

    fn restore_backup(&self) -> Result<()> {
        info!("Restoring mirrorlist from backup");

        let backup_file = self.get_latest_backup()?;

        fs::copy(&backup_file, &self.mirrorlist_file)
            .context("Failed to restore mirrorlist from backup")?;

        info!("Restored from backup: {:?}", backup_file);
        Ok(())
    }

    fn validate(&self) -> Result<bool> {
        debug!("Validating Pacman configuration");

        // Check if mirrorlist is readable and parseable
        match self.parse_mirrorlist() {
            Ok(mirrors) if !mirrors.is_empty() => {
                debug!("Validation successful, found {} mirrors", mirrors.len());
                Ok(true)
            }
            Ok(_) => {
                warn!("Validation found no mirrors");
                Ok(false)
            }
            Err(e) => {
                warn!("Validation failed to parse mirrorlist: {}", e);
                Ok(false)
            }
        }
    }
}

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

    #[test]
    fn test_parse_mirrorlist_content() {
        let handler = PacmanHandler::new();
        let content = r#"
##
## Arch Linux repository mirrorlist
##

## United States
Server = https://mirror.us.example.com/archlinux/$repo/os/$arch
#Server = https://mirror2.us.example.com/archlinux/$repo/os/$arch

## Germany
Server = https://mirror.de.example.com/archlinux/$repo/os/$arch
"#;

        let entries = handler.parse_mirrorlist_content(content).unwrap();
        assert_eq!(entries.len(), 3);

        assert!(entries[0].enabled);
        assert_eq!(
            entries[0].url,
            "https://mirror.us.example.com/archlinux/$repo/os/$arch"
        );

        assert!(!entries[1].enabled);

        assert!(entries[2].enabled);
    }

    #[test]
    fn test_expand_variables() {
        let handler = PacmanHandler::new();
        let url = "https://mirror.example.com/$repo/os/$arch";

        let expanded = handler.expand_variables(url);
        assert!(!expanded.contains("$repo"));
        assert!(!expanded.contains("$arch"));
    }

    #[test]
    fn test_extract_country_from_url() {
        assert_eq!(
            PacmanHandler::extract_country_from_url(
                "https://us.mirror.example.com/archlinux/$repo/os/$arch"
            ),
            Some("US".to_string())
        );

        assert_eq!(
            PacmanHandler::extract_country_from_url(
                "https://mirror.de.example.com/archlinux/$repo/os/$arch"
            ),
            Some("DE".to_string())
        );
    }
}