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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! APT package manager handler for Debian and Ubuntu
//!
//! Handles mirror management for APT-based distributions including:
//! - Parsing sources.list and sources.list.d/*.list files
//! - Fetching available mirrors from official mirror lists
//! - Updating mirror configurations
//! - 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 std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};
use url::Url;

/// APT handler for Debian/Ubuntu distributions
pub struct AptHandler {
    sources_file: PathBuf,
    sources_dir: PathBuf,
    backup_dir: PathBuf,
    distro_variant: AptVariant,
}

/// APT distribution variant
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AptVariant {
    Debian,
    Ubuntu,
}

/// Represents a parsed APT source line
#[derive(Debug, Clone)]
struct SourceLine {
    enabled: bool,
    source_type: String, // "deb" or "deb-src"
    options: Vec<String>,
    url: String,
    distribution: String,
    components: Vec<String>,
    original_line: String,
    line_number: usize,
}

impl AptHandler {
    /// Create a new APT handler
    pub fn new() -> Self {
        let variant = Self::detect_variant();
        Self {
            sources_file: PathBuf::from("/etc/apt/sources.list"),
            sources_dir: PathBuf::from("/etc/apt/sources.list.d"),
            backup_dir: PathBuf::from("/var/backups/smirrors/apt"),
            distro_variant: variant,
        }
    }

    /// Detect if this is Debian or Ubuntu
    fn detect_variant() -> AptVariant {
        if let Ok(content) = fs::read_to_string("/etc/os-release") {
            if content.contains("Ubuntu") || content.contains("ID=ubuntu") {
                return AptVariant::Ubuntu;
            }
        }

        if Path::new("/etc/lsb-release").exists() {
            if let Ok(content) = fs::read_to_string("/etc/lsb-release") {
                if content.contains("Ubuntu") {
                    return AptVariant::Ubuntu;
                }
            }
        }

        AptVariant::Debian
    }

    /// Parse sources.list file
    fn parse_sources_list(&self) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();

        // Parse main sources.list
        if self.sources_file.exists() {
            let content = fs::read_to_string(&self.sources_file)?;
            mirrors.extend(self.extract_mirrors_from_content(&content)?);
        }

        // Parse sources.list.d/*.list files
        if self.sources_dir.exists() {
            for entry in fs::read_dir(&self.sources_dir)? {
                let entry = entry?;
                let path = entry.path();

                if path.extension().and_then(|s| s.to_str()) == Some("list") {
                    if let Ok(content) = fs::read_to_string(&path) {
                        mirrors.extend(self.extract_mirrors_from_content(&content)?);
                    }
                }
            }
        }

        Ok(mirrors)
    }

    /// Extract mirrors from file content
    fn extract_mirrors_from_content(&self, content: &str) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();
        let mut seen_urls = std::collections::HashSet::new();

        for source in self.parse_source_lines(content)? {
            if !source.enabled {
                continue;
            }

            // Only process "deb" lines, not "deb-src"
            if source.source_type != "deb" {
                continue;
            }

            // Parse URL
            if let Ok(url) = Url::parse(&source.url) {
                // Normalize URL (remove trailing slash for comparison)
                let url_str = url.as_str().trim_end_matches('/');

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

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

                    // Extract country from hostname if possible
                    if let Some(country) = Self::extract_country_from_hostname(&source.url) {
                        mirror.country = Some(country);
                    }

                    // Store distribution and components in metadata
                    mirror
                        .metadata
                        .insert("distribution".to_string(), source.distribution.clone());
                    mirror.metadata.insert(
                        "components".to_string(),
                        source.components.join(" "),
                    );

                    mirrors.push(mirror);
                }
            }
        }

        Ok(mirrors)
    }

    /// Parse source lines from content
    fn parse_source_lines(&self, content: &str) -> Result<Vec<SourceLine>> {
        let mut sources = Vec::new();

        // Regex for matching source lines
        // Matches: deb [options] url distribution components...
        // or: deb url distribution components...
        let re = Regex::new(
            r"(?x)
            ^
            \s*
            (?P<comment>\#?)          # Optional comment marker
            \s*
            (?P<type>deb|deb-src)     # Source type
            \s+
            (?:\[(?P<options>[^\]]+)\]\s+)?  # Optional options in brackets
            (?P<url>\S+)              # URL
            \s+
            (?P<dist>\S+)             # Distribution
            (?:\s+(?P<components>.+))?  # Optional components
            \s*
            $
        ",
        )?;

        for (line_num, line) in content.lines().enumerate() {
            let trimmed = line.trim();

            // Skip empty lines
            if trimmed.is_empty() {
                continue;
            }

            // Check if line matches
            if let Some(caps) = re.captures(line) {
                let is_commented = caps.name("comment").map_or(false, |m| !m.as_str().is_empty());

                let source_type = caps["type"].to_string();
                let url = caps["url"].to_string();
                let distribution = caps["dist"].to_string();

                let options = caps
                    .name("options")
                    .map(|m| {
                        m.as_str()
                            .split_whitespace()
                            .map(|s| s.to_string())
                            .collect()
                    })
                    .unwrap_or_default();

                let components = caps
                    .name("components")
                    .map(|m| {
                        m.as_str()
                            .split_whitespace()
                            .map(|s| s.to_string())
                            .collect()
                    })
                    .unwrap_or_default();

                sources.push(SourceLine {
                    enabled: !is_commented,
                    source_type,
                    options,
                    url,
                    distribution,
                    components,
                    original_line: line.to_string(),
                    line_number: line_num,
                });
            }
        }

        Ok(sources)
    }

    /// Extract country code from hostname
    fn extract_country_from_hostname(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 like mirror.us.example.com or us.mirror.example.com
                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 available mirrors for Debian
    async fn fetch_debian_mirrors(&self) -> Result<Vec<Mirror>> {
        let client = Client::new();
        let url = "https://www.debian.org/mirror/list";

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

        let html = response
            .text()
            .await
            .context("Failed to read Debian mirror list")?;

        self.parse_debian_mirror_html(&html)
    }

    /// Parse Debian mirror list HTML
    fn parse_debian_mirror_html(&self, html: &str) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();

        // Regex to extract mirror URLs from HTML
        // Debian mirror list contains URLs in <a href="..."> tags
        let re = Regex::new(r#"(?:https?://[^\s"<>]+/debian/?)"#)?;

        for cap in re.captures_iter(html) {
            if let Some(url_str) = cap.get(0) {
                let url_str = url_str.as_str().trim_end_matches('/');
                if let Ok(url) = Url::parse(url_str) {
                    let mut mirror = Mirror::new(url.clone());

                    // Try to extract country
                    if let Some(country) = Self::extract_country_from_hostname(url_str) {
                        mirror.country = Some(country);
                    }

                    mirrors.push(mirror);
                }
            }
        }

        Ok(mirrors)
    }

    /// Fetch available mirrors for Ubuntu
    async fn fetch_ubuntu_mirrors(&self) -> Result<Vec<Mirror>> {
        let client = Client::new();

        // Ubuntu maintains a JSON API for mirrors
        let url = "https://launchpad.net/ubuntu/+archivemirrors-rss";

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

        let content = response
            .text()
            .await
            .context("Failed to read Ubuntu mirror list")?;

        self.parse_ubuntu_mirror_list(&content)
    }

    /// Parse Ubuntu mirror list (RSS/XML format)
    fn parse_ubuntu_mirror_list(&self, content: &str) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();

        // Extract URLs from XML/RSS content
        let re = Regex::new(r#"(?:https?://[^\s"<>]+/ubuntu/?)"#)?;

        for cap in re.captures_iter(content) {
            if let Some(url_str) = cap.get(0) {
                let url_str = url_str.as_str().trim_end_matches('/');
                if let Ok(url) = Url::parse(url_str) {
                    let mut mirror = Mirror::new(url.clone());

                    if let Some(country) = Self::extract_country_from_hostname(url_str) {
                        mirror.country = Some(country);
                    }

                    mirrors.push(mirror);
                }
            }
        }

        // If no mirrors found from RSS, use fallback list
        if mirrors.is_empty() {
            mirrors = self.get_fallback_ubuntu_mirrors();
        }

        Ok(mirrors)
    }

    /// Get fallback Ubuntu mirrors
    fn get_fallback_ubuntu_mirrors(&self) -> Vec<Mirror> {
        let mirror_urls = vec![
            "http://archive.ubuntu.com/ubuntu/",
            "http://us.archive.ubuntu.com/ubuntu/",
            "http://security.ubuntu.com/ubuntu/",
            "http://mirrors.kernel.org/ubuntu/",
            "http://mirror.math.princeton.edu/pub/ubuntu/",
        ];

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

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

        // Read current sources.list
        let content = fs::read_to_string(&self.sources_file)
            .context("Failed to read sources.list")?;

        let sources = self.parse_source_lines(&content)?;

        // Use the best mirror (first one, assumed to be sorted by score)
        let best_mirror = &mirrors[0];
        let new_url = best_mirror.url.as_str().trim_end_matches('/');

        // Replace URLs in sources
        let mut new_content = String::new();
        let mut current_line = 0;

        for line in content.lines() {
            let mut modified_line = line.to_string();

            // Check if this line is a source line
            if let Some(source) = sources.iter().find(|s| s.line_number == current_line) {
                // Replace the URL in this line
                if source.enabled && source.source_type == "deb" {
                    modified_line = Self::replace_url_in_line(line, new_url);
                }
            }

            new_content.push_str(&modified_line);
            new_content.push('\n');
            current_line += 1;
        }

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

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

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

        drop(file);

        // Atomic rename
        fs::rename(&temp_file, &self.sources_file)
            .context("Failed to replace sources.list")?;

        info!("Updated sources.list with new mirror: {}", new_url);

        Ok(())
    }

    /// Replace URL in a source line
    fn replace_url_in_line(line: &str, new_url: &str) -> String {
        // Regex to match the URL part of a deb line
        let re = Regex::new(
            r"(?x)
            (^\s*(?:\#\s*)?(?:deb|deb-src)\s+(?:\[[^\]]+\]\s+)?)  # Prefix
            (\S+)                                                   # URL to replace
            (\s+.*)                                                 # Suffix
        ",
        )
        .unwrap();

        if let Some(caps) = re.captures(line) {
            format!("{}{}{}", &caps[1], new_url, &caps[3])
        } else {
            line.to_string()
        }
    }

    /// Get most recent backup file
    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("sources.list."))
                    .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 AptHandler {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DistroHandler for AptHandler {
    fn name(&self) -> &str {
        match self.distro_variant {
            AptVariant::Debian => "Debian APT",
            AptVariant::Ubuntu => "Ubuntu APT",
        }
    }

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

    async fn get_available_mirrors(&self) -> Result<Vec<Mirror>> {
        debug!("Fetching available mirrors for APT");

        match self.distro_variant {
            AptVariant::Debian => self.fetch_debian_mirrors().await,
            AptVariant::Ubuntu => self.fetch_ubuntu_mirrors().await,
        }
    }

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

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

        // Check for root privileges
        if !nix::unistd::geteuid().is_root() {
            anyhow::bail!("Root privileges required to update APT sources");
        }

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

        // Update sources.list
        self.update_sources_list(mirrors)?;

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

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

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

        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!("sources.list.{}", timestamp));

        fs::copy(&self.sources_file, &backup_file)
            .context("Failed to copy sources.list 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 sources.list from backup");

        let backup_file = self.get_latest_backup()?;

        fs::copy(&backup_file, &self.sources_file)
            .context("Failed to restore sources.list from backup")?;

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

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

        // Run apt-cache policy to validate sources
        let output = std::process::Command::new("apt-cache")
            .arg("policy")
            .output()
            .context("Failed to run apt-cache policy")?;

        if !output.status.success() {
            warn!("apt-cache policy failed: {}", String::from_utf8_lossy(&output.stderr));
            return Ok(false);
        }

        // Check if sources.list is readable and parseable
        match self.parse_sources_list() {
            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 sources: {}", e);
                Ok(false)
            }
        }
    }
}

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

    #[test]
    fn test_parse_source_line_simple() {
        let handler = AptHandler::new();
        let content = "deb http://archive.ubuntu.com/ubuntu/ jammy main restricted";

        let sources = handler.parse_source_lines(content).unwrap();
        assert_eq!(sources.len(), 1);

        let source = &sources[0];
        assert!(source.enabled);
        assert_eq!(source.source_type, "deb");
        assert_eq!(source.url, "http://archive.ubuntu.com/ubuntu/");
        assert_eq!(source.distribution, "jammy");
        assert_eq!(source.components, vec!["main", "restricted"]);
    }

    #[test]
    fn test_parse_source_line_with_options() {
        let handler = AptHandler::new();
        let content = "deb [arch=amd64,arm64] http://example.com/ubuntu jammy main";

        let sources = handler.parse_source_lines(content).unwrap();
        assert_eq!(sources.len(), 1);

        let source = &sources[0];
        assert!(source.enabled);
        assert!(!source.options.is_empty());
        assert_eq!(source.url, "http://example.com/ubuntu");
    }

    #[test]
    fn test_parse_commented_line() {
        let handler = AptHandler::new();
        let content = "# deb http://example.com/ubuntu jammy main";

        let sources = handler.parse_source_lines(content).unwrap();
        assert_eq!(sources.len(), 1);

        let source = &sources[0];
        assert!(!source.enabled);
    }

    #[test]
    fn test_replace_url_in_line() {
        let line = "deb http://old.com/ubuntu/ jammy main";
        let new_url = "http://new.com/ubuntu";

        let result = AptHandler::replace_url_in_line(line, new_url);
        assert!(result.contains("http://new.com/ubuntu"));
        assert!(result.contains("jammy main"));
    }

    #[test]
    fn test_extract_country_from_hostname() {
        assert_eq!(
            AptHandler::extract_country_from_hostname("http://us.mirror.example.com/"),
            Some("US".to_string())
        );

        assert_eq!(
            AptHandler::extract_country_from_hostname("http://mirror.uk.example.com/"),
            Some("UK".to_string())
        );
    }
}