blackship 0.6.0

A FreeBSD jail manager with state machine control
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
//! Bootstrap functionality for fetching FreeBSD releases
//!
//! Provides:
//! - Downloading and extracting FreeBSD base system archives
//! - Release management (list, verify)
//! - Support for different architectures
//! - Retry with exponential backoff for network operations

use crate::error::{Error, Result};
use crate::manifest::{RetryConfig, validate_name};
use crate::supply::{backoff_from_config, download_file, fetch_text, url_exists};
use rand::{RngExt, rng};
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::thread;
use tar::Archive;
use xz2::read::XzDecoder;

/// Supported FreeBSD architectures
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Arch {
    Amd64,
    Arm64,
    I386,
}

impl Arch {
    /// Get architecture from current system
    pub fn current() -> Result<Self> {
        let arch = std::env::consts::ARCH;
        match arch {
            "x86_64" => Ok(Self::Amd64),
            "aarch64" => Ok(Self::Arm64),
            "x86" => Ok(Self::I386),
            _ => Err(Error::UnsupportedArch(arch.to_string())),
        }
    }

    /// Get FreeBSD architecture name
    pub const fn freebsd_name(self) -> &'static str {
        match self {
            Self::Amd64 => "amd64",
            Self::Arm64 => "arm64",
            Self::I386 => "i386",
        }
    }
}

/// A bootstrapped release
#[derive(Debug)]
pub struct Release {
    /// Release name (e.g., "15.1-RELEASE")
    pub name: String,
    /// Path to the extracted release
    pub path: PathBuf,
    /// Architecture
    pub arch: Arch,
}

/// Provisioner for fetching and managing releases
pub struct Provisioner {
    /// Base URL for FreeBSD mirror
    mirror_url: String,
    /// Directory for storing releases
    releases_dir: PathBuf,
    /// Cache directory for downloads
    cache_dir: PathBuf,
    /// Archives to download
    archives: Vec<String>,
    /// Current architecture
    arch: Arch,
    /// Retry configuration for network operations
    retry_config: RetryConfig,
}

impl Provisioner {
    /// Create a new provisioner
    pub fn new(
        mirror_url: String,
        releases_dir: PathBuf,
        cache_dir: PathBuf,
        archives: Vec<String>,
        retry_config: RetryConfig,
    ) -> Result<Self> {
        Ok(Self {
            mirror_url,
            releases_dir,
            cache_dir,
            archives,
            arch: Arch::current()?,
            retry_config,
        })
    }

    /// Create provisioner from config
    pub fn from_config(config: &crate::manifest::GlobalConfig) -> Result<Self> {
        Self::new(
            config.mirror_url.clone(),
            config.releases_dir.clone(),
            config.cache_dir.clone(),
            config.bootstrap_archives.clone(),
            config.retry.clone(),
        )
    }

    /// Get URL for a release archive
    fn archive_url(&self, release: &str, archive: &str) -> String {
        format!(
            "{}/{}/{}/{}.txz",
            self.mirror_url,
            self.arch.freebsd_name(),
            release,
            archive
        )
    }

    /// Get URL for release MANIFEST
    fn manifest_url(&self, release: &str) -> String {
        format!(
            "{}/{}/{}/MANIFEST",
            self.mirror_url,
            self.arch.freebsd_name(),
            release
        )
    }

    /// Parse a MANIFEST file and return archive -> sha256 mapping
    // provision/tests.rs calls it on an instance.
    fn parse_manifest(content: &str) -> HashMap<String, String> {
        let mut checksums = HashMap::new();

        for line in content.lines() {
            // Format: archive.txz\tsha256\tsize\tpath_count
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 2 {
                let archive = parts[0].trim_end_matches(".txz");
                let sha256 = parts[1];
                checksums.insert(archive.to_string(), sha256.to_string());
            }
        }

        checksums
    }

    /// Get the path where a release would be extracted
    pub fn release_path(&self, release: &str) -> Result<PathBuf> {
        validate_name("release", release)?;
        Ok(self.releases_dir.join(release))
    }

    /// Check if a release is already bootstrapped
    pub fn is_bootstrapped(&self, release: &str) -> Result<bool> {
        let path = self.release_path(release)?;
        Ok(path.exists() && path.join("bin").exists() && path.join("usr").exists())
    }

    /// List all bootstrapped releases
    pub fn list_releases(&self) -> Result<Vec<Release>> {
        let mut releases = Vec::new();

        if !self.releases_dir.exists() {
            return Ok(releases);
        }

        for entry in fs::read_dir(&self.releases_dir).map_err(Error::Io)? {
            let entry = entry.map_err(Error::Io)?;
            let path = entry.path();

            if path.is_dir() {
                // Check if it looks like a valid release
                if path.join("bin").exists()
                    && path.join("usr").exists()
                    && let Some(name) = path.file_name().and_then(|n| n.to_str())
                {
                    releases.push(Release {
                        name: name.to_string(),
                        path: path.clone(),
                        arch: self.arch,
                    });
                }
            }
        }

        // Sort by name
        releases.sort_by(|a, b| a.name.cmp(&b.name));

        Ok(releases)
    }

    /// Bootstrap a FreeBSD release
    ///
    /// Downloads and extracts the specified release archives.
    /// Bootstrap a release from base packages (pkgbase) instead of base.txz.
    ///
    /// FreeBSD 16 dropped distribution sets, so this is the only path
    /// forward there; it works for 15.x too. Uses fingerprint-verified
    /// official repos via `pkg --rootdir`.
    pub fn bootstrap_pkgbase(&self, release: &str, force: bool) -> Result<PathBuf> {
        let release_path = self.release_path(release)?;

        if self.is_bootstrapped(release)? && !force {
            return Err(Error::ReleaseAlreadyExists(release.to_string()));
        }

        let version = crate::sys::OsVersion::parse(release)?;
        let host = crate::sys::OsVersion::detect_kernel()?;
        if version.major > host.major {
            return Err(Error::JailOperation(format!(
                "Cannot bootstrap {release} on a FreeBSD {host} host: jail userlands must not be newer than the kernel"
            )));
        }

        let repo = match version.release_type {
            crate::sys::ReleaseType::Release => format!("base_release_{}", version.minor),
            _ => "base_latest".to_string(),
        };
        let abi = format!("FreeBSD:{}:{}", version.major, self.arch.freebsd_name());

        // Prefer the per-major pkgbase key directory when the host ships it.
        let versioned_keys = format!("/usr/share/keys/pkgbase-{}", version.major);
        let fingerprints = if Path::new(&versioned_keys).exists() {
            versioned_keys
        } else {
            "/usr/share/keys/pkg".to_string()
        };

        std::fs::create_dir_all(&release_path)?;
        // pkg extracts /etc config files without creating the directory
        // first; a missing etc/ makes it skip them silently.
        std::fs::create_dir_all(release_path.join("etc"))?;

        // pkg --rootdir resolves the fingerprints path inside the rootdir,
        // so the host's trusted keys must be copied into the target first.
        let keys_in_root = release_path.join(fingerprints.trim_start_matches('/'));
        copy_tree(Path::new(&fingerprints), &keys_in_root)?;
        let repo_dir = self.cache_dir.join("pkgbase-repo");
        std::fs::create_dir_all(&repo_dir)?;
        std::fs::write(
            repo_dir.join("FreeBSD-base.conf"),
            format!(
                "FreeBSD-base: {{\n  url: \"pkg+https://pkg.freebsd.org/${{ABI}}/{repo}\",\n  mirror_type: \"srv\",\n  signature_type: \"fingerprints\",\n  fingerprints: \"{fingerprints}\",\n  enabled: yes\n}}\n"
            ),
        )?;

        eprintln!("Bootstrapping {release} via pkgbase ({abi} / {repo})");
        // pkg(8) itself lives in the ports repo, not base; jails bootstrap
        // it on first `pkg` use like any fresh FreeBSD install.
        for pkg_args in [
            vec!["update"],
            vec!["install", "-y", "FreeBSD-set-base-jail"],
        ] {
            let status = std::process::Command::new("/usr/sbin/pkg")
                .arg("--rootdir")
                .arg(&release_path)
                .arg("--repo-conf-dir")
                .arg(&repo_dir)
                .args(["-o", &format!("ABI={abi}")])
                .args(["-o", "IGNORE_OSVERSION=yes"])
                .args(&pkg_args)
                .status()
                .map_err(|e| Error::JailOperation(format!("Failed to run pkg: {e}")))?;
            if !status.success() {
                return Err(Error::JailOperation(format!(
                    "pkg {} failed for pkgbase bootstrap of {}",
                    pkg_args.join(" "),
                    release
                )));
            }
        }

        // pkgbase ships no /etc/rc.conf; sysrc needs one to edit.
        let rc_conf = release_path.join("etc/rc.conf");
        if !rc_conf.exists()
            && let Err(e) = std::fs::write(&rc_conf, "")
        {
            eprintln!("Warning: could not create {}: {e}", rc_conf.display());
        }
        // Cosmetic.
        let _ = std::fs::write(release_path.join("root/.hushlogin"), "");

        eprintln!("Bootstrap complete: {}", release_path.display());
        Ok(release_path)
    }

    pub fn bootstrap(&self, release: &str, force: bool) -> Result<PathBuf> {
        let release_path = self.release_path(release)?;

        for archive in &self.archives {
            validate_name("archive", archive)?;
        }

        // Check if already exists
        if self.is_bootstrapped(release)? && !force {
            return Err(Error::ReleaseAlreadyExists(release.to_string()));
        }

        // Verify release exists on mirror
        let manifest_url = self.manifest_url(release);
        if !url_exists(&manifest_url, &self.retry_config) {
            return Err(Error::ReleaseNotFound(release.to_string()));
        }

        eprintln!("Bootstrapping {} for {}", release, self.arch.freebsd_name());

        // Fetch MANIFEST for checksums
        eprintln!("Fetching MANIFEST...");
        let manifest_content = fetch_text(&manifest_url, &self.retry_config)?;
        let checksums = Self::parse_manifest(&manifest_content);

        // Pre-planted symlinks in parent dirs would redirect create_dir_all writes.
        for dir in [&self.cache_dir, &release_path] {
            let mut check = dir.as_path();
            while let Some(parent) = check.parent() {
                if let Ok(meta) = fs::symlink_metadata(check)
                    && meta.file_type().is_symlink()
                {
                    return Err(Error::ExtractionFailed(format!(
                        "Path component '{}' is a symlink, refusing to proceed",
                        check.display()
                    )));
                }
                if check == parent {
                    break;
                }
                check = parent;
            }
        }

        // Create directories
        fs::create_dir_all(&self.cache_dir).map_err(Error::Io)?;
        fs::create_dir_all(&release_path).map_err(Error::Io)?;

        // Download and extract each archive with retry
        for archive in &self.archives {
            let url = self.archive_url(release, archive);
            let cache_file = self.cache_dir.join(format!("{release}-{archive}.txz"));

            // Get expected checksum
            let expected_sha256 = checksums.get(archive.as_str());

            // Retry loop for download and extract
            let mut backoff = backoff_from_config(&self.retry_config)?;
            let mut rng = rng();
            let mut attempt: u8 = 0;

            loop {
                attempt += 1;

                // Download if not cached or checksum doesn't match
                let needs_download = if cache_file.exists() {
                    if let Some(expected) = expected_sha256 {
                        match crate::supply::sha256_file(&cache_file) {
                            Ok(actual) => actual != *expected,
                            Err(_) => true,
                        }
                    } else {
                        false
                    }
                } else {
                    true
                };

                let result: Result<()> = (|| {
                    if needs_download {
                        eprintln!("Downloading {archive}.txz...");
                        download_file(
                            &url,
                            &cache_file,
                            expected_sha256.map(std::string::String::as_str),
                            &self.retry_config,
                        )?;
                    } else {
                        eprintln!("Using cached {archive}.txz");
                    }

                    // Extract archive
                    eprintln!("Extracting {archive}.txz...");
                    Self::extract_txz(&cache_file, &release_path)?;
                    Ok(())
                })();

                match result {
                    Ok(()) => break,
                    Err(e) => {
                        if let Ok(delay) = backoff.failed(rng.random()) {
                            eprintln!(
                                "Archive {archive} attempt {attempt} failed, retrying in {}ms...",
                                delay.as_millis()
                            );
                            // Remove potentially corrupt cached file before retry
                            let _ = fs::remove_file(&cache_file);
                            thread::sleep(delay);
                        } else {
                            return Err(e);
                        }
                    }
                }
            }
        }

        eprintln!("Bootstrap complete: {}", release_path.display());
        Ok(release_path)
    }

    /// Extract a .txz (tar.xz) archive
    fn extract_txz(archive_path: &Path, dest: &Path) -> Result<()> {
        let file = File::open(archive_path).map_err(|e| {
            Error::ExtractionFailed(format!(
                "Failed to open archive {}: {}",
                archive_path.display(),
                e
            ))
        })?;

        let reader = BufReader::new(file);
        let xz = XzDecoder::new(reader);
        let mut archive = Archive::new(xz);

        // Preserve permissions and ownership
        archive.set_preserve_permissions(true);
        archive.set_preserve_ownerships(true);

        // Refuse to extract into a symlink
        if let Ok(meta) = std::fs::symlink_metadata(dest)
            && meta.file_type().is_symlink()
        {
            return Err(Error::ExtractionFailed(format!(
                "Extraction destination '{}' is a symlink, refusing to unpack into it",
                dest.display()
            )));
        }

        archive.unpack(dest).map_err(|e| {
            Error::ExtractionFailed(format!(
                "Failed to extract {}: {}",
                archive_path.display(),
                e
            ))
        })?;

        Ok(())
    }

    /// Verify a bootstrapped release against MANIFEST
    pub fn verify(&self, release: &str) -> Result<bool> {
        if !self.is_bootstrapped(release)? {
            return Err(Error::ReleaseNotFound(release.to_string()));
        }

        // For now, just check that essential directories exist
        let release_path = self.release_path(release)?;
        let essential_paths = ["bin/sh", "usr/bin/env", "lib/libc.so.7"];

        for path in essential_paths {
            if !release_path.join(path).exists() {
                eprintln!("Missing essential file: {path}");
                return Ok(false);
            }
        }

        Ok(true)
    }
}

/// Recursively copy a small file tree, preserving permissions and symlinks.
///
/// Suitable for config/key trees. Whole-userland copies stay on `cp -a`:
/// it preserves hardlinks (/rescue is ~150 links to one binary) and file
/// flags, which a naive walk does not.
pub fn copy_tree(src: &Path, dest: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    let meta = fs::symlink_metadata(src)
        .map_err(|e| Error::ExtractionFailed(format!("stat {}: {}", src.display(), e)))?;

    if meta.file_type().is_symlink() {
        let target = fs::read_link(src)
            .map_err(|e| Error::ExtractionFailed(format!("readlink {}: {}", src.display(), e)))?;
        let _ = fs::remove_file(dest); // usually NotFound; symlink() reports the rest
        std::os::unix::fs::symlink(&target, dest)
            .map_err(|e| Error::ExtractionFailed(format!("symlink {}: {}", dest.display(), e)))?;
    } else if meta.is_dir() {
        fs::create_dir_all(dest)
            .map_err(|e| Error::ExtractionFailed(format!("mkdir {}: {}", dest.display(), e)))?;
        fs::set_permissions(dest, fs::Permissions::from_mode(meta.permissions().mode()))
            .map_err(|e| Error::ExtractionFailed(format!("chmod {}: {}", dest.display(), e)))?;
        for entry in fs::read_dir(src)
            .map_err(|e| Error::ExtractionFailed(format!("readdir {}: {}", src.display(), e)))?
        {
            let entry = entry.map_err(|e| {
                Error::ExtractionFailed(format!("readdir {}: {}", src.display(), e))
            })?;
            copy_tree(&entry.path(), &dest.join(entry.file_name()))?;
        }
    } else {
        fs::copy(src, dest).map_err(|e| {
            Error::ExtractionFailed(format!(
                "copy {} -> {}: {}",
                src.display(),
                dest.display(),
                e
            ))
        })?;
    }
    Ok(())
}

/// Warnings for jails whose `release` is not bootstrapped under the
/// manifest's `releases_dir`. Host state, not configuration: the release can
/// be bootstrapped later, so callers warn rather than fail.
pub fn unbootstrapped_releases(config: &crate::manifest::BlackshipConfig) -> Vec<String> {
    let Ok(provisioner) = Provisioner::from_config(&config.config) else {
        return Vec::new();
    };
    config
        .jails
        .iter()
        .filter_map(|jail| {
            let release = jail.release.as_deref()?;
            (!provisioner.is_bootstrapped(release).unwrap_or(true)).then(|| {
                format!(
                    "jail `{}`: release `{release}` not bootstrapped in {} (blackship bootstrap {release})",
                    jail.name,
                    config.config.releases_dir.display()
                )
            })
        })
        .collect()
}

#[cfg(test)]
mod tests;