Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
301781cdce
|
||
|
|
4c3aaefdd5 | ||
|
|
d314d6b3c2 | ||
|
|
e155900ddd | ||
|
|
c1da681b2c | ||
|
|
de47ac0d91 | ||
|
|
c8252d1040 |
No files matched your search
@@ -62,7 +62,9 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
|
||||
// On a Linux host, SIGTERM or SIGINT stops the agent as Shutdown does.
|
||||
let term = if host_process { Some(term_signals()?) } else { None };
|
||||
let mut bridges = Bridges::default();
|
||||
// In the VM, lookups the gateway's resolver fails go through the host.
|
||||
let mut dns = super::dns::Dns::default();
|
||||
dns.relay = !host_process;
|
||||
let forward = super::relay::listen()?;
|
||||
// host.docker.internal's relay to the Mac (VM only). A Linux host maps
|
||||
// that name to the bridge gateway and redirects nothing here, so the
|
||||
@@ -130,6 +132,10 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
|
||||
let wait = TTY_HUP_WAIT.as_millis() as i32;
|
||||
timeout = if timeout < 0 { wait } else { timeout.min(wait) };
|
||||
}
|
||||
let wait = dns.timeout_ms();
|
||||
if wait >= 0 {
|
||||
timeout = if timeout < 0 { wait } else { timeout.min(wait) };
|
||||
}
|
||||
// SAFETY: `fds` is a valid array of pollfd of the given length.
|
||||
let n = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout) };
|
||||
if n < 0 {
|
||||
@@ -157,6 +163,8 @@ pub fn serve(mut conn: File, paths: &Paths) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
dns.on_timer();
|
||||
|
||||
// Output and input first, so a process's last words go out before its exit.
|
||||
for pfd in &fds[3..] {
|
||||
if pfd.revents == 0 {
|
||||
|
||||
@@ -222,7 +222,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
|
||||
super::cgroup::apply_limits(&cgroup, &spec.limits).map_err(cleanup)?;
|
||||
}
|
||||
let cgroup_fd = fs::File::open(&cgroup).map_err(cleanup)?;
|
||||
let host = super::hostopts::parse(spec.opts).map_err(cleanup)?;
|
||||
let mut host = super::hostopts::parse(spec.opts).map_err(cleanup)?;
|
||||
if spec.flags & run_flags::NET_HOST != 0 && host.sysctls.iter().any(|s| s.ns == super::hostopts::Ns::Net) {
|
||||
return Err(cleanup(io::Error::new(io::ErrorKind::InvalidInput, "net.* sysctls are not allowed in the host network namespace")));
|
||||
}
|
||||
@@ -257,9 +257,16 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
|
||||
prepared.host = HostApplied { rlimits: host.rlimits.clone(), groups: host.groups.clone(), nodes };
|
||||
// Small, short-lived files: kept in memory (/run is tmpfs), not on the data disk.
|
||||
let etc_dir = PathBuf::from("/run/kiri").join(spec.id);
|
||||
let embedded_dns = embedded_dns(spec, net.upstream_dns);
|
||||
prepared.etc_files = write_etc_files(spec, &etc_dir, net.upstream_dns, embedded_dns).map_err(cleanup)?;
|
||||
let embedded_dns = embedded_dns(spec, net.upstream_dns, net.dns.relay);
|
||||
let nameserver = embedded_dns.then(|| embedded_address(spec, net.dns.relay));
|
||||
prepared.etc_files = write_etc_files(spec, &etc_dir, net.upstream_dns, nameserver).map_err(cleanup)?;
|
||||
prepared.mounts = parse_mounts(spec.mounts).map_err(cleanup)?;
|
||||
// A network namespace of its own gets Docker's two defaults: any port
|
||||
// and ping without root. Host networking, and `--network container:`
|
||||
// (that container already has them), keep what they have.
|
||||
if spec.flags & run_flags::NET_HOST == 0 && prepared.net_join.is_none() {
|
||||
super::hostopts::add_net_defaults(&mut host.sysctls);
|
||||
}
|
||||
let bridged = !spec.net.bridge.is_empty() && spec.flags & (run_flags::NET_HOST | run_flags::NET_NONE) == 0 && prepared.net_join.is_none();
|
||||
let mut go = None;
|
||||
// Sysctls are written from here once the namespaces exist: the child
|
||||
@@ -323,10 +330,15 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
|
||||
net.dns.serve(spec.net.bridge, spec.net.gateway).map_err(|e| kill_child(io::Error::new(e.kind(), format!("dns: {e}"))))?;
|
||||
net.dns.register(spec.net.bridge, spec.net.dns_names.iter(), spec.net.ip);
|
||||
}
|
||||
// 127.0.0.11 in the container, what its resolv.conf names.
|
||||
std::fs::File::open(format!("/proc/{pid}/ns/net"))
|
||||
.and_then(|ns| net.dns.serve_in(&ns, pid, spec.net.ip, spec.net.bridge))
|
||||
.map_err(|e| kill_child(io::Error::new(e.kind(), format!("dns: {e}"))))?;
|
||||
// 127.0.0.11 in the container, when its resolv.conf names it. Not
|
||||
// when it names the gateway (the default bridge in the VM): the
|
||||
// listener would only hold port 53, and a DNS server in the
|
||||
// container could not bind it.
|
||||
if nameserver == Some(super::dns::EMBEDDED) {
|
||||
std::fs::File::open(format!("/proc/{pid}/ns/net"))
|
||||
.and_then(|ns| net.dns.serve_in(&ns, pid, spec.net.ip, spec.net.bridge))
|
||||
.map_err(|e| kill_child(io::Error::new(e.kind(), format!("dns: {e}"))))?;
|
||||
}
|
||||
if let Some(v) = v6 {
|
||||
net.dns.register6(spec.net.bridge, spec.net.dns_names.iter(), spec.net.ip, v.ip);
|
||||
}
|
||||
@@ -483,14 +495,15 @@ pub fn oom_killed(p: &Process) -> bool {
|
||||
/// `netns_shared`: another live process still uses the container's network
|
||||
/// namespace (a container started with `--network container:`). Only then
|
||||
/// are its veths deleted here, or they would live on with that namespace
|
||||
/// and keep its address. Otherwise the kernel deletes them as the namespace
|
||||
/// goes, off the agent's loop: deleting one here waits out RCU, 15-40 ms of
|
||||
/// netlink that every request after the exit queued behind.
|
||||
/// and keep its address. Otherwise the next container to be plugged in
|
||||
/// deletes them (see `net::retire`).
|
||||
pub fn teardown(p: &Process, netns_shared: bool) {
|
||||
if netns_shared {
|
||||
for v in &p.veths {
|
||||
let _ = net::detach(v);
|
||||
}
|
||||
} else {
|
||||
net::retire(&p.veths);
|
||||
}
|
||||
if let Some(t) = &p.teardown {
|
||||
undo_now(t, t.remove);
|
||||
@@ -672,7 +685,7 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname:
|
||||
|
||||
/// Writes the container's /etc/hosts, /etc/resolv.conf and /etc/hostname
|
||||
/// beside its writable layer; the child binds them over the image's files.
|
||||
fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8; 4]], embedded_dns: bool) -> io::Result<Vec<(CString, CString)>> {
|
||||
fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8; 4]], embedded: Option<[u8; 4]>) -> io::Result<Vec<(CString, CString)>> {
|
||||
fs::create_dir_all(base)?;
|
||||
// `--network container:<id>` shares that container's files, as Docker does.
|
||||
if let Some(target) = net_opts::values(spec.net.opts, net_opts::NETNS).next() {
|
||||
@@ -719,7 +732,7 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8;
|
||||
}
|
||||
hosts.push('\n');
|
||||
}
|
||||
let resolv = resolv_conf(spec, upstream, embedded_dns);
|
||||
let resolv = resolv_conf(spec, upstream, embedded);
|
||||
let files = [("hosts", hosts), ("resolv.conf", resolv), ("hostname", format!("{}\n", spec.hostname))];
|
||||
let mut out = Vec::with_capacity(files.len());
|
||||
for (name, text) in files {
|
||||
@@ -736,23 +749,37 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8;
|
||||
/// `--dns-search` and `--dns-option` apply either way.
|
||||
/// Whether the container's DNS goes to the agent's resolver (127.0.0.11):
|
||||
/// on a user network, as Docker's embedded DNS; and on the default bridge
|
||||
/// when the host's resolver is one of its own addresses (net::local_resolver),
|
||||
/// unless the container names its own servers (`--dns`).
|
||||
fn embedded_dns(spec: &RunSpec<'_>, upstream: &[[u8; 4]]) -> bool {
|
||||
/// when the host's resolver is one of its own addresses (net::local_resolver)
|
||||
/// or, in the VM (`relay`), so that lookups the Mac's gateway resolver fails
|
||||
/// can go through the host (dns.rs), unless the container names its own
|
||||
/// servers (`--dns`).
|
||||
fn embedded_dns(spec: &RunSpec<'_>, upstream: &[[u8; 4]], relay: bool) -> bool {
|
||||
if spec.flags & run_flags::DNS_GATEWAY != 0 {
|
||||
return true;
|
||||
}
|
||||
let bridged = !spec.net.bridge.is_empty()
|
||||
&& spec.flags & (run_flags::NET_HOST | run_flags::NET_NONE) == 0
|
||||
&& net_opts::values(spec.net.opts, net_opts::NETNS).next().is_none();
|
||||
bridged && net_opts::values(spec.net.opts, net_opts::NAMESERVER).next().is_none() && net::local_resolver(upstream)
|
||||
bridged && net_opts::values(spec.net.opts, net_opts::NAMESERVER).next().is_none() && (relay || net::local_resolver(upstream))
|
||||
}
|
||||
|
||||
fn resolv_conf(spec: &RunSpec<'_>, upstream: &[[u8; 4]], embedded_dns: bool) -> String {
|
||||
/// The address a container that uses the agent's resolver names in its
|
||||
/// resolv.conf: 127.0.0.11 on a user network, as Docker's embedded DNS;
|
||||
/// on the default bridge in the VM, the bridge's gateway, where the agent
|
||||
/// answers too. Not a loopback address there, because what runs builds
|
||||
/// in a container takes loopback nameservers out of the copy it gives
|
||||
/// each step and puts Google's in their place (BuildKit does, for every
|
||||
/// step that isn't `--network=host`): those steps would ask 8.8.8.8, not
|
||||
/// the Mac's resolver, and VPN and company names would stop resolving.
|
||||
fn embedded_address(spec: &RunSpec<'_>, relay: bool) -> [u8; 4] {
|
||||
if relay && spec.flags & run_flags::DNS_GATEWAY == 0 && spec.net.gateway != [0; 4] { spec.net.gateway } else { super::dns::EMBEDDED }
|
||||
}
|
||||
|
||||
fn resolv_conf(spec: &RunSpec<'_>, upstream: &[[u8; 4]], embedded: Option<[u8; 4]>) -> String {
|
||||
let mut resolv = String::new();
|
||||
let mut servers = net_opts::values(spec.net.opts, net_opts::NAMESERVER).peekable();
|
||||
if embedded_dns {
|
||||
resolv.push_str(&format!("nameserver {}\n", net::ip_str(super::dns::EMBEDDED)));
|
||||
if let Some(ns) = embedded {
|
||||
resolv.push_str(&format!("nameserver {}\n", net::ip_str(ns)));
|
||||
} else if servers.peek().is_some() {
|
||||
for d in servers {
|
||||
resolv.push_str(&format!("nameserver {d}\n"));
|
||||
@@ -1200,7 +1227,22 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()
|
||||
(c"/proc/self/fd/2", c"dev/stderr"),
|
||||
(c"pts/ptmx", c"dev/ptmx"),
|
||||
] {
|
||||
// SAFETY: valid NUL-terminated strings; devtmpfs may have some.
|
||||
if privileged {
|
||||
// devtmpfs is one filesystem for the whole kernel: this dev is the
|
||||
// VM's /dev, and on a Linux host, where there is no VM, the host's
|
||||
// own. Replacing its ptmx with a link to pts/ptmx (mode 000 in the
|
||||
// host's devpts) stopped every new terminal on the host. Nothing
|
||||
// there is changed, only what is missing is added: the real ptmx
|
||||
// (5:2) opens the devpts mounted beside it at dev/pts below, so
|
||||
// the container still gets its own ptys (Linux 4.7 and later).
|
||||
if link == c"dev/ptmx" || fs::symlink_metadata(Path::new(std::ffi::OsStr::from_bytes(link.to_bytes()))).is_ok() {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: valid NUL-terminated strings.
|
||||
unsafe { libc::symlink(target.as_ptr(), link.as_ptr()) };
|
||||
continue;
|
||||
}
|
||||
// SAFETY: valid NUL-terminated strings.
|
||||
unsafe {
|
||||
libc::unlink(link.as_ptr());
|
||||
libc::symlink(target.as_ptr(), link.as_ptr())
|
||||
@@ -1360,7 +1402,7 @@ mod tests {
|
||||
let net = Net { bridge: "kiri1", ip: [10, 5, 0, 2], prefix: 24, gateway: [10, 5, 0, 1], extra_hosts: &[], dns_names: &[], opts };
|
||||
encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", flags, net, &[], &Limits::default(), 0, &[] as &[&str]);
|
||||
let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
|
||||
super::resolv_conf(&spec, upstream, flags & run_flags::DNS_GATEWAY != 0)
|
||||
super::resolv_conf(&spec, upstream, (flags & run_flags::DNS_GATEWAY != 0).then_some(super::super::dns::EMBEDDED))
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1380,8 +1422,30 @@ mod tests {
|
||||
encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &[] as &[&str]);
|
||||
let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
|
||||
// TEST-NET-3: no machine running the tests has it.
|
||||
assert!(!super::embedded_dns(&spec, &[[203, 0, 113, 53]]), "a resolver elsewhere is asked directly");
|
||||
assert!(!super::embedded_dns(&spec, &[]), "no resolver: the public fallback, not the agent");
|
||||
assert!(!super::embedded_dns(&spec, &[[203, 0, 113, 53]], false), "a resolver elsewhere is asked directly");
|
||||
assert!(!super::embedded_dns(&spec, &[], false), "no resolver: the public fallback, not the agent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_the_vm_the_default_bridge_goes_through_the_agent() {
|
||||
let spec_with = |flags: u32, opts: &[&str], f: &dyn Fn(&kiri_proto::RunSpec<'_>)| {
|
||||
let mut buf = Vec::new();
|
||||
let net = Net { bridge: "kiri0", ip: [172, 17, 0, 2], prefix: 16, gateway: [172, 17, 0, 1], extra_hosts: &[], dns_names: &[], opts };
|
||||
encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", flags, net, &[], &Limits::default(), 0, &[] as &[&str]);
|
||||
let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
|
||||
f(&spec);
|
||||
};
|
||||
let gateway = [[192, 168, 64, 1]];
|
||||
spec_with(0, &[], &|s| assert!(super::embedded_dns(s, &gateway, true), "so a refused gateway can fall back to the host"));
|
||||
spec_with(0, &["nameserver=8.8.8.8"], &|s| assert!(!super::embedded_dns(s, &gateway, true), "--dns servers are asked directly"));
|
||||
spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking keeps the VM's resolv.conf"));
|
||||
// Named by the bridge's gateway, not 127.0.0.11: builders keep it
|
||||
// for their steps rather than swapping in 8.8.8.8.
|
||||
spec_with(0, &[], &|s| assert_eq!(super::embedded_address(s, true), [172, 17, 0, 1]));
|
||||
spec_with(0, &[], &|s| assert_eq!(super::resolv_conf(s, &gateway, Some(super::embedded_address(s, true))), "nameserver 172.17.0.1\n"));
|
||||
// A user network keeps Docker's 127.0.0.11, as does a Linux host.
|
||||
spec_with(run_flags::DNS_GATEWAY, &[], &|s| assert_eq!(super::embedded_address(s, true), super::super::dns::EMBEDDED));
|
||||
spec_with(0, &[], &|s| assert_eq!(super::embedded_address(s, false), super::super::dns::EMBEDDED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -6,6 +6,15 @@
|
||||
//! forwarded to the VM's upstream resolver (or the container's own `--dns`
|
||||
//! servers) and the answer relayed back. The 127.0.0.11 socket is opened in
|
||||
//! the container's namespace by this agent, so no process runs in there.
|
||||
//!
|
||||
//! In the VM the upstream is the Mac's resolver for the NAT network, at its
|
||||
//! gateway (192.168.64.1). macOS doesn't always answer there: after a
|
||||
//! network change, sleep or a VPN, lookups are refused or go unanswered
|
||||
//! while the Mac itself resolves fine. So a lookup the gateway refuses, or
|
||||
//! leaves unanswered for `FALLBACK_AFTER`, is asked again through the Kiri
|
||||
//! daemon on the Mac, over vsock, which asks the Mac's own resolvers
|
||||
//! (crates/kiri/src/daemon/dns.rs). A container's own `--dns` servers are
|
||||
//! never second-guessed.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Read};
|
||||
@@ -24,6 +33,21 @@ const FORWARD_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// At most this many forwarded queries in flight (each has its own socket);
|
||||
/// more are dropped, and the client asks again.
|
||||
const MAX_PENDING: usize = 256;
|
||||
/// At most this many of them from one container (or one address on a
|
||||
/// bridge), so a container flooding lookups can't take DNS from the rest.
|
||||
const MAX_PER_CLIENT: usize = 64;
|
||||
/// How long the agent's loop may wait for the host to take a relayed
|
||||
/// lookup's connection.
|
||||
const RELAY_CONNECT: Duration = Duration::from_millis(250);
|
||||
/// After the host failed to take one, lookups aren't relayed for this long:
|
||||
/// each would stall the loop for `RELAY_CONNECT` again.
|
||||
const RELAY_BACKOFF: Duration = Duration::from_secs(5);
|
||||
/// A lookup the VM's resolver hasn't answered within this goes through the
|
||||
/// host (VM only). Gateway answers take milliseconds; a slow recursive one
|
||||
/// that loses the race is simply replaced by the host's.
|
||||
const FALLBACK_AFTER: Duration = Duration::from_secs(1);
|
||||
/// Largest reply the host relay may send (a DNS over TCP frame's limit).
|
||||
const MAX_RELAYED: usize = 2 + 65_535;
|
||||
|
||||
/// Docker's embedded DNS address, inside each container.
|
||||
pub const EMBEDDED: [u8; 4] = [127, 0, 0, 11];
|
||||
@@ -42,16 +66,26 @@ struct Pending {
|
||||
/// Its own socket, connected to the resolver: a fresh source port for
|
||||
/// every query, as Docker's embedded DNS does, so one lost or blocked
|
||||
/// flow doesn't take the resolver away from every later query, and an
|
||||
/// answer has to guess the port as well as the ID.
|
||||
/// answer has to guess the port as well as the ID. Once the query goes
|
||||
/// through the host, the vsock stream to it instead.
|
||||
sock: OwnedFd,
|
||||
/// The ID it went out with.
|
||||
our: u16,
|
||||
/// Who asked, for `MAX_PER_CLIENT`: the container's address.
|
||||
key: [u8; 4],
|
||||
/// The server's socket the query came in on.
|
||||
server: RawFd,
|
||||
client: libc::sockaddr_in,
|
||||
id: u16,
|
||||
question: Vec<u8>,
|
||||
sent: Instant,
|
||||
/// The query as sent (with `our` ID), to send again through the host.
|
||||
query: Vec<u8>,
|
||||
/// It may still go through the host: in the VM, asked of the VM's own
|
||||
/// resolver (not `--dns` servers), and not tried there yet.
|
||||
may_relay: bool,
|
||||
/// Sent through the host: the reply's bytes so far, `u16 len | reply`.
|
||||
relayed: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// One name's IPv6 addresses, each with its container's IPv4 address.
|
||||
@@ -68,6 +102,11 @@ pub struct Dns {
|
||||
/// Container address → its `--dns` servers, used instead of the VM's.
|
||||
clients: HashMap<[u8; 4], Vec<[u8; 4]>>,
|
||||
pending: Vec<Pending>,
|
||||
/// Lookups the VM's resolver fails go through the host (in the VM; a
|
||||
/// Linux host's agent asks the host's resolvers itself).
|
||||
pub relay: bool,
|
||||
/// The host didn't take a relayed lookup: none are tried until then.
|
||||
relay_down_until: Option<Instant>,
|
||||
}
|
||||
|
||||
fn udp_socket() -> io::Result<OwnedFd> {
|
||||
@@ -220,21 +259,27 @@ impl Dns {
|
||||
pub fn on_readable(&mut self, fd: RawFd, upstream: &[[u8; 4]]) {
|
||||
let mut buf = [0u8; 1500];
|
||||
if let Some(at) = self.pending.iter().position(|p| p.sock.as_raw_fd() == fd) {
|
||||
if self.pending[at].relayed.is_some() {
|
||||
self.read_relayed(at);
|
||||
return;
|
||||
}
|
||||
// A forwarded answer: hand it back to whoever asked.
|
||||
loop {
|
||||
// SAFETY: receiving into a buffer we own.
|
||||
let n = unsafe { libc::recv(fd, buf.as_mut_ptr().cast(), buf.len(), 0) };
|
||||
if n < 0 && io::Error::last_os_error().raw_os_error() == Some(libc::ECONNREFUSED) {
|
||||
// Nothing listens at the resolver: ask the host now
|
||||
// rather than wait for the client to give up.
|
||||
self.relay(at);
|
||||
break;
|
||||
}
|
||||
if n < 12 {
|
||||
break;
|
||||
}
|
||||
let msg = &mut buf[..n as usize];
|
||||
let p = &self.pending[at];
|
||||
if u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(msg, p) {
|
||||
let p = self.pending.swap_remove(at);
|
||||
msg[0..2].copy_from_slice(&p.id.to_be_bytes());
|
||||
if let Some(s) = self.servers.iter().find(|s| s.sock.as_raw_fd() == p.server) {
|
||||
send_to(s.sock.as_raw_fd(), msg, &p.client);
|
||||
}
|
||||
self.answered(at, msg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -309,31 +354,180 @@ impl Dns {
|
||||
let now = Instant::now();
|
||||
self.pending.retain(|p| now.duration_since(p.sent) < FORWARD_TIMEOUT);
|
||||
let key = self.servers[server].container.map_or(client.sin_addr.s_addr.to_ne_bytes(), |(_, owner)| owner);
|
||||
let own = self.clients.get(&key).and_then(|v| v.first());
|
||||
let Some(dest) = own.or(upstream.first()).copied() else { return };
|
||||
if self.pending.len() >= MAX_PENDING {
|
||||
let own = self.clients.get(&key).and_then(|v| v.first()).copied();
|
||||
if self.pending.len() >= MAX_PENDING || self.pending.iter().filter(|p| p.key == key).count() >= MAX_PER_CLIENT {
|
||||
return;
|
||||
}
|
||||
let Some((_, _, end)) = parse_question(q) else {
|
||||
return;
|
||||
};
|
||||
let Ok(sock) = udp_socket() else { return };
|
||||
let to = sockaddr(dest, 53);
|
||||
// Connected, so it only receives datagrams from this resolver.
|
||||
// SAFETY: connecting to a valid sockaddr_in.
|
||||
if unsafe { libc::connect(sock.as_raw_fd(), (&to as *const libc::sockaddr_in).cast(), std::mem::size_of::<libc::sockaddr_in>() as u32) } != 0 {
|
||||
return;
|
||||
}
|
||||
let Some(our) = random_id() else { return };
|
||||
let mut msg = q.to_vec();
|
||||
let id = u16::from_be_bytes([msg[0], msg[1]]);
|
||||
msg[0..2].copy_from_slice(&our.to_be_bytes());
|
||||
// SAFETY: sending a buffer we own on a connected socket.
|
||||
if unsafe { libc::send(sock.as_raw_fd(), msg.as_ptr().cast(), msg.len(), 0) } < 0 {
|
||||
let may_relay = self.relay && own.is_none();
|
||||
let dest = own.or(upstream.first().copied());
|
||||
// No resolver yet, or it can't be reached: the host, if allowed.
|
||||
let (sock, relayed) = match dest.and_then(|d| ask(d, &msg)) {
|
||||
Some(s) => (s, false),
|
||||
None if may_relay => match self.relay_stream(&msg) {
|
||||
Some(s) => (s, true),
|
||||
None => return,
|
||||
},
|
||||
None => return,
|
||||
};
|
||||
let p = Pending {
|
||||
sock,
|
||||
our,
|
||||
key,
|
||||
server: self.servers[server].sock.as_raw_fd(),
|
||||
client,
|
||||
id,
|
||||
question: q[12..end].to_vec(),
|
||||
sent: now,
|
||||
query: msg,
|
||||
may_relay: may_relay && !relayed,
|
||||
relayed: relayed.then(Vec::new),
|
||||
};
|
||||
self.pending.push(p);
|
||||
}
|
||||
|
||||
/// Hands a matching answer to whoever asked, and forgets the query.
|
||||
fn answered(&mut self, at: usize, msg: &mut [u8]) {
|
||||
let p = self.pending.swap_remove(at);
|
||||
msg[0..2].copy_from_slice(&p.id.to_be_bytes());
|
||||
if let Some(s) = self.servers.iter().find(|s| s.sock.as_raw_fd() == p.server) {
|
||||
send_to(s.sock.as_raw_fd(), msg, &p.client);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends pending query `at` again, through the host, once.
|
||||
fn relay(&mut self, at: usize) {
|
||||
if !self.pending[at].may_relay {
|
||||
return;
|
||||
}
|
||||
self.pending.push(Pending { sock, our, server: self.servers[server].sock.as_raw_fd(), client, id, question: q[12..end].to_vec(), sent: now });
|
||||
self.pending[at].may_relay = false;
|
||||
let query = std::mem::take(&mut self.pending[at].query);
|
||||
let stream = self.relay_stream(&query);
|
||||
let p = &mut self.pending[at];
|
||||
p.query = query;
|
||||
if let Some(stream) = stream {
|
||||
p.sock = stream;
|
||||
p.relayed = Some(Vec::new());
|
||||
p.sent = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the host's reply to query `at` as it arrives.
|
||||
fn read_relayed(&mut self, at: usize) {
|
||||
let fd = self.pending[at].sock.as_raw_fd();
|
||||
let mut buf = [0u8; 4096];
|
||||
let mut eof = false;
|
||||
loop {
|
||||
// SAFETY: reading into a buffer we own.
|
||||
let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
|
||||
if n > 0 {
|
||||
let got = self.pending[at].relayed.get_or_insert_with(Vec::new);
|
||||
got.extend_from_slice(&buf[..n as usize]);
|
||||
if got.len() > MAX_RELAYED {
|
||||
eof = true;
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if n < 0 && io::Error::last_os_error().kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
eof = true;
|
||||
break;
|
||||
}
|
||||
let got = self.pending[at].relayed.take().unwrap_or_default();
|
||||
match framed_reply(&got) {
|
||||
Some(reply) => {
|
||||
let mut msg = reply.to_vec();
|
||||
let p = &self.pending[at];
|
||||
if msg.len() >= 12 && u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(&msg, p) {
|
||||
self.answered(at, &mut msg);
|
||||
} else {
|
||||
self.pending.swap_remove(at);
|
||||
}
|
||||
}
|
||||
// Gone before a whole reply: the client asks again.
|
||||
None if eof => {
|
||||
self.pending.swap_remove(at);
|
||||
}
|
||||
None => self.pending[at].relayed = Some(got),
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream to the host's DNS relay with `msg` sent on it, non-blocking
|
||||
/// for the reply; None while the host is taken for down.
|
||||
fn relay_stream(&mut self, msg: &[u8]) -> Option<OwnedFd> {
|
||||
if self.relay_down_until.is_some_and(|t| Instant::now() < t) {
|
||||
return None;
|
||||
}
|
||||
let Ok(stream) = super::transport::dial_within(kiri_proto::DNS_RELAY_PORT, RELAY_CONNECT) else {
|
||||
self.relay_down_until = Some(Instant::now() + RELAY_BACKOFF);
|
||||
return None;
|
||||
};
|
||||
self.relay_down_until = None;
|
||||
let mut frame = Vec::with_capacity(2 + msg.len());
|
||||
frame.extend_from_slice(&u16::try_from(msg.len()).ok()?.to_be_bytes());
|
||||
frame.extend_from_slice(msg);
|
||||
// A few hundred bytes on a fresh stream: one write, never short.
|
||||
// SAFETY: writing a buffer we own to a socket we own.
|
||||
if unsafe { libc::write(stream.as_raw_fd(), frame.as_ptr().cast(), frame.len()) } != frame.len() as isize {
|
||||
return None;
|
||||
}
|
||||
sys::set_nonblocking(stream.as_raw_fd()).ok()?;
|
||||
Some(stream)
|
||||
}
|
||||
|
||||
/// Sends lookups the VM's resolver has left unanswered too long
|
||||
/// through the host. Called on every turn of the agent's loop.
|
||||
pub fn on_timer(&mut self) {
|
||||
let now = Instant::now();
|
||||
for at in 0..self.pending.len() {
|
||||
let p = &self.pending[at];
|
||||
if p.may_relay && now.duration_since(p.sent) >= FALLBACK_AFTER {
|
||||
self.relay(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Milliseconds until `on_timer` has something to do; -1 for never.
|
||||
pub fn timeout_ms(&self) -> i32 {
|
||||
let now = Instant::now();
|
||||
self.pending
|
||||
.iter()
|
||||
.filter(|p| p.may_relay)
|
||||
.map(|p| FALLBACK_AFTER.saturating_sub(now.duration_since(p.sent)).as_millis().min(i32::MAX as u128) as i32)
|
||||
.min()
|
||||
.unwrap_or(-1)
|
||||
}
|
||||
}
|
||||
|
||||
/// A UDP socket connected to `dest`:53 with `msg` sent on it, or None if
|
||||
/// it couldn't be sent (no route, the network down).
|
||||
fn ask(dest: [u8; 4], msg: &[u8]) -> Option<OwnedFd> {
|
||||
let sock = udp_socket().ok()?;
|
||||
let to = sockaddr(dest, 53);
|
||||
// Connected, so it only receives datagrams from this resolver.
|
||||
// SAFETY: connecting to a valid sockaddr_in.
|
||||
if unsafe { libc::connect(sock.as_raw_fd(), (&to as *const libc::sockaddr_in).cast(), std::mem::size_of::<libc::sockaddr_in>() as u32) } != 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: sending a buffer we own on a connected socket.
|
||||
if unsafe { libc::send(sock.as_raw_fd(), msg.as_ptr().cast(), msg.len(), 0) } < 0 {
|
||||
return None;
|
||||
}
|
||||
Some(sock)
|
||||
}
|
||||
|
||||
/// The reply in `u16 len | reply`, once all of it is there.
|
||||
fn framed_reply(got: &[u8]) -> Option<&[u8]> {
|
||||
let len = u16::from_be_bytes([*got.first()?, *got.get(1)?]) as usize;
|
||||
got.get(2..2 + len)
|
||||
}
|
||||
|
||||
/// A UDP socket bound to `ip`:53.
|
||||
@@ -555,14 +749,119 @@ mod tests {
|
||||
Pending {
|
||||
sock: udp_socket().unwrap(),
|
||||
our: 1,
|
||||
key: [0; 4],
|
||||
server: -1,
|
||||
client: unsafe { std::mem::zeroed() },
|
||||
id: 7,
|
||||
question: b"\x03www\x07example\x03com\x00\x00\x01\x00\x01".to_vec(),
|
||||
sent: Instant::now(),
|
||||
query: Vec::new(),
|
||||
may_relay: false,
|
||||
relayed: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_client_cant_take_every_forwarded_slot() {
|
||||
let mut dns = Dns::default();
|
||||
dns.servers.push(Server { bridges: vec!["kiri0".into()], sock: udp_socket().unwrap(), container: None });
|
||||
let client = super::sockaddr([172, 17, 0, 2], 4000);
|
||||
for _ in 0..super::MAX_PER_CLIENT {
|
||||
let mut p = pending();
|
||||
p.key = [172, 17, 0, 2];
|
||||
dns.pending.push(p);
|
||||
}
|
||||
let q = query("example.com", 1);
|
||||
// Loopback as the resolver: sending always works.
|
||||
dns.forward(0, &q, client, &[[127, 0, 0, 1]]);
|
||||
assert_eq!(dns.pending.len(), super::MAX_PER_CLIENT, "that container's next lookup waits");
|
||||
dns.forward(0, &q, super::sockaddr([172, 17, 0, 3], 4000), &[[127, 0, 0, 1]]);
|
||||
assert_eq!(dns.pending.len(), super::MAX_PER_CLIENT + 1, "another container's goes out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_that_didnt_answer_isnt_dialled_again_at_once() {
|
||||
let mut dns = Dns { relay: true, ..Default::default() };
|
||||
// No host to dial in a test: the first try fails and backs off.
|
||||
assert!(dns.relay_stream(b"query").is_none());
|
||||
let until = dns.relay_down_until.expect("backing off");
|
||||
assert!(until > Instant::now());
|
||||
assert!(dns.relay_stream(b"query").is_none());
|
||||
assert_eq!(dns.relay_down_until, Some(until), "not tried again while backing off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relayed_reply_is_whole_only_once_its_length_is_there() {
|
||||
use super::framed_reply;
|
||||
assert_eq!(framed_reply(&[]), None);
|
||||
assert_eq!(framed_reply(&[0]), None);
|
||||
assert_eq!(framed_reply(&[0, 3, 1, 2]), None);
|
||||
assert_eq!(framed_reply(&[0, 3, 1, 2, 3]), Some(&[1u8, 2, 3][..]));
|
||||
assert_eq!(framed_reply(&[0, 0]), Some(&[][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_lookups_the_vm_resolver_may_miss_wait_for_the_host() {
|
||||
let mut dns = Dns::default();
|
||||
assert_eq!(dns.timeout_ms(), -1, "nothing pending");
|
||||
dns.pending.push(pending());
|
||||
assert_eq!(dns.timeout_ms(), -1, "--dns servers are not second-guessed");
|
||||
let mut p = pending();
|
||||
p.may_relay = true;
|
||||
dns.pending.push(p);
|
||||
let t = dns.timeout_ms();
|
||||
assert!((0..=1000).contains(&t), "{t}");
|
||||
// Past the wait it is tried through the host once, whatever comes of it.
|
||||
dns.pending[1].sent = Instant::now() - super::FALLBACK_AFTER;
|
||||
assert_eq!(dns.timeout_ms(), 0);
|
||||
dns.on_timer();
|
||||
assert!(!dns.pending[1].may_relay);
|
||||
assert_eq!(dns.timeout_ms(), -1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hosts_reply_goes_back_to_whoever_asked() {
|
||||
use std::net::UdpSocket;
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
||||
let client = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
client.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap();
|
||||
let std::net::SocketAddr::V4(addr) = client.local_addr().unwrap() else { panic!() };
|
||||
let mut dns = Dns::default();
|
||||
dns.servers.push(Server { bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None });
|
||||
let mut fds = [0; 2];
|
||||
// SAFETY: `fds` has room for the pair.
|
||||
assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds.as_mut_ptr()) }, 0);
|
||||
// SAFETY: fresh descriptors from socketpair.
|
||||
let (ours, host) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) };
|
||||
let mut p = pending();
|
||||
p.sock = ours;
|
||||
p.server = dns.servers[0].sock.as_raw_fd();
|
||||
p.client = super::sockaddr(addr.ip().octets(), addr.port());
|
||||
p.relayed = Some(Vec::new());
|
||||
let question = p.question.clone();
|
||||
dns.pending.push(p);
|
||||
let mut reply = vec![0, 1, 0x81, 0x80, 0, 1, 0, 0, 0, 0, 0, 0];
|
||||
reply.extend_from_slice(&question);
|
||||
let mut frame = (reply.len() as u16).to_be_bytes().to_vec();
|
||||
frame.extend_from_slice(&reply);
|
||||
let send = |b: &[u8]| {
|
||||
// SAFETY: writing a buffer we own to our end of the pair.
|
||||
assert_eq!(unsafe { libc::write(host.as_raw_fd(), b.as_ptr().cast(), b.len()) }, b.len() as isize)
|
||||
};
|
||||
// Half a reply waits for the rest.
|
||||
send(&frame[..5]);
|
||||
let fd = dns.pending[0].sock.as_raw_fd();
|
||||
dns.on_readable(fd, &[]);
|
||||
assert_eq!(dns.pending.len(), 1);
|
||||
send(&frame[5..]);
|
||||
dns.on_readable(fd, &[]);
|
||||
assert!(dns.pending.is_empty());
|
||||
let mut buf = [0u8; 512];
|
||||
let n = client.recv(&mut buf).unwrap();
|
||||
assert_eq!(&buf[..2], &[0, 7], "the client's own ID");
|
||||
assert_eq!(&buf[2..n], &reply[2..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_must_match_the_whole_question() {
|
||||
let p = pending();
|
||||
|
||||
@@ -183,6 +183,23 @@ pub fn make_nodes(root: BorrowedFd<'_>, nodes: &[Node]) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What Docker writes in every container with a network namespace of its
|
||||
/// own: a non-root process may listen on any port (nginx or Caddy on 80 as
|
||||
/// a user) and ping without CAP_NET_RAW. A `--sysctl` for the same key
|
||||
/// wins, as it does on Docker.
|
||||
const NET_DEFAULTS: [(&str, &str); 2] = [("net/ipv4/ip_unprivileged_port_start", "0"), ("net/ipv4/ping_group_range", "0 2147483647")];
|
||||
|
||||
/// Puts Docker's defaults first in `sysctls`, leaving out any key the
|
||||
/// container sets itself.
|
||||
pub fn add_net_defaults(sysctls: &mut Vec<Sysctl>) {
|
||||
let defaults = NET_DEFAULTS
|
||||
.iter()
|
||||
.filter(|(path, _)| !sysctls.iter().any(|s| s.path == *path))
|
||||
.map(|(path, value)| Sysctl { ns: Ns::Net, path: (*path).to_owned(), value: (*value).to_owned() });
|
||||
let mine: Vec<Sysctl> = defaults.collect();
|
||||
sysctls.splice(0..0, mine);
|
||||
}
|
||||
|
||||
/// Writes the sysctls from the agent, inside the container's namespaces:
|
||||
/// /proc/sys shows the calling task's network, IPC and UTS namespace, so
|
||||
/// the agent joins the one each key belongs to, writes, and comes back.
|
||||
@@ -302,6 +319,18 @@ mod tests {
|
||||
buf
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_container_gets_dockers_port_and_ping_defaults_unless_it_sets_them() {
|
||||
let mut none = Vec::new();
|
||||
add_net_defaults(&mut none);
|
||||
let keys: Vec<(&str, &str)> = none.iter().map(|s| (s.path.as_str(), s.value.as_str())).collect();
|
||||
assert_eq!(keys, [("net/ipv4/ip_unprivileged_port_start", "0"), ("net/ipv4/ping_group_range", "0 2147483647")]);
|
||||
let mut own = vec![Sysctl { ns: Ns::Net, path: "net/ipv4/ip_unprivileged_port_start".into(), value: "1024".into() }];
|
||||
add_net_defaults(&mut own);
|
||||
let keys: Vec<(&str, &str)> = own.iter().map(|s| (s.path.as_str(), s.value.as_str())).collect();
|
||||
assert_eq!(keys, [("net/ipv4/ping_group_range", "0 2147483647"), ("net/ipv4/ip_unprivileged_port_start", "1024")], "--sysctl wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_refuses() {
|
||||
let buf = list(&["rlimit\t7\t65536\t65536", "sysctl\tnet\tnet/core/somaxconn\t1024", "device\t/dev/fuse\t/dev/fuse\trwm", "devrule\tc\t10\t229\trwm", "group\tvideo"]);
|
||||
|
||||
@@ -659,6 +659,8 @@ pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc:
|
||||
let bridge_index = bridges.ensure(bridge, (!no_ipv4).then_some(gateway), prefix, v6)?;
|
||||
let netns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?;
|
||||
let mut host = Netlink::open(libc::NETLINK_ROUTE)?;
|
||||
// A stopped container's veth may still hold this address and MAC.
|
||||
delete_retired(&mut host);
|
||||
let ifname = format!("eth{n}");
|
||||
netlink::create_veth(&mut host, host_ifname, bridge_index, &netns, CONTAINER_MTU, &ifname, mac)?;
|
||||
// By name: a new namespace may have tunl0, gre0 … before it.
|
||||
@@ -686,6 +688,29 @@ pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Host-side veths of stopped containers, deleted by the next `attach`.
|
||||
static RETIRED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// Notes a stopped container's host-side veths for the next `attach` to
|
||||
/// delete. Deleting one waits out RCU, 15-40 ms that every request after
|
||||
/// the exit would queue behind on the agent's loop; and the agent stays
|
||||
/// single-threaded, as clone3 without CLONE_VM needs. Left to the kernel
|
||||
/// they went only as the namespace did, a second or more later: by then the
|
||||
/// next container had the same address and MAC, the bridge sent its replies
|
||||
/// to the old namespace, and that answered with resets (a download that
|
||||
/// broke mid-TLS or stalled).
|
||||
pub fn retire(veths: &[String]) {
|
||||
RETIRED.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(veths);
|
||||
}
|
||||
|
||||
/// Deletes the veths `retire` noted. Gone already (the kernel took them
|
||||
/// with their namespace) is fine.
|
||||
fn delete_retired(nl: &mut Netlink) {
|
||||
for v in std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())) {
|
||||
let _ = netlink::delete_link(nl, &v);
|
||||
}
|
||||
}
|
||||
|
||||
/// Unplugs a container's extra network by its host-side veth.
|
||||
pub fn detach(host_ifname: &str) -> io::Result<()> {
|
||||
let mut host = Netlink::open(libc::NETLINK_ROUTE)?;
|
||||
|
||||
@@ -181,16 +181,48 @@ fn ifinfo(index: i32, flags: u32, change: u32) -> [u8; 16] {
|
||||
b
|
||||
}
|
||||
|
||||
/// Creates bridge `name` with a MAC address of its own. Without one a Linux
|
||||
/// bridge takes the lowest address among its ports, so the gateway's MAC
|
||||
/// changed whenever a container joined or left: every other container's ARP
|
||||
/// entry for it went stale, and their connections stalled, were reset or
|
||||
/// broke mid-TLS until it was asked again. Docker gives its bridges an
|
||||
/// address for the same reason. A bridge left by an earlier run without
|
||||
/// one (a Linux host) gets one too.
|
||||
pub fn create_bridge(nl: &mut Netlink, name: &str) -> io::Result<()> {
|
||||
let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL);
|
||||
m.raw(&ifinfo(0, 0, 0)).attr_str(IFLA_IFNAME, name);
|
||||
m.nest(IFLA_LINKINFO).attr_str(IFLA_INFO_KIND, "bridge").end();
|
||||
match nl.request(&mut [m]) {
|
||||
Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
|
||||
match nl.request(&mut [new_bridge(name, bridge_mac(random_bytes()))]) {
|
||||
Err(e) if e.raw_os_error() == Some(libc::EEXIST) => {
|
||||
// NET_ADDR_SET (3): someone set it, so it no longer follows the ports.
|
||||
let kind = std::fs::read_to_string(format!("/sys/class/net/{name}/addr_assign_type")).unwrap_or_default();
|
||||
if kind.trim() == "3" {
|
||||
return Ok(());
|
||||
}
|
||||
let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK);
|
||||
m.raw(&ifinfo(index_of(name)?, 0, 0)).attr(IFLA_ADDRESS, &bridge_mac(random_bytes()));
|
||||
nl.request(&mut [m])
|
||||
}
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_bridge(name: &str, mac: [u8; 6]) -> Msg {
|
||||
let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL);
|
||||
m.raw(&ifinfo(0, 0, 0)).attr_str(IFLA_IFNAME, name).attr(IFLA_ADDRESS, &mac);
|
||||
m.nest(IFLA_LINKINFO).attr_str(IFLA_INFO_KIND, "bridge").end();
|
||||
m
|
||||
}
|
||||
|
||||
/// `b` as a locally administered unicast MAC address.
|
||||
fn bridge_mac(mut b: [u8; 6]) -> [u8; 6] {
|
||||
b[0] = (b[0] & 0xfc) | 0x02;
|
||||
b
|
||||
}
|
||||
|
||||
fn random_bytes() -> [u8; 6] {
|
||||
let mut b = [0u8; 6];
|
||||
let _ = std::fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut b));
|
||||
b
|
||||
}
|
||||
|
||||
/// Creates a veth pair: `host` stays here, attached to `bridge` and up; its
|
||||
/// peer is created straight inside `netns` as `peer`. The kernel picks the
|
||||
/// peer's interface index: a new namespace is not always only lo (with ipip
|
||||
@@ -884,6 +916,18 @@ mod tests {
|
||||
u32::from_be_bytes(d.try_into().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bridge_is_made_with_a_mac_address_of_its_own() {
|
||||
let m = new_bridge("kiri0", bridge_mac([0xff; 6]));
|
||||
let a = attrs(&m.buf[32..]); // nlmsghdr, ifinfomsg
|
||||
assert_eq!(get(&a, IFLA_ADDRESS), &[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
assert_eq!(get(&a, IFLA_IFNAME), b"kiri0\0");
|
||||
// Locally administered, never multicast.
|
||||
for b in [[0u8; 6], [0x01; 6], [0xff; 6]] {
|
||||
assert_eq!(bridge_mac(b)[0] & 0x03, 0x02);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rule's expressions: (name, its NFTA_EXPR_DATA attributes).
|
||||
fn exprs(m: &Msg) -> Vec<(String, Vec<(u16, &[u8])>)> {
|
||||
let top = attrs(&m.buf[20..]); // nlmsghdr, nfgenmsg
|
||||
|
||||
@@ -85,6 +85,35 @@ pub fn dial(port: u32) -> io::Result<OwnedFd> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `SO_VM_SOCKETS_CONNECT_TIMEOUT` (linux/vm_sockets.h, the `_OLD` value,
|
||||
/// which takes a native `timeval`; libc doesn't name it).
|
||||
const SO_VM_SOCKETS_CONNECT_TIMEOUT: libc::c_int = 6;
|
||||
|
||||
/// Like `dial`, but a connection the host doesn't take within `timeout`
|
||||
/// fails (vsock waits two seconds by default), for callers in the agent's
|
||||
/// loop, which nothing else runs in while it waits.
|
||||
pub fn dial_within(port: u32, timeout: std::time::Duration) -> io::Result<OwnedFd> {
|
||||
if host_dir().is_some() {
|
||||
return dial(port); // a unix socket: connect never waits
|
||||
}
|
||||
// SAFETY: plain socket setup and connect; the fd is owned immediately.
|
||||
unsafe {
|
||||
let fd = sys::check(libc::socket(libc::AF_VSOCK, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) as _, "vsock socket")?;
|
||||
let sock = OwnedFd::from_raw_fd(fd as RawFd);
|
||||
let tv = libc::timeval { tv_sec: timeout.as_secs() as _, tv_usec: timeout.subsec_micros() as _ };
|
||||
sys::check(
|
||||
libc::setsockopt(sock.as_raw_fd(), libc::AF_VSOCK, SO_VM_SOCKETS_CONNECT_TIMEOUT, (&tv as *const libc::timeval).cast(), std::mem::size_of::<libc::timeval>() as u32) as _,
|
||||
"vsock connect timeout",
|
||||
)?;
|
||||
let mut addr: libc::sockaddr_vm = std::mem::zeroed();
|
||||
addr.svm_family = libc::AF_VSOCK as libc::sa_family_t;
|
||||
addr.svm_cid = VMADDR_CID_HOST;
|
||||
addr.svm_port = port;
|
||||
sys::check(libc::connect(sock.as_raw_fd(), (&addr as *const libc::sockaddr_vm).cast(), std::mem::size_of::<libc::sockaddr_vm>() as u32) as _, "vsock connect")?;
|
||||
Ok(sock)
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's own DNS servers, for a host process (no DHCP lease to ask).
|
||||
/// systemd-resolved's stub (127.0.0.53) is skipped for its upstreams.
|
||||
pub fn host_dns() -> Vec<[u8; 4]> {
|
||||
|
||||
@@ -167,6 +167,11 @@ pub enum Msg<'a> {
|
||||
/// vsock port of the guest's copy service: one connection per copy.
|
||||
pub const COPY_PORT: u32 = 1028;
|
||||
|
||||
/// vsock port of the host's DNS relay (VM only). The agent sends a lookup
|
||||
/// the VM's gateway resolver didn't answer as `u16 len | query`, as DNS over
|
||||
/// TCP frames it, and gets `u16 len | reply` back: one lookup per connection.
|
||||
pub const DNS_RELAY_PORT: u32 = 1037;
|
||||
|
||||
pub mod copy_op {
|
||||
pub const IN: u8 = 1;
|
||||
pub const OUT: u8 = 2;
|
||||
|
||||
@@ -46,6 +46,11 @@ mod builds;
|
||||
#[cfg(windows)]
|
||||
#[path = "../../kiri/src/buildwith.rs"]
|
||||
mod buildwith;
|
||||
// Kiri's program moved or deleted from where it started: the Mac's and
|
||||
// Linux's own crates/kiri/src/appwatch.rs.
|
||||
#[cfg(windows)]
|
||||
#[path = "../../kiri/src/appwatch.rs"]
|
||||
mod appwatch;
|
||||
// An image's Layers and Security tabs, asked of the engine in WSL.
|
||||
#[cfg(windows)]
|
||||
mod scan;
|
||||
@@ -139,6 +144,22 @@ fn main() -> std::process::ExitCode {
|
||||
serve::log(&format!("dns on 127.0.0.1:53: {e}"));
|
||||
}
|
||||
engine::start(engine::Env { distro: cfg.distro.clone(), pipe: cfg.pipe.clone() });
|
||||
// Its folder renamed, moved or deleted around it (Windows won't delete
|
||||
// a running program itself): docker build handed back as it was before
|
||||
// Kiri took it, the choice kept for when Kiri runs again, and Kiri quits.
|
||||
appwatch::watch(|exe| {
|
||||
serve::log(&format!("{} is gone from where Kiri started; handing docker build back and quitting", exe.display()));
|
||||
if let Err(e) = buildwith::places().and_then(|p| p.give_back()) {
|
||||
serve::log(&format!("docker build not handed back: {e}"));
|
||||
}
|
||||
app::Handle.run(|_| {
|
||||
// SAFETY: ends the window's message loop; run on its thread.
|
||||
unsafe { windows::Win32::UI::WindowsAndMessaging::PostQuitMessage(0) }
|
||||
});
|
||||
// No window to quit (it never opened): quit from here.
|
||||
std::thread::sleep(std::time::Duration::from_secs(5));
|
||||
std::process::exit(0);
|
||||
});
|
||||
// The engine starts when the page says `ready`, and with the window
|
||||
// hidden (--background, as from the login shortcut) no page loads: after
|
||||
// kiri-win restarted, docker got no answer until Start was pressed.
|
||||
|
||||
@@ -89,9 +89,9 @@ fn physical_mib() -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the running VM has: CPUs, and memory rounded up to a whole GB
|
||||
/// (Linux reports a little less than WSL gave it). None while Kiri's
|
||||
/// engine isn't running, so that Settings never starts WSL.
|
||||
/// What the running VM has: CPUs, and memory in MiB as Linux reports it
|
||||
/// (MemTotal; see `as_set`). None while Kiri's engine isn't running, so
|
||||
/// that Settings never starts WSL.
|
||||
fn running() -> Option<(u64, u64)> {
|
||||
if !crate::client::alive() {
|
||||
return None;
|
||||
@@ -106,7 +106,20 @@ fn running() -> Option<(u64, u64)> {
|
||||
let mut lines = text.lines();
|
||||
let cpus: u64 = lines.next()?.trim().parse().ok()?;
|
||||
let kib: u64 = lines.next()?.split_whitespace().nth(1)?.parse().ok()?;
|
||||
Some((cpus, (kib >> 10).div_ceil(1024) * 1024))
|
||||
Some((cpus, kib >> 10))
|
||||
}
|
||||
|
||||
/// The memory the VM runs with, as Settings shows it. Linux reports less
|
||||
/// than WSL gave it: the kernel keeps some back, 1.2 GB of 64 GB, more than
|
||||
/// rounding up to a whole GB makes good, and Settings said "up to 63 GB"
|
||||
/// and offered a restart that changed nothing. Up to a sixteenth under
|
||||
/// the setting is the setting; anything else is rounded up to a whole GB.
|
||||
fn as_set(running_mib: u64, set_mib: u64) -> u64 {
|
||||
if running_mib <= set_mib && running_mib + set_mib / 16 >= set_mib {
|
||||
set_mib
|
||||
} else {
|
||||
running_mib.div_ceil(1024) * 1024
|
||||
}
|
||||
}
|
||||
|
||||
fn event() -> Value {
|
||||
@@ -121,7 +134,7 @@ fn event() -> Value {
|
||||
"cpus": cpus,
|
||||
"memory_mib": memory,
|
||||
"running_cpus": now.map_or(cpus, |r| r.0),
|
||||
"running_memory_mib": now.map_or(memory, |r| r.1),
|
||||
"running_memory_mib": now.map_or(memory, |r| as_set(r.1, memory)),
|
||||
"awake": now.is_some(),
|
||||
"max_cpus": max_cpus,
|
||||
"max_memory_mib": max_mib,
|
||||
@@ -175,6 +188,16 @@ pub fn restart() {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_vm_running_as_set_shows_its_setting() {
|
||||
// WSL given 64 GB: Linux's MemTotal is 65843312 kB.
|
||||
assert_eq!(as_set(65843312 >> 10, 65536), 65536);
|
||||
assert_eq!(as_set(8000, 8192), 8192);
|
||||
// Given less, or more, than the setting now says: what it has.
|
||||
assert_eq!(as_set(65843312 >> 10, 32768), 63 * 1024);
|
||||
assert_eq!(as_set(16000, 65536), 16 * 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_sizes() {
|
||||
assert_eq!(mib("32GB"), Some(32768));
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Noticing that Kiri's own program is gone from where it started: the app
|
||||
//! dragged to the Trash, a development build's folder deleted, or (on
|
||||
//! Windows, where a running program can't be deleted) its folder renamed
|
||||
//! or moved. What's left running can't do its job any more (on the Mac the
|
||||
//! VM's kernel went with the app), yet it still holds what "Build with
|
||||
//! Kiri" took, buildx's builder for every context, and every `docker
|
||||
//! build` fails on it. The daemon (daemon/mod.rs) and kiri-win both watch,
|
||||
//! hand the builder back and stop.
|
||||
//!
|
||||
//! The same file serves the Mac and Linux (crates/kiri) and Windows
|
||||
//! (kiri-win includes it).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How often the program's path is looked at.
|
||||
pub const EVERY: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Calls `on_gone` once, on its own thread, when the program this process
|
||||
/// started from has been missing from its path on two looks in a row (an
|
||||
/// update swaps the app in well under that). The path is the one it started
|
||||
/// with: on a Linux host a package upgrade puts a new file there, which
|
||||
/// counts as still there.
|
||||
pub fn watch(on_gone: impl FnOnce(&Path) + Send + 'static) {
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
watch_path(exe, EVERY, on_gone);
|
||||
}
|
||||
}
|
||||
|
||||
fn watch_path(path: PathBuf, every: Duration, on_gone: impl FnOnce(&Path) + Send + 'static) {
|
||||
let _ = std::thread::Builder::new().name("kiri-app-watch".into()).spawn(move || {
|
||||
let mut missing = 0;
|
||||
while missing < 2 {
|
||||
std::thread::sleep(every);
|
||||
missing = if path.exists() { 0 } else { missing + 1 };
|
||||
}
|
||||
on_gone(&path);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn a_program_moved_away_is_noticed_once_and_one_put_back_is_not() {
|
||||
let dir = std::env::temp_dir().join(format!("kiri-appwatch-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("app")).unwrap();
|
||||
let exe = dir.join("app").join("kiri");
|
||||
std::fs::write(&exe, b"program").unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
super::watch_path(exe.clone(), Duration::from_millis(20), move |p| tx.send(p.to_owned()).unwrap());
|
||||
// There all along: nothing.
|
||||
assert!(rx.recv_timeout(Duration::from_millis(150)).is_err());
|
||||
// Its folder renamed, as Windows allows for a running program.
|
||||
std::fs::rename(dir.join("app"), dir.join("moved")).unwrap();
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(5)).unwrap(), exe);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_brief_swap_is_not_taken_for_gone() {
|
||||
let dir = std::env::temp_dir().join(format!("kiri-appwatch-swap-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let exe = dir.join("kiri");
|
||||
std::fs::write(&exe, b"old").unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
super::watch_path(exe.clone(), Duration::from_millis(400), move |p| tx.send(p.to_owned()).unwrap());
|
||||
// Gone for the first look (at 400 ms), back before the second (800 ms).
|
||||
std::fs::remove_file(&exe).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(600));
|
||||
std::fs::write(&exe, b"new").unwrap();
|
||||
assert!(rx.recv_timeout(Duration::from_millis(1500)).is_err());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -209,8 +209,9 @@ impl Places {
|
||||
}
|
||||
|
||||
/// Build with Docker: puts back what `take` kept, where it is still
|
||||
/// as Kiri left it.
|
||||
fn give_back(&self) -> io::Result<()> {
|
||||
/// as Kiri left it. Also when Kiri's program is gone (appwatch.rs):
|
||||
/// the choice itself is kept, so `apply` takes it again later.
|
||||
pub fn give_back(&self) -> io::Result<()> {
|
||||
let mut s = self.state();
|
||||
let before = s["before"].take();
|
||||
if before.is_null() {
|
||||
@@ -493,6 +494,27 @@ mod tests {
|
||||
assert!(p.instance("kiri").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_kiri_whose_app_is_gone_hands_builds_back_to_the_first() {
|
||||
let d = scratch("second");
|
||||
let main = places(&d);
|
||||
builder(&main);
|
||||
main.choose(With::Kiri).unwrap();
|
||||
// A development build of Kiri, its own state and builder, takes them.
|
||||
let dev = Places { state: d.join(".kiri-layers/build.json"), builder: "kiri-layers-build".into(), context: "kiri-layers".into(), ..places(&d) };
|
||||
let i = json!({"Name": "kiri-layers-build", "Driver": "docker-container", "Nodes": [{"Name": "kiri-layers-build0", "Endpoint": "kiri-layers"}], "Dynamic": false});
|
||||
write_bytes(&dev.instance("kiri-layers-build"), i.to_string().as_bytes()).unwrap();
|
||||
dev.choose(With::Kiri).unwrap();
|
||||
assert!(dev.taken() && !main.taken());
|
||||
// Its app deleted: the daemon hands back (daemon/mod.rs).
|
||||
dev.give_back().unwrap();
|
||||
assert!(main.taken(), "builds go to the first Kiri again");
|
||||
assert_eq!(dev.saved(), Some(With::Kiri), "the choice stays");
|
||||
// Taken up again, it takes them again.
|
||||
dev.apply(None).unwrap();
|
||||
assert!(dev.taken());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_back_restores_exactly() {
|
||||
let d = scratch("restore");
|
||||
|
||||
@@ -3,9 +3,17 @@
|
||||
//! picks the container from the Host header. macOS sends these lookups here
|
||||
//! because of `/etc/resolver/kiri.local`, which `kiri setup` installs once
|
||||
//! (it needs an administrator). Anything else is refused.
|
||||
//!
|
||||
//! Also the relay for container lookups the VM's gateway resolver fails
|
||||
//! (`serve_relay`): the guest agent sends them here over vsock, and they're
|
||||
//! asked of the Mac's own resolvers.
|
||||
|
||||
use std::io;
|
||||
use std::net::UdpSocket;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{IpAddr, SocketAddr, UdpSocket};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The resolver file's port; unprivileged, so the daemon needs no root.
|
||||
pub const PORT: u16 = 53535;
|
||||
@@ -73,9 +81,211 @@ fn answer(q: &[u8]) -> Option<Vec<u8>> {
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// How long one resolver gets to answer a relayed lookup.
|
||||
const RELAY_TRY: Duration = Duration::from_millis(1500);
|
||||
/// All the resolvers together: the agent stops waiting at five seconds.
|
||||
const RELAY_BUDGET: Duration = Duration::from_millis(3500);
|
||||
/// How long the agent gets to send its query, and to take the reply.
|
||||
const RELAY_IO: Duration = Duration::from_secs(5);
|
||||
/// Relayed lookups at once, as many as the agent itself keeps in flight;
|
||||
/// more are dropped (the client asks again).
|
||||
const MAX_RELAYS: usize = 256;
|
||||
static RELAYS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// One lookup from the guest agent: `u16 len | query` in, `u16 len | reply`
|
||||
/// out (kiri_proto::DNS_RELAY_PORT). The agent sends here only what the
|
||||
/// VM's gateway resolver refused or left unanswered, so this is the path
|
||||
/// while macOS's resolver for the VM network is down.
|
||||
pub fn serve_relay(stream: kiri_vmm::VsockStream) {
|
||||
if RELAYS.fetch_add(1, Ordering::Relaxed) >= MAX_RELAYS {
|
||||
RELAYS.fetch_sub(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
let spawned = std::thread::Builder::new().name("kiri-dns-relay".into()).spawn(move || {
|
||||
relay_one(&stream);
|
||||
RELAYS.fetch_sub(1, Ordering::Relaxed);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
RELAYS.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn relay_one(stream: &kiri_vmm::VsockStream) {
|
||||
let Ok(fd) = stream.fd.try_clone() else { return };
|
||||
// A peer that connects and then says nothing doesn't keep a thread.
|
||||
// Best effort: without the timeouts the lookup still works.
|
||||
if let Err(e) = set_timeouts(fd.as_raw_fd(), RELAY_IO) {
|
||||
crate::diag::debug!("DNS relay: no socket timeouts", error = e);
|
||||
}
|
||||
let mut conn = std::fs::File::from(fd);
|
||||
let mut len = [0u8; 2];
|
||||
if conn.read_exact(&mut len).is_err() {
|
||||
return;
|
||||
}
|
||||
let mut query = vec![0u8; u16::from_be_bytes(len) as usize];
|
||||
if conn.read_exact(&mut query).is_err() || !is_query(&query) {
|
||||
return;
|
||||
}
|
||||
static SAID: AtomicBool = AtomicBool::new(false);
|
||||
if !SAID.swap(true, Ordering::Relaxed) {
|
||||
crate::diag::warn!("the VM's DNS at its gateway did not answer; container lookups go through the Mac");
|
||||
}
|
||||
let name = question_name(&query).unwrap_or_default();
|
||||
let servers = mac_resolvers(&name, Path::new("/etc/resolv.conf"), Path::new("/etc/resolver"));
|
||||
let reply = relay_query(&query, &servers).unwrap_or_else(|| servfail(&query));
|
||||
let mut out = Vec::with_capacity(2 + reply.len());
|
||||
out.extend_from_slice(&(reply.len().min(u16::MAX as usize) as u16).to_be_bytes());
|
||||
out.extend_from_slice(&reply[..reply.len().min(u16::MAX as usize)]);
|
||||
let _ = conn.write_all(&out);
|
||||
}
|
||||
|
||||
/// Whether `q` is a standard DNS query with one well-formed question: the
|
||||
/// only thing the agent sends, and so all that's passed to the Mac's
|
||||
/// resolvers (some of which listen on the Mac's loopback).
|
||||
fn is_query(q: &[u8]) -> bool {
|
||||
q.len() >= 12
|
||||
&& q[2] & 0x80 == 0 // QR: a query
|
||||
&& (q[2] >> 3) & 0x0f == 0 // OPCODE: QUERY
|
||||
&& u16::from_be_bytes([q[4], q[5]]) == 1
|
||||
&& q[6..8] == [0, 0] // no answers
|
||||
&& question_end(q).is_some()
|
||||
}
|
||||
|
||||
fn set_timeouts(fd: std::os::fd::RawFd, t: Duration) -> io::Result<()> {
|
||||
let tv = libc::timeval { tv_sec: t.as_secs() as _, tv_usec: t.subsec_micros() as _ };
|
||||
let len = std::mem::size_of::<libc::timeval>() as libc::socklen_t;
|
||||
for opt in [libc::SO_RCVTIMEO, libc::SO_SNDTIMEO] {
|
||||
// SAFETY: a valid timeval for a socket option on a descriptor we hold.
|
||||
if unsafe { libc::setsockopt(fd, libc::SOL_SOCKET, opt, (&tv as *const libc::timeval).cast(), len) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first answer to `query` from `servers`, tried in order.
|
||||
fn relay_query(query: &[u8], servers: &[SocketAddr]) -> Option<Vec<u8>> {
|
||||
let start = Instant::now();
|
||||
let mut buf = vec![0u8; 65_535];
|
||||
for server in servers {
|
||||
let left = RELAY_BUDGET.checked_sub(start.elapsed())?;
|
||||
let bind: SocketAddr = if server.is_ipv4() { ([0, 0, 0, 0], 0).into() } else { (std::net::Ipv6Addr::UNSPECIFIED, 0).into() };
|
||||
let Ok(sock) = UdpSocket::bind(bind) else { continue };
|
||||
if sock.connect(server).is_err() || sock.send(query).is_err() {
|
||||
continue;
|
||||
}
|
||||
let until = Instant::now() + RELAY_TRY.min(left);
|
||||
// Read past stray datagrams until this query's answer or the deadline.
|
||||
while let Some(wait) = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) {
|
||||
if sock.set_read_timeout(Some(wait)).is_err() {
|
||||
break;
|
||||
}
|
||||
let Ok(n) = sock.recv(&mut buf) else { break };
|
||||
let r = &buf[..n];
|
||||
if n >= 12 && r[..2] == query[..2] && r[2] & 0x80 != 0 {
|
||||
return Some(r.to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// SERVFAIL for `query`: no resolver on the Mac answered either.
|
||||
fn servfail(query: &[u8]) -> Vec<u8> {
|
||||
let end = question_end(query).unwrap_or(12).min(query.len());
|
||||
let mut r = query[..end].to_vec();
|
||||
r[2] = 0x80 | (query[2] & 0x79); // QR, opcode and RD kept
|
||||
r[3] = 0x80 | 2; // RA, SERVFAIL
|
||||
r[6..12].fill(0);
|
||||
if end > 12 {
|
||||
r[5] = 1;
|
||||
} else {
|
||||
r[4..6].fill(0);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Offset just past the first question, if there is one.
|
||||
fn question_end(q: &[u8]) -> Option<usize> {
|
||||
if q.len() < 12 || u16::from_be_bytes([q[4], q[5]]) == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut i = 12;
|
||||
loop {
|
||||
let len = *q.get(i)? as usize;
|
||||
if len == 0 {
|
||||
break;
|
||||
}
|
||||
if len > 63 {
|
||||
return None;
|
||||
}
|
||||
i += 1 + len;
|
||||
}
|
||||
(i + 5 <= q.len()).then_some(i + 5)
|
||||
}
|
||||
|
||||
/// The first question's name, lowercase, without the trailing dot.
|
||||
fn question_name(q: &[u8]) -> Option<String> {
|
||||
question_end(q)?;
|
||||
let mut i = 12;
|
||||
let mut name = String::new();
|
||||
loop {
|
||||
let len = q[i] as usize;
|
||||
if len == 0 {
|
||||
return Some(name);
|
||||
}
|
||||
if !name.is_empty() {
|
||||
name.push('.');
|
||||
}
|
||||
name.push_str(&String::from_utf8_lossy(&q[i + 1..i + 1 + len]).to_ascii_lowercase());
|
||||
i += 1 + len;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the Mac would send a lookup for `name`: the servers of the
|
||||
/// `/etc/resolver/<domain>` file with the longest domain that `name` is in
|
||||
/// (VPNs and tools such as dnsmasq set these up), else `/etc/resolv.conf`'s,
|
||||
/// which macOS keeps to its current primary DNS servers. Read on every
|
||||
/// lookup, so network changes are followed. Kiri's own `kiri.local` file is
|
||||
/// skipped: its server answers 127.0.0.1, the Mac's loopback, which means
|
||||
/// nothing in a container.
|
||||
fn mac_resolvers(name: &str, resolv_conf: &Path, resolver_dir: &Path) -> Vec<SocketAddr> {
|
||||
let mut best: Option<(usize, Vec<SocketAddr>)> = None;
|
||||
for entry in std::fs::read_dir(resolver_dir).into_iter().flatten().flatten() {
|
||||
let Ok(text) = std::fs::read_to_string(entry.path()) else { continue };
|
||||
let file = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
let domain = text
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("domain").map(|d| d.trim().trim_end_matches('.').to_ascii_lowercase()))
|
||||
.filter(|d| !d.is_empty())
|
||||
.unwrap_or(file);
|
||||
if domain == SUFFIX {
|
||||
continue;
|
||||
}
|
||||
let inside = name == domain || name.ends_with(&format!(".{domain}"));
|
||||
if !inside || best.as_ref().is_some_and(|(len, _)| *len >= domain.len()) {
|
||||
continue;
|
||||
}
|
||||
let servers = parse_servers(&text);
|
||||
if !servers.is_empty() {
|
||||
best = Some((domain.len(), servers));
|
||||
}
|
||||
}
|
||||
best.map(|(_, s)| s).unwrap_or_else(|| parse_servers(&std::fs::read_to_string(resolv_conf).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// `nameserver` lines (and a `port` line) of a resolv.conf-style file.
|
||||
/// Link-local IPv6 servers, which need an interface named, are skipped.
|
||||
fn parse_servers(text: &str) -> Vec<SocketAddr> {
|
||||
let field = |key: &'static str| text.lines().filter_map(move |l| l.trim().strip_prefix(key).filter(|v| v.starts_with([' ', '\t'])).map(str::trim));
|
||||
let port = field("port").find_map(|p| p.parse::<u16>().ok()).unwrap_or(53);
|
||||
field("nameserver").filter_map(|ip| ip.parse::<IpAddr>().ok()).map(|ip| SocketAddr::new(ip, port)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::answer;
|
||||
use std::net::UdpSocket;
|
||||
|
||||
fn query(name: &str, qtype: u16) -> Vec<u8> {
|
||||
let mut q = vec![0x12, 0x34, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0];
|
||||
@@ -100,4 +310,72 @@ mod tests {
|
||||
assert_eq!(answer(&query("notkiri.local", 1)).unwrap()[3], 5);
|
||||
assert!(answer(&[0; 5]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relayed_lookups_go_where_the_mac_would_send_them() {
|
||||
let dir = std::env::temp_dir().join(format!("kiri-dns-test-{}", std::process::id()));
|
||||
let resolvers = dir.join("resolver");
|
||||
std::fs::create_dir_all(&resolvers).unwrap();
|
||||
let conf = dir.join("resolv.conf");
|
||||
std::fs::write(&conf, "# macOS\nsearch home\nnameserver 192.168.1.1\nnameserver fe80::1%en0\nnameserver 2001:db8::53\n").unwrap();
|
||||
std::fs::write(resolvers.join("corp.example"), "nameserver 10.0.0.53\n").unwrap();
|
||||
std::fs::write(resolvers.join("eu.corp.example"), "nameserver 10.1.0.53\nport 5353\n").unwrap();
|
||||
std::fs::write(resolvers.join("kiri.local"), "nameserver 127.0.0.1\nport 53535\n").unwrap();
|
||||
let r = |name: &str| super::mac_resolvers(name, &conf, &resolvers).iter().map(ToString::to_string).collect::<Vec<_>>();
|
||||
assert_eq!(r("registry-1.docker.io"), ["192.168.1.1:53", "[2001:db8::53]:53"]);
|
||||
assert_eq!(r("git.corp.example"), ["10.0.0.53:53"]);
|
||||
assert_eq!(r("corp.example"), ["10.0.0.53:53"]);
|
||||
assert_eq!(r("db.eu.corp.example"), ["10.1.0.53:5353"], "the longest domain wins");
|
||||
assert_eq!(r("notcorp.example"), ["192.168.1.1:53", "[2001:db8::53]:53"]);
|
||||
assert_eq!(r("web.kiri.local"), ["192.168.1.1:53", "[2001:db8::53]:53"], "Kiri's own resolver is the Mac's loopback");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relayed_lookup_takes_the_first_resolver_that_answers() {
|
||||
let up = UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let addr = up.local_addr().unwrap();
|
||||
let resolver = std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 512];
|
||||
let (n, from) = up.recv_from(&mut buf).unwrap();
|
||||
// A stray datagram first, then the answer.
|
||||
up.send_to(&[9; 12], from).unwrap();
|
||||
buf[2] |= 0x80;
|
||||
up.send_to(&buf[..n], from).unwrap();
|
||||
});
|
||||
// A closed port first: refused, then the next one is asked.
|
||||
let closed = UdpSocket::bind("127.0.0.1:0").unwrap().local_addr().unwrap();
|
||||
let q = query("registry-1.docker.io", 1);
|
||||
let r = super::relay_query(&q, &[closed, addr]).expect("answered");
|
||||
resolver.join().unwrap();
|
||||
assert_eq!((&r[..2], r[2] & 0x80, &r[12..]), (&q[..2], 0x80, &q[12..]));
|
||||
assert_eq!(super::question_name(&q).as_deref(), Some("registry-1.docker.io"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_standard_queries_are_relayed() {
|
||||
let q = query("registry-1.docker.io", 1);
|
||||
assert!(super::is_query(&q));
|
||||
let mut reply = q.clone();
|
||||
reply[2] |= 0x80;
|
||||
assert!(!super::is_query(&reply), "a response");
|
||||
let mut update = q.clone();
|
||||
update[2] = 5 << 3;
|
||||
assert!(!super::is_query(&update), "an UPDATE");
|
||||
let mut two = q.clone();
|
||||
two[5] = 2;
|
||||
assert!(!super::is_query(&two), "two questions");
|
||||
assert!(!super::is_query(&q[..q.len() - 1]), "cut short");
|
||||
assert!(!super::is_query(&[0x12, 0x34, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0xc0, 12, 0, 1, 0, 1]), "a compression pointer");
|
||||
assert!(!super::is_query(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n"), "not DNS at all");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servfail_keeps_the_id_and_question() {
|
||||
let q = query("example.com", 1);
|
||||
let r = super::servfail(&q);
|
||||
assert_eq!((&r[..2], r[2] & 0x80, r[3] & 0x0f), (&q[..2], 0x80, 2));
|
||||
assert_eq!((&r[4..12], &r[12..]), (&[0, 1, 0, 0, 0, 0, 0, 0][..], &q[12..]));
|
||||
assert_eq!(super::servfail(&[0x12, 0x34, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0])[3], 0x82);
|
||||
}
|
||||
}
|
||||
@@ -668,6 +668,11 @@ impl Engine {
|
||||
if cfg!(target_os = "macos") {
|
||||
vm.listen(super::ports::ENGINE_API_PORT, Box::new(super::ports::serve_engine_api))?;
|
||||
}
|
||||
// Container lookups the VM's gateway resolver fails, asked of the
|
||||
// Mac's own (VM only: a Linux host's agent asks the host's itself).
|
||||
if cfg!(target_os = "macos") {
|
||||
vm.listen(kiri_proto::DNS_RELAY_PORT, Box::new(super::dns::serve_relay))?;
|
||||
}
|
||||
// Everything else on the guest's disk belongs to containers that are gone.
|
||||
let keep: Vec<String> = self.lock().containers.keys().cloned().collect();
|
||||
vm.retain(&keep)?;
|
||||
|
||||
@@ -151,6 +151,8 @@ pub fn run(_args: &[String]) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
watch_own_app(engine.clone(), socket.clone());
|
||||
|
||||
let on_signal = engine.clone();
|
||||
let sock = socket.clone();
|
||||
std::thread::Builder::new().name("kiri-signals".into()).spawn(move || {
|
||||
@@ -180,6 +182,26 @@ pub fn run(_args: &[String]) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// When the app this daemon runs from is deleted (appwatch.rs): docker
|
||||
/// build handed back (buildwith.rs: what was there before; the choice
|
||||
/// stays, so the app taken up again takes it again), and the engine stops.
|
||||
fn watch_own_app(engine: std::sync::Arc<engine::Engine>, socket: std::path::PathBuf) {
|
||||
crate::appwatch::watch(move |exe| {
|
||||
diag::error!("the app this engine runs from was deleted; stopping and handing docker build back", path = exe.display());
|
||||
if let Err(e) = crate::buildwith::places().and_then(|p| p.give_back()) {
|
||||
diag::warn!("docker build not handed back", error = e);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
nfs::unmount();
|
||||
let _ = std::fs::remove_file(&socket);
|
||||
engine.shutdown();
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
// 0: launchd restarts the engine on failure only, and there is
|
||||
// nothing left to restart.
|
||||
std::process::exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
/// Serves container files over NFS and mounts them at ~/Kiri.
|
||||
/// KIRI_NO_FINDER=1 skips the mount.
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -141,6 +141,9 @@ impl Guest {
|
||||
share: opts.data_disk.then(|| (PathBuf::from("/"), "kiri-mac".to_owned())),
|
||||
rosetta_tag: opts.data_disk.then(|| "rosetta".to_owned()),
|
||||
};
|
||||
if !cfg.kernel.is_file() {
|
||||
return Err(missing_kernel(&cfg.kernel, std::env::current_exe().ok().as_deref()));
|
||||
}
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
@@ -404,6 +407,17 @@ fn translated() -> bool {
|
||||
on == 1
|
||||
}
|
||||
|
||||
/// The error for a guest kernel that isn't there. Mostly the app was
|
||||
/// deleted or moved while its engine ran: say that, not a bare path.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn missing_kernel(kernel: &std::path::Path, exe: Option<&std::path::Path>) -> io::Error {
|
||||
let msg = match exe {
|
||||
Some(exe) if !exe.exists() => format!("{} was deleted or moved while it ran: open Kiri again from where it is now", crate::flavor::APP),
|
||||
_ => format!("the guest kernel {} is missing: reinstall Kiri", kernel.display()),
|
||||
};
|
||||
io::Error::new(io::ErrorKind::NotFound, msg)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
/// Where the kernel and initramfs live: `KIRI_GUEST_DIR`, else
|
||||
/// `Kiri.app/Contents/Resources/guest` when running from the app, else the
|
||||
|
||||
@@ -12,6 +12,10 @@ mod boot;
|
||||
#[cfg(unix)]
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
mod builds;
|
||||
// The engine stops when its app is deleted under it (kiri-win includes it
|
||||
// for Windows).
|
||||
#[cfg(unix)]
|
||||
mod appwatch;
|
||||
// Which builder plain `docker build` uses: Docker's or Kiri's.
|
||||
#[cfg(unix)]
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
|
||||
@@ -443,7 +443,15 @@ table.sized .name[data-detail] > div:last-child { max-width: none; }
|
||||
.swatches button { width: 22px; height: 22px; border-radius: 50%; border: 0; background: var(--sw); cursor: pointer; box-shadow: 0 0 0 2px var(--bg), 0 0 0 2px var(--bg); }
|
||||
.swatches button[aria-checked=true] { box-shadow: 0 0 0 2px var(--bg), 0 0 0 4px var(--text); }
|
||||
.range { grid-row: 1 / span 2; grid-column: 2; display: flex; align-items: center; gap: 10px; }
|
||||
.range input { width: 200px; accent-color: var(--blue); }
|
||||
/* Drawn by Kiri, not the system: macOS WebKit, WebView2 (Chromium) and
|
||||
WebKitGTK each draw a native slider their own way. This is the Mac's: a
|
||||
dark track, filled in blue up to a white pill. --fill is set from the
|
||||
value (rangeFill). */
|
||||
.range input { -webkit-appearance: none; appearance: none; width: 200px; height: 9px; margin: 0; border-radius: 999px; cursor: pointer;
|
||||
background: linear-gradient(to right, var(--blue) var(--fill, 0%), var(--line) var(--fill, 0%)); }
|
||||
.range input::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 26px; height: 18px; border-radius: 999px; background: #fff;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, .35), 0 0 0 .5px rgba(0, 0, 0, .2); }
|
||||
.range input:focus-visible { outline: 2px solid var(--blue-light); outline-offset: 4px; }
|
||||
.range .num { min-width: 64px; text-align: right; font-weight: 600; }
|
||||
.isec { display: grid; gap: 6px; }
|
||||
.ihead { display: flex; gap: 8px; align-items: baseline; }
|
||||
@@ -770,6 +778,9 @@ td.actions .acts-row { margin-left: auto; width: max-content; padding-left: 24px
|
||||
.settings .tabs button[aria-current=true] { background: var(--raised); color: var(--text); box-shadow: inset 0 0 0 1px var(--line); }
|
||||
.settings .tabs button[aria-current=true] svg { color: var(--blue); }
|
||||
.pane { display: grid; gap: 22px; min-width: 0; }
|
||||
/* A tab with more than one pane (Resources: the engine, then its limits)
|
||||
keeps them together in the second column of .settings. */
|
||||
.panes { display: grid; gap: 28px; min-width: 0; }
|
||||
.pane h3 { font-size: var(--fs-head); }
|
||||
.updrow { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.updpill { font-size: var(--fs-small); font-weight: 600; padding: 2px 7px; border-radius: 99px; background: color-mix(in srgb, #3FB97A 16%, transparent); color: color-mix(in srgb, #3FB97A 70%, var(--text)); }
|
||||
@@ -3148,6 +3159,12 @@ function networkPane() {
|
||||
/* Settings → Resources: the most the Linux VM may use. */
|
||||
const gb = (mib) => `${Math.round(mib / 1024)} GB`;
|
||||
const cpuText = (n) => `${n} ${n === 1 ? "CPU" : "CPUs"}`;
|
||||
/* How far along its track a slider's blue fill reaches, as CSS: to the
|
||||
middle of the thumb, which travels the track less its own 26 px. */
|
||||
const rangeFill = (v, min, max) => {
|
||||
const f = max > min ? (v - min) / (max - min) : 0;
|
||||
return `calc(13px + (100% - 26px) * ${f.toFixed(4)})`;
|
||||
};
|
||||
const resChanged = () => ui.res && (ui.resDraft.cpus !== ui.res.cpus || ui.resDraft.memory_mib !== ui.res.memory_mib);
|
||||
/* Settings › Resources: the engine's on/off, the same switch as the card. */
|
||||
function enginePane() {
|
||||
@@ -3170,9 +3187,9 @@ function resourcesPane() {
|
||||
const pending = r.awake && (r.running_cpus !== r.cpus || Math.abs(r.running_memory_mib - r.memory_mib) > 64);
|
||||
return `<div class="pane"><h3>Resources</h3>
|
||||
<div class="pref"><span class="t">CPUs</span><span class="d">Shared with ${OS}: the VM only uses them while containers are busy.</span>
|
||||
<div class="range"><input type="range" id="res-cpus" min="1" max="${r.max_cpus}" step="1" value="${d.cpus}" aria-label="CPUs"><span class="num" id="res-cpus-v">${cpuText(d.cpus)}</span></div></div>
|
||||
<div class="range"><input type="range" id="res-cpus" min="1" max="${r.max_cpus}" step="1" value="${d.cpus}" aria-label="CPUs" style="--fill:${rangeFill(d.cpus, 1, r.max_cpus)}"><span class="num" id="res-cpus-v">${cpuText(d.cpus)}</span></div></div>
|
||||
<div class="pref"><span class="t">Memory</span><span class="d">The most the VM may take. It uses memory only as containers need it and gives the rest back to ${OS}.</span>
|
||||
<div class="range"><input type="range" id="res-mem" min="1024" max="${maxGb * 1024}" step="1024" value="${Math.min(d.memory_mib, maxGb * 1024)}" aria-label="Memory"><span class="num" id="res-mem-v">${gb(d.memory_mib)}</span></div></div>
|
||||
<div class="range"><input type="range" id="res-mem" min="1024" max="${maxGb * 1024}" step="1024" value="${Math.min(d.memory_mib, maxGb * 1024)}" aria-label="Memory" style="--fill:${rangeFill(Math.min(d.memory_mib, maxGb * 1024), 1024, maxGb * 1024)}"><span class="num" id="res-mem-v">${gb(d.memory_mib)}</span></div></div>
|
||||
${r.overridden ? `<p class="muted">KIRI_CPUS or KIRI_MEMORY_MIB is set for the daemon, and it takes precedence over these.</p>` : ""}
|
||||
<div class="res-foot"><span class="muted">${r.awake ? `Running now with ${cpuText(r.running_cpus)} and up to ${gb(r.running_memory_mib)}.` : "The VM is asleep; it starts with these next time."}</span>
|
||||
<span style="flex:1"></span>
|
||||
@@ -3259,7 +3276,7 @@ function renderSettings() {
|
||||
</dl>
|
||||
<p class="muted">The name comes from the Igbo word ntakịrị, “small”.</p></div>`;
|
||||
const html = `<div class="settings"><div class="tabs">${tab("appearance", "textaa", "Appearance")}${tab("resources", "stack", "Resources")}${tab("network", "globe", "Network")}${tab("builds", "hammer", "Builds")}${loginsOn() ? tab("registries", "lock", "Registries") : ""}${tab("kubernetes", "pods", "Kubernetes")}${tab("import", "stack", "Import")}${tab("domains", "network", "Domains")}${tab("diagnostics", "bug", "Diagnostics")}${tab("about", "info", "About")}</div>
|
||||
${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? enginePane() + resourcesPane() : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" && loginsOn() ? registriesPane() : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}</div>`;
|
||||
${prefs.tab === "diagnostics" ? diagPane() : prefs.tab === "about" ? aboutPane : prefs.tab === "domains" ? domainsPane : prefs.tab === "resources" ? `<div class="panes">${enginePane()}${resourcesPane()}</div>` : prefs.tab === "network" ? networkPane() : prefs.tab === "builds" ? buildsPane() : prefs.tab === "registries" && loginsOn() ? registriesPane() : prefs.tab === "kubernetes" ? kubernetesPane() : prefs.tab === "import" ? importPane() : appearance}</div>`;
|
||||
// The container lists arrive every few seconds; rebuilding an unchanged page
|
||||
// closes an open menu. The font menus list names in the interface font: an
|
||||
// option in its own font made WebKit load every installed font (438 here)
|
||||
@@ -3280,6 +3297,7 @@ function renderSettings() {
|
||||
}));
|
||||
for (const id of ["res-cpus", "res-mem"]) $(id)?.addEventListener("input", (ev) => {
|
||||
ui.resDraft[id === "res-cpus" ? "cpus" : "memory_mib"] = +ev.target.value;
|
||||
ev.target.style.setProperty("--fill", rangeFill(+ev.target.value, +ev.target.min, +ev.target.max));
|
||||
$(`${id}-v`).textContent = id === "res-cpus" ? cpuText(+ev.target.value) : gb(+ev.target.value);
|
||||
$("res-save").disabled = !resChanged();
|
||||
});
|
||||
@@ -5171,9 +5189,15 @@ function stopReason(c) {
|
||||
// the strictest images take it.
|
||||
function genPassword() {
|
||||
const sets = ["ABCDEFGHJKLMNPQRSTUVWXYZ", "abcdefghijkmnpqrstuvwxyz", "23456789", "-_.@%"], all = sets.join("");
|
||||
const r = crypto.getRandomValues(new Uint32Array(20));
|
||||
const out = [...r].map((n, i) => (i < 4 ? sets[i] : all)[n % (i < 4 ? sets[i] : all).length]);
|
||||
for (let i = out.length - 1; i > 0; i--) { const j = r[i] % (i + 1); [out[i], out[j]] = [out[j], out[i]]; }
|
||||
// A uniform number below n: fresh random values, dropping the few at the
|
||||
// top of the range that would make some answers likelier than others.
|
||||
const below = (n) => {
|
||||
const limit = 2 ** 32 - (2 ** 32 % n), r = new Uint32Array(1);
|
||||
do crypto.getRandomValues(r); while (r[0] >= limit);
|
||||
return r[0] % n;
|
||||
};
|
||||
const out = Array.from({ length: 20 }, (_, i) => { const set = i < 4 ? sets[i] : all; return set[below(set.length)]; });
|
||||
for (let i = out.length - 1; i > 0; i--) { const j = below(i + 1); [out[i], out[j]] = [out[j], out[i]]; }
|
||||
return out.join("");
|
||||
}
|
||||
const strong = (v) => v.length >= 8 && /[A-Z]/.test(v) && /[a-z]/.test(v) && /\d/.test(v) && /[^A-Za-z0-9]/.test(v);
|
||||
|
||||
+26
-1
@@ -180,7 +180,20 @@ t default-route "default via 172.17.0.1" $D run --rm alpine ip route
|
||||
t lo "127.0.0.1" $D run --rm alpine sh -c 'ip -4 addr show lo'
|
||||
t internet-http "Example Domain" $D run --rm alpine wget -qO- http://example.com
|
||||
t internet-dns "Address" $D run --rm alpine nslookup example.com
|
||||
# The default bridge in the VM names its gateway, not 127.0.0.11: BuildKit
|
||||
# drops loopback nameservers from build steps and puts 8.8.8.8 in their place.
|
||||
t dns-default-bridge-gateway "nameserver 172.17.0.1" $D run --rm alpine cat /etc/resolv.conf
|
||||
code dns-default-bridge-no-loopback 1 $D run --rm alpine grep -q 127.0.0.11 /etc/resolv.conf
|
||||
t internet-https "200" $D run --rm curlimages/curl:latest -s -o /dev/null -w '%{http_code}' https://www.google.com
|
||||
# Each container gets the last one's address and MAC: its first download
|
||||
# broke mid-TLS or stalled while the old one's veth lingered, and one that
|
||||
# keeps running lost its gateway whenever the bridge's MAC moved.
|
||||
APKIDX=https://dl-cdn.alpinelinux.org/alpine/v3.22/main/aarch64/APKINDEX.tar.gz
|
||||
t first-download-x8 "8" bash -c "n=0; for i in \$(seq 8); do $D run --rm curlimages/curl:latest -s -m 20 -o /dev/null -w '%{exitcode}' $APKIDX | grep -qx 0 && n=\$((n+1)); done; echo \$n"
|
||||
$D run -d --name dl curlimages/curl:latest sh -c "while true; do curl -s -m 10 -o /dev/null -w '%{exitcode} ' $APKIDX; done" >/dev/null
|
||||
for _ in $(seq 6); do $D run --rm alpine true; sleep 1; done
|
||||
code download-while-others-start 1 bash -c "$D logs dl 2>&1 | grep -qE '(^| )[1-9][0-9]* '"
|
||||
$D rm -f dl >/dev/null
|
||||
t none-net "lo" $D run --rm --network none alpine ip link
|
||||
code none-no-internet 1 $D run --rm --network none alpine wget -qO- -T 2 http://example.com
|
||||
t host-net "192.168.64." $D run --rm --network host alpine ip -4 addr show eth0
|
||||
@@ -540,6 +553,10 @@ t build-runs "from context" $D run --rm kiri-test/built
|
||||
t build-arg "hello" $D run --rm kiri-test/built
|
||||
t build-cached "CACHED" bash -c "cd $BD && BUILDX_BUILDER=$BX $D build --progress plain --build-arg MSG=hello -t kiri-test/built . 2>&1"
|
||||
t build-network "curl" bash -c "cd $BD && printf 'FROM alpine\nRUN apk add --no-cache curl\n' > Dockerfile.net && BUILDX_BUILDER=$BX perl -e 'alarm 300; exec @ARGV' $D build -f Dockerfile.net -t kiri-test/net . >/dev/null 2>&1 && $D run --rm kiri-test/net curl --version"
|
||||
# Build steps keep Kiri's resolver (and with it the Mac's): no 8.8.8.8.
|
||||
t build-resolvconf "nameserver 172.17.0.1" bash -c "cd $BD && printf 'FROM alpine\nRUN cat /etc/resolv.conf\n' > Dockerfile.dns && BUILDX_BUILDER=$BX perl -e 'alarm 300; exec @ARGV' $D build --no-cache --progress plain -f Dockerfile.dns . 2>&1"
|
||||
code build-no-public-resolver 1 bash -c "cd $BD && BUILDX_BUILDER=$BX perl -e 'alarm 300; exec @ARGV' $D build --no-cache --progress plain -f Dockerfile.dns . 2>&1 | grep -q 'nameserver 8.8.8.8'"
|
||||
t build-dns "Address" bash -c "cd $BD && printf 'FROM alpine\nRUN nslookup example.com\n' > Dockerfile.lookup && BUILDX_BUILDER=$BX perl -e 'alarm 300; exec @ARGV' $D build --no-cache --progress plain -f Dockerfile.lookup . 2>&1"
|
||||
t build-fails "exit code: 3" bash -c "cd $BD && printf 'FROM alpine\nRUN exit 3\n' > Dockerfile.bad && BUILDX_BUILDER=$BX $D build -f Dockerfile.bad . 2>&1"
|
||||
$D rmi kiri-test/built kiri-test/net >/dev/null 2>&1; rm -rf "$BD"
|
||||
|
||||
@@ -644,6 +661,13 @@ t native-again "aarch64" bash -c "$D pull -q --platform linux/arm64 alpine >/dev
|
||||
$D rmi amd64/alpine:3.22 >/dev/null 2>&1
|
||||
|
||||
section "security: seccomp, capabilities, read-only"
|
||||
# Docker's two defaults in a container's own network: any port and ping
|
||||
# without root. --sysctl wins; host networking keeps the VM's own.
|
||||
t unpriv-port-start "0" $D run --rm alpine cat /proc/sys/net/ipv4/ip_unprivileged_port_start
|
||||
t unpriv-ping-range "0 2147483647" $D run --rm alpine cat /proc/sys/net/ipv4/ping_group_range
|
||||
t unpriv-listen-80 "listening" $D run --rm -u 1000 alpine sh -c 'nc -lk -p 80 >/dev/null 2>&1 & sleep 0.5; netstat -ltn | grep -q ":80 " && echo listening'
|
||||
t unpriv-sysctl-wins "1024" $D run --rm --sysctl net.ipv4.ip_unprivileged_port_start=1024 alpine cat /proc/sys/net/ipv4/ip_unprivileged_port_start
|
||||
t unpriv-port-host-net "1024" $D run --rm --network host alpine cat /proc/sys/net/ipv4/ip_unprivileged_port_start
|
||||
t seccomp-on "Seccomp: 2" $D run --rm alpine grep Seccomp: /proc/self/status
|
||||
t seccomp-userns "not permitted" $D run --rm alpine unshare -U true
|
||||
t seccomp-keyctl "not permitted" bash -c "$D run --rm alpine sh -c 'apk add -q keyutils >/dev/null 2>&1; keyctl show 2>&1'"
|
||||
@@ -683,7 +707,8 @@ $D rm -f dns >/dev/null
|
||||
code udp-port-free-after 0 bash -c "python3 -c 'import socket; s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.bind((\"0.0.0.0\", 15354))'"
|
||||
|
||||
section "Linux machines"
|
||||
KIRI=${KIRI:-./target/release/kiri}
|
||||
# Absolute: machine-cwd runs it from another folder.
|
||||
KIRI=${KIRI:-$(cd "$(dirname "$0")/.." && pwd)/target/release/kiri}
|
||||
# The binary as one shell word, for commands passed to bash -c (app paths have spaces).
|
||||
KQ=$(printf %q "$KIRI")
|
||||
t machine-create "is running" "$KIRI" machine create e2e-m --distro alpine
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Every Settings tab keeps its panes in the second column, beside the tabs:
|
||||
// Resources has two (the engine, then its limits), and the second one fell
|
||||
// under the 180 px tab list, its sliders and words squeezed into it.
|
||||
const R = [];
|
||||
const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } };
|
||||
kiri.on({ type: "importsources", sources: [] });
|
||||
kiri.on({ type: "resources", cpus: 24, memory_mib: 65536, running_cpus: 24, running_memory_mib: 65536, awake: false, max_cpus: 32, max_memory_mib: 130048, overridden: false });
|
||||
show("settings");
|
||||
for (const id of [...document.querySelectorAll("[data-stab]")].map((b) => b.dataset.stab)) {
|
||||
t(`Settings → ${id}: every pane beside the tabs`, () => {
|
||||
document.querySelector(`[data-stab="${id}"]`).click();
|
||||
const tabs = document.querySelector(".settings .tabs").getBoundingClientRect();
|
||||
const panes = [...document.querySelectorAll(".settings .pane")];
|
||||
if (!panes.length) throw new Error("no pane");
|
||||
for (const p of panes) {
|
||||
const r = p.getBoundingClientRect();
|
||||
if (r.left < tabs.right) throw new Error(`"${p.querySelector("h3")?.textContent}" starts at ${Math.round(r.left)}, under the tabs (they end at ${Math.round(tabs.right)})`);
|
||||
}
|
||||
});
|
||||
}
|
||||
t("Resources: both sliders beside the tabs, not under them", () => {
|
||||
document.querySelector('[data-stab="resources"]').click();
|
||||
const tabs = document.querySelector(".settings .tabs").getBoundingClientRect();
|
||||
for (const id of ["res-cpus", "res-mem"]) {
|
||||
const r = document.getElementById(id)?.getBoundingClientRect();
|
||||
if (!r) throw new Error(`no ${id}`);
|
||||
if (r.left < tabs.right) throw new Error(`${id} starts at ${Math.round(r.left)}, under the tabs`);
|
||||
}
|
||||
});
|
||||
report(R);
|
||||
Reference in new issue
Block a user