blackship 0.5.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
//! Building a container: claim, provision, mount, network, jail, limits.

use super::registry::{self, Record};
use super::{Container, ContainerSpec, Mount, Network, teardown, validate_container_name};
use crate::error::{Error, Result};
use crate::host::Layout;
use crate::manifest::validate_name;
use crate::network;
use std::net::IpAddr;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

pub fn create(layout: &Arc<Layout>, spec: &ContainerSpec) -> Result<Container> {
    Error::require_root("creating a container")?;
    validate(spec)?;

    let name = spec.name();
    let release_path = layout.releases_dir().join(spec.release());
    if !release_path.join("bin").exists() {
        return Err(Error::ReleaseNotFound(spec.release().to_string()));
    }
    if crate::jail::jail_getid(name).is_ok() {
        return Err(Error::JailExists(name.to_string()));
    }

    let root = layout.container_root(name);
    crate::blueprint::context::reject_symlink_ancestors(layout.data_dir(), &root)?;

    let zfs = layout.zfs();
    let dataset = zfs
        .as_ref()
        .filter(|zfs| zfs.release_is_cloneable(spec.release()))
        .map(|zfs| zfs.container_dataset(name));

    registry::claim(
        layout,
        name,
        &Record {
            release: spec.release().to_string(),
            root: root.clone(),
            dataset: dataset.clone(),
            owner_pid: Some(std::process::id()),
            labels: spec.labels.clone(),
        },
    )?;

    // Leftovers predating the claim are not ours: refuse rather than clobber.
    let occupied = std::fs::read_dir(&root).is_ok_and(|mut entries| entries.next().is_some());
    let dataset_taken = match (&zfs, &dataset) {
        (Some(zfs), Some(ds)) => zfs.dataset_exists(ds)?,
        _ => false,
    };
    if occupied || dataset_taken {
        // Rollback; keep the original error.
        let _ = registry::remove(layout, name);
        return Err(Error::JailExists(name.to_string()));
    }

    match build(layout, spec, &release_path, &root, dataset.as_deref()) {
        Ok(jid) => Ok(Container {
            layout: Arc::clone(layout),
            name: name.to_string(),
            jid,
            root,
            dataset,
            destroy_on_drop: true,
        }),
        Err(e) => {
            // Rollback; keep the original error.
            let _ = teardown::destroy(layout, name);
            Err(e)
        }
    }
}

fn validate(spec: &ContainerSpec) -> Result<()> {
    validate_container_name(spec.name())?;
    validate_name("release", spec.release())?;
    if let Some(hostname) = &spec.hostname
        && (hostname.is_empty()
            || !hostname
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.'))
    {
        return Err(Error::InvalidArgument(format!(
            "hostname '{hostname}' must be letters, digits, '-' and '.'"
        )));
    }
    for mount in &spec.mounts {
        if !mount.host.is_absolute() || !mount.host.is_dir() {
            return Err(Error::InvalidArgument(format!(
                "mount source '{}' must be an existing absolute directory",
                mount.host.display()
            )));
        }
        let clean = mount
            .jail
            .components()
            .all(|c| matches!(c, Component::RootDir | Component::Normal(_)));
        if !mount.jail.is_absolute() || !clean || mount.jail == Path::new("/") {
            return Err(Error::InvalidArgument(format!(
                "mount target '{}' must be an absolute path below / with no '..'",
                mount.jail.display()
            )));
        }
    }
    for param in &spec.params {
        if param.is_empty() || param.starts_with('-') {
            return Err(Error::InvalidArgument(format!(
                "jail parameter '{param}' is not a jail(8) parameter"
            )));
        }
    }
    Ok(())
}

/// Everything after the claim; returns the new jail id.
fn build(
    layout: &Layout,
    spec: &ContainerSpec,
    release_path: &Path,
    root: &Path,
    dataset: Option<&str>,
) -> Result<i32> {
    match (dataset, layout.zfs()) {
        (Some(dataset), Some(zfs)) => zfs.clone_release_into(spec.release(), dataset, root)?,
        _ => copy_release(layout, release_path, root)?,
    }

    install_resolver(spec, root)?;

    for mount in &spec.mounts {
        mount_nullfs(root, mount)?;
    }

    let vnet = match &spec.network {
        Network::Vnet(network_name) => Some(setup_vnet(layout, spec.name(), network_name)?),
        _ => None,
    };

    start_jail(spec, root)?;
    let jid = crate::jail::jail_getid(spec.name())?;

    if let Some(vnet) = &vnet {
        vnet.attach_to_jail(jid)?;
    }

    let resources = spec.limits.resources();
    if resources.has_rctl_rules() {
        crate::rctl::apply_limits(spec.name(), resources)?;
    }
    if let Some(cpus) = &resources.cpuset {
        crate::rctl::apply_cpuset(jid, cpus)?;
    }
    Ok(jid)
}

/// Full copy of the release for non-ZFS hosts, after a free-space check.
fn copy_release(layout: &Layout, release_path: &Path, root: &Path) -> Result<()> {
    if let Some(needed) = dir_size(release_path) {
        let free = free_space(layout.data_dir()).unwrap_or(u64::MAX);
        if free < needed + needed / 10 {
            return Err(Error::JailCreationFailed(format!(
                "Not enough space to copy release: need ~{} MiB, {} MiB free on {}. \
                 Enable ZFS for copy-on-write clones.",
                needed / 1_048_576,
                free / 1_048_576,
                layout.data_dir().display()
            )));
        }
    }
    std::fs::create_dir_all(root)?;
    let mut source = release_path.as_os_str().to_owned();
    source.push("/.");
    let output = Command::new("/bin/cp")
        .arg("-a")
        .arg(&source)
        .arg(root)
        .output()?;
    if !output.status.success() {
        return Err(Error::JailCreationFailed(format!(
            "Failed to copy release: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(())
}

/// Total bytes used by a directory tree (best effort).
fn dir_size(path: &Path) -> Option<u64> {
    let output = Command::new("/usr/bin/du")
        .args(["-sk"])
        .arg(path)
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    let kib: u64 = text.split_whitespace().next()?.parse().ok()?;
    Some(kib * 1024)
}

/// Free bytes on the filesystem holding `path`.
fn free_space(path: &Path) -> Option<u64> {
    let stat = nix::sys::statfs::statfs(path).ok()?;
    // f_bavail is signed on FreeBSD (negative when root eats the reserve).
    u64::try_from(stat.blocks_available())
        .ok()
        .map(|blocks| blocks * stat.block_size())
}

/// nullfs-mount `mount` inside `root`, creating the target.
fn mount_nullfs(root: &Path, mount: &Mount) -> Result<()> {
    let (host, jail) = (&mount.host, &mount.jail);
    let target = root.join(jail.strip_prefix("/").unwrap_or(jail));
    crate::blueprint::context::reject_symlink_ancestors(root, &target)?;
    std::fs::create_dir_all(&target)?;
    let canonical_root = root.canonicalize()?;
    let canonical_target: PathBuf = target.canonicalize()?;
    if !canonical_target.starts_with(&canonical_root) {
        return Err(Error::InvalidArgument(format!(
            "mount target '{}' escapes the container root",
            jail.display()
        )));
    }
    let mut command = Command::new("/sbin/mount_nullfs");
    for option in mount.options() {
        command.args(["-o", option]);
    }
    let output = command.arg(host).arg(&canonical_target).output()?;
    if !output.status.success() {
        return Err(Error::JailCreationFailed(format!(
            "mount_nullfs {} {}: {}",
            host.display(),
            canonical_target.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(())
}

/// Write the container's `/etc/resolv.conf` (see [`resolv_conf`]). The
/// release may ship none (pkgbase does not) or one from another network.
fn install_resolver(spec: &ContainerSpec, root: &Path) -> Result<()> {
    let host = match std::fs::read_to_string(HOST_RESOLV_CONF) {
        Ok(text) => Some(text),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => {
            return Err(Error::Network(format!(
                "cannot read {HOST_RESOLV_CONF}: {e}"
            )));
        }
    };
    let Some(content) = resolv_conf(spec, host.as_deref())? else {
        return Ok(());
    };
    // etc/ must be the container's own; the file itself is replaced, never followed.
    let etc = root.join("etc");
    crate::blueprint::context::reject_symlink_ancestors(root, &etc)?;
    crate::sys::write_nofollow(&etc.join("resolv.conf"), content.as_bytes())
}

const HOST_RESOLV_CONF: &str = "/etc/resolv.conf";

/// The resolver for `spec`, given the host's `resolv.conf`; `None` leaves
/// the release's alone.
///
/// Explicit nameservers win. [`Network::Inherit`] shares the host's stack,
/// so the host's file works verbatim. A VNET stack cannot reach the host's
/// loopback or a link-local address scoped to a host interface, so those
/// nameservers are dropped; when nothing is left the container would
/// resolve nothing, and that is an error rather than a surprise later.
fn resolv_conf(spec: &ContainerSpec, host: Option<&str>) -> Result<Option<String>> {
    if !spec.nameservers.is_empty() {
        let mut content = String::from("# Written by blackship\n");
        for server in &spec.nameservers {
            content.push_str("nameserver ");
            content.push_str(&server.to_string());
            content.push('\n');
        }
        return Ok(Some(content));
    }
    let Some(host) = host else {
        return Ok(None);
    };
    match spec.network {
        Network::None => Ok(None),
        Network::Inherit => Ok(Some(host.to_string())),
        Network::Vnet(_) => {
            let mut content = String::with_capacity(host.len());
            let mut dropped = Vec::new();
            let mut kept = 0;
            for line in host.lines() {
                match nameserver_of(line) {
                    Some(server) if !reachable_from_vnet(server) => {
                        dropped.push(server);
                        continue;
                    }
                    Some(_) => kept += 1,
                    None => {}
                }
                content.push_str(line);
                content.push('\n');
            }
            if kept == 0 && !dropped.is_empty() {
                return Err(Error::Network(format!(
                    "the host resolves through {}, which container '{}' cannot reach from its \
                     own network stack; give it a nameserver (ContainerSpec::nameserver, \
                     or --dns on the CLI)",
                    dropped.join(", "),
                    spec.name()
                )));
            }
            Ok(Some(content))
        }
    }
}

/// The address of a `nameserver` line.
fn nameserver_of(line: &str) -> Option<&str> {
    let mut words = line.split_whitespace();
    (words.next() == Some("nameserver"))
        .then(|| words.next())
        .flatten()
}

/// Whether a nameserver is somewhere other than the host's own stack.
fn reachable_from_vnet(server: &str) -> bool {
    // fe80::1%em0 names a host interface the container does not have.
    if server.contains('%') {
        return false;
    }
    server
        .parse::<IpAddr>()
        .map_or(true, |ip| !ip.is_loopback())
}

/// Lease an address on `network_name` and build the VNET interface pair.
fn setup_vnet(layout: &Layout, name: &str, network_name: &str) -> Result<network::VnetSetup> {
    let config = layout.state_config();
    let lease_store = network::NetworkLeaseStore::from_config(config);
    let (runtime_networks, mut allocator, _) = network::build_runtime_allocator(config)?;
    let runtime_network = runtime_networks
        .get(network_name)
        .cloned()
        .ok_or_else(|| Error::NetworkNotFound(network_name.to_string()))?;
    let bridge_name = runtime_network.bridge.clone().ok_or_else(|| {
        Error::Network(format!(
            "Network '{network_name}' exists but has no host bridge. Create it with 'blackship network create {network_name} ...'"
        ))
    })?;
    let ip = network::allocate_and_record(&mut allocator, &lease_store, network_name, name)?;

    let backend = match runtime_network.backend.as_str() {
        "netgraph" => network::vnet::NetworkBackend::Netgraph,
        _ => network::vnet::NetworkBackend::Epair,
    };
    let vnet_config = network::VnetConfig::new(
        bridge_name,
        format!("{}/{}", ip, runtime_network.subnet.prefix_len()),
        runtime_network.gateway,
    )
    .with_backend(backend);
    let setup = network::VnetSetup::create(name, vnet_config)?;
    let state_record = setup.state_record(name, Some(network_name));
    if let Err(e) = network::VnetStateStore::from_config(config).save(&state_record) {
        // Not recorded yet, so the teardown would not find it.
        let _ = setup.cleanup();
        return Err(e);
    }
    Ok(setup)
}

/// The jail(8) parameters for `spec` rooted at `root`.
fn jail_params(spec: &ContainerSpec, root: &Path) -> Vec<String> {
    let mut params = vec![
        format!("name={}", spec.name()),
        format!("path={}", root.display()),
        format!(
            "host.hostname={}",
            spec.hostname.as_deref().unwrap_or(&spec.name)
        ),
        // The handle, not a process, decides when the jail ends.
        "persist".to_string(),
        "mount.devfs".to_string(),
    ];
    match &spec.network {
        Network::None => {
            params.push("ip4=disable".to_string());
            params.push("ip6=disable".to_string());
        }
        Network::Inherit => {
            params.push("ip4=inherit".to_string());
            params.push("ip6=inherit".to_string());
        }
        Network::Vnet(_) => params.push("vnet".to_string()),
    }
    if spec.raw_sockets {
        params.push("allow.raw_sockets".to_string());
    }
    if spec.chflags {
        params.push("allow.chflags".to_string());
    }
    if spec.boot {
        params.push("exec.start=/bin/sh /etc/rc".to_string());
    }
    params.extend(spec.params.iter().cloned());
    params
}

fn start_jail(spec: &ContainerSpec, root: &Path) -> Result<()> {
    let output = Command::new("/usr/sbin/jail")
        .arg("-c")
        .args(jail_params(spec, root))
        .output()?;
    if output.status.success() {
        Ok(())
    } else {
        Err(Error::JailCreationFailed(format!(
            "jail -c {}: {}",
            spec.name(),
            String::from_utf8_lossy(&output.stderr).trim()
        )))
    }
}

#[cfg(test)]
mod tests;