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
672
673
674
675
676
677
678
679
680
681
682
683
684
//! DNF/YUM package manager handler for Fedora and RHEL
//!
//! Handles mirror management for DNF-based distributions including:
//! - Parsing .repo files in /etc/yum.repos.d/
//! - Fetching available mirrors from Fedora Mirror Manager API
//! - Updating repository 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 serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};
use url::Url;

/// DNF handler for Fedora/RHEL distributions
pub struct DnfHandler {
    repos_dir: PathBuf,
    backup_dir: PathBuf,
    distro_variant: DnfVariant,
}

/// DNF distribution variant
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DnfVariant {
    Fedora,
    RHEL,
}

/// Represents a repository section in a .repo file
#[derive(Debug, Clone)]
struct RepoSection {
    name: String,
    enabled: bool,
    baseurl: Option<String>,
    mirrorlist: Option<String>,
    metalink: Option<String>,
    gpgcheck: bool,
    gpgkey: Option<String>,
    other_fields: HashMap<String, String>,
}

/// Fedora Mirror Manager API response
#[derive(Debug, Deserialize)]
struct MirrorManagerResponse {
    #[serde(default)]
    mirrors: Vec<MirrorEntry>,
}

#[derive(Debug, Deserialize)]
struct MirrorEntry {
    url: String,
    #[serde(default)]
    country: Option<String>,
    #[serde(default)]
    continent: Option<String>,
}

impl DnfHandler {
    /// Create a new DNF handler
    pub fn new() -> Self {
        let variant = Self::detect_variant();
        Self {
            repos_dir: PathBuf::from("/etc/yum.repos.d"),
            backup_dir: PathBuf::from("/var/backups/smirrors/dnf"),
            distro_variant: variant,
        }
    }

    /// Detect if this is Fedora or RHEL
    fn detect_variant() -> DnfVariant {
        if Path::new("/etc/fedora-release").exists() {
            return DnfVariant::Fedora;
        }

        if let Ok(content) = fs::read_to_string("/etc/os-release") {
            if content.contains("Fedora") || content.contains("ID=fedora") {
                return DnfVariant::Fedora;
            }
        }

        DnfVariant::RHEL
    }

    /// Parse all .repo files in repos directory
    fn parse_all_repos(&self) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();
        let mut seen_urls = std::collections::HashSet::new();

        if !self.repos_dir.exists() {
            return Ok(mirrors);
        }

        for entry in fs::read_dir(&self.repos_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.extension().and_then(|s| s.to_str()) == Some("repo") {
                if let Ok(content) = fs::read_to_string(&path) {
                    let sections = self.parse_repo_file(&content)?;

                    for section in sections {
                        if !section.enabled {
                            continue;
                        }

                        // Extract URL from baseurl, mirrorlist, or metalink
                        let url_str = section
                            .baseurl
                            .or(section.mirrorlist)
                            .or(section.metalink);

                        if let Some(url_str) = url_str {
                            // Handle variables like $releasever, $basearch
                            let url_str = self.expand_variables(&url_str);

                            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);
                                    mirror
                                        .metadata
                                        .insert("repo_name".to_string(), section.name.clone());

                                    mirrors.push(mirror);
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(mirrors)
    }

    /// Parse a single .repo file
    fn parse_repo_file(&self, content: &str) -> Result<Vec<RepoSection>> {
        let mut sections = Vec::new();
        let mut current_section: Option<RepoSection> = None;

        for line in content.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Check for section header [repo-name]
            if line.starts_with('[') && line.ends_with(']') {
                // Save previous section
                if let Some(section) = current_section.take() {
                    sections.push(section);
                }

                // Start new section
                let name = line[1..line.len() - 1].to_string();
                current_section = Some(RepoSection {
                    name,
                    enabled: false,
                    baseurl: None,
                    mirrorlist: None,
                    metalink: None,
                    gpgcheck: true,
                    gpgkey: None,
                    other_fields: HashMap::new(),
                });

                continue;
            }

            // Parse key=value pairs
            if let Some(eq_pos) = line.find('=') {
                let key = line[..eq_pos].trim().to_lowercase();
                let value = line[eq_pos + 1..].trim().to_string();

                if let Some(ref mut section) = current_section {
                    match key.as_str() {
                        "enabled" => {
                            section.enabled = value == "1" || value.to_lowercase() == "true";
                        }
                        "baseurl" => {
                            section.baseurl = Some(value);
                        }
                        "mirrorlist" => {
                            section.mirrorlist = Some(value);
                        }
                        "metalink" => {
                            section.metalink = Some(value);
                        }
                        "gpgcheck" => {
                            section.gpgcheck = value == "1" || value.to_lowercase() == "true";
                        }
                        "gpgkey" => {
                            section.gpgkey = Some(value);
                        }
                        _ => {
                            section.other_fields.insert(key, value);
                        }
                    }
                }
            }
        }

        // Save last section
        if let Some(section) = current_section {
            sections.push(section);
        }

        Ok(sections)
    }

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

        // Get system release version
        if let Ok(releasever) = self.get_releasever() {
            expanded = expanded.replace("$releasever", &releasever);
        }

        // Get system architecture
        if let Ok(basearch) = self.get_basearch() {
            expanded = expanded.replace("$basearch", &basearch);
        }

        expanded
    }

    /// Get release version
    fn get_releasever(&self) -> Result<String> {
        match self.distro_variant {
            DnfVariant::Fedora => {
                if let Ok(content) = fs::read_to_string("/etc/fedora-release") {
                    // Extract version number from "Fedora release 38 (Thirty Eight)"
                    let re = Regex::new(r"release\s+(\d+)")?;
                    if let Some(caps) = re.captures(&content) {
                        return Ok(caps[1].to_string());
                    }
                }
            }
            DnfVariant::RHEL => {
                if let Ok(content) = fs::read_to_string("/etc/redhat-release") {
                    let re = Regex::new(r"release\s+(\d+)")?;
                    if let Some(caps) = re.captures(&content) {
                        return Ok(caps[1].to_string());
                    }
                }
            }
        }

        // Fallback: read from os-release
        if let Ok(content) = fs::read_to_string("/etc/os-release") {
            for line in content.lines() {
                if line.starts_with("VERSION_ID=") {
                    let value = line.trim_start_matches("VERSION_ID=").trim_matches('"');
                    return Ok(value.to_string());
                }
            }
        }

        Ok("38".to_string()) // Default fallback
    }

    /// Get base architecture
    fn get_basearch(&self) -> Result<String> {
        let output = std::process::Command::new("uname")
            .arg("-m")
            .output()
            .context("Failed to get architecture")?;

        let arch = String::from_utf8(output.stdout)?.trim().to_string();

        // Map to DNF basearch
        let basearch = match arch.as_str() {
            "x86_64" => "x86_64",
            "i686" | "i386" => "i386",
            "aarch64" => "aarch64",
            "armv7l" => "armhfp",
            "ppc64le" => "ppc64le",
            "s390x" => "s390x",
            _ => &arch,
        };

        Ok(basearch.to_string())
    }

    /// Fetch available mirrors from Fedora Mirror Manager
    async fn fetch_fedora_mirrors(&self) -> Result<Vec<Mirror>> {
        let client = Client::new();

        // Fedora Mirror Manager API
        let releasever = self.get_releasever()?;
        let basearch = self.get_basearch()?;

        let url = format!(
            "https://mirrors.fedoraproject.org/mirrorlist?repo=fedora-{}&arch={}",
            releasever, basearch
        );

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

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

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

        self.parse_mirrorlist_response(&text)
    }

    /// Parse mirrorlist response
    fn parse_mirrorlist_response(&self, content: &str) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();

        for line in content.lines() {
            let line = line.trim();

            // Skip comments
            if line.starts_with('#') || line.is_empty() {
                continue;
            }

            // Parse URL
            if let Ok(url) = Url::parse(line) {
                mirrors.push(Mirror::new(url));
            }
        }

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

        Ok(mirrors)
    }

    /// Get fallback Fedora mirrors
    fn get_fallback_fedora_mirrors(&self) -> Vec<Mirror> {
        let mirror_urls = vec![
            "https://download.fedoraproject.org/pub/fedora/linux/",
            "https://mirrors.kernel.org/fedora/",
            "http://mirror.math.princeton.edu/pub/fedora/linux/",
            "http://mirrors.mit.edu/fedora/linux/",
        ];

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

    /// Update .repo file with new mirror
    fn update_repo_file(&self, path: &Path, new_mirror: &Mirror) -> Result<()> {
        let content = fs::read_to_string(path)?;
        let sections = self.parse_repo_file(&content)?;

        let mut new_content = String::new();
        let mut current_section: Option<&RepoSection> = None;
        let mut section_index = 0;

        let new_url = new_mirror.url.as_str().trim_end_matches('/');

        for line in content.lines() {
            let line_trimmed = line.trim();

            // Track current section
            if line_trimmed.starts_with('[') && line_trimmed.ends_with(']') {
                current_section = sections.get(section_index);
                section_index += 1;
            }

            let mut modified_line = line.to_string();

            // Replace baseurl if in enabled section
            if let Some(section) = current_section {
                if section.enabled && line_trimmed.to_lowercase().starts_with("baseurl=") {
                    // Replace the URL
                    modified_line = format!("baseurl={}", new_url);
                }
            }

            new_content.push_str(&modified_line);
            new_content.push('\n');
        }

        // Write atomically
        let temp_file = path.with_extension("tmp");
        let mut file = fs::File::create(&temp_file)?;
        file.write_all(new_content.as_bytes())?;
        file.sync_all()?;
        drop(file);

        fs::rename(&temp_file, path)?;

        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())
            .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 DnfHandler {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DistroHandler for DnfHandler {
    fn name(&self) -> &str {
        match self.distro_variant {
            DnfVariant::Fedora => "Fedora DNF",
            DnfVariant::RHEL => "RHEL DNF/YUM",
        }
    }

    fn detect(&self) -> bool {
        self.repos_dir.exists()
            && (std::process::Command::new("dnf")
                .arg("--version")
                .output()
                .is_ok()
                || std::process::Command::new("yum")
                    .arg("--version")
                    .output()
                    .is_ok())
    }

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

        match self.distro_variant {
            DnfVariant::Fedora => self.fetch_fedora_mirrors().await,
            DnfVariant::RHEL => {
                // RHEL doesn't have public mirror list
                Ok(self.get_fallback_fedora_mirrors())
            }
        }
    }

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

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

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

        if mirrors.is_empty() {
            anyhow::bail!("No mirrors provided for update");
        }

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

        let best_mirror = &mirrors[0];

        // Update all .repo files
        for entry in fs::read_dir(&self.repos_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.extension().and_then(|s| s.to_str()) == Some("repo") {
                if let Err(e) = self.update_repo_file(&path, best_mirror) {
                    warn!("Failed to update {:?}: {}", path, e);
                }
            }
        }

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

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

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

        fs::create_dir_all(&self.backup_dir)?;

        let timestamp = chrono::Utc::now().timestamp();
        let backup_subdir = self.backup_dir.join(format!("backup-{}", timestamp));
        fs::create_dir_all(&backup_subdir)?;

        // Backup all .repo files
        for entry in fs::read_dir(&self.repos_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.extension().and_then(|s| s.to_str()) == Some("repo") {
                if let Some(filename) = path.file_name() {
                    let backup_path = backup_subdir.join(filename);
                    fs::copy(&path, backup_path)?;
                }
            }
        }

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

        // Keep only last 10 backups
        let mut backups: Vec<_> = fs::read_dir(&self.backup_dir)?
            .filter_map(|e| e.ok())
            .filter(|e| e.path().is_dir())
            .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_dir_all(entry.path());
            }
        }

        Ok(())
    }

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

        let backup_dir = self.get_latest_backup()?;

        // Restore all files from backup
        for entry in fs::read_dir(&backup_dir)? {
            let entry = entry?;
            let backup_path = entry.path();

            if backup_path.extension().and_then(|s| s.to_str()) == Some("repo") {
                if let Some(filename) = backup_path.file_name() {
                    let target_path = self.repos_dir.join(filename);
                    fs::copy(&backup_path, target_path)?;
                }
            }
        }

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

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

        // Try to run dnf repolist
        let cmd = if std::process::Command::new("dnf")
            .arg("--version")
            .output()
            .is_ok()
        {
            "dnf"
        } else {
            "yum"
        };

        let output = std::process::Command::new(cmd)
            .arg("repolist")
            .arg("--quiet")
            .output()
            .context("Failed to run repolist")?;

        if !output.status.success() {
            warn!(
                "{} repolist failed: {}",
                cmd,
                String::from_utf8_lossy(&output.stderr)
            );
            return Ok(false);
        }

        // Check if we can parse repos
        match self.parse_all_repos() {
            Ok(mirrors) if !mirrors.is_empty() => {
                debug!("Validation successful, found {} repos", mirrors.len());
                Ok(true)
            }
            Ok(_) => {
                warn!("Validation found no repos");
                Ok(false)
            }
            Err(e) => {
                warn!("Validation failed to parse repos: {}", e);
                Ok(false)
            }
        }
    }
}

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

    #[test]
    fn test_parse_repo_file() {
        let handler = DnfHandler::new();
        let content = r#"
[fedora]
name=Fedora $releasever - $basearch
baseurl=http://download.fedoraproject.org/pub/fedora/linux/releases/$releasever/Everything/$basearch/os/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-$releasever-$basearch

[fedora-updates]
name=Fedora $releasever - $basearch - Updates
mirrorlist=https://mirrors.fedoraproject.org/mirrorlist?repo=updates-released-f$releasever&arch=$basearch
enabled=1
gpgcheck=1
"#;

        let sections = handler.parse_repo_file(content).unwrap();
        assert_eq!(sections.len(), 2);

        assert_eq!(sections[0].name, "fedora");
        assert!(sections[0].enabled);
        assert!(sections[0].baseurl.is_some());

        assert_eq!(sections[1].name, "fedora-updates");
        assert!(sections[1].enabled);
        assert!(sections[1].mirrorlist.is_some());
    }

    #[test]
    fn test_expand_variables() {
        let handler = DnfHandler::new();
        let url = "http://example.com/$releasever/$basearch/";

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

    #[test]
    fn test_parse_mirrorlist_response() {
        let handler = DnfHandler::new();
        let content = r#"
# Fedora Mirrors
http://mirror1.example.com/fedora/
http://mirror2.example.com/fedora/
https://mirror3.example.com/fedora/
"#;

        let mirrors = handler.parse_mirrorlist_response(content).unwrap();
        assert_eq!(mirrors.len(), 3);
    }
}