Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
301781cdce
|
||
|
|
4c3aaefdd5 | ||
|
|
d314d6b3c2 | ||
|
|
e155900ddd | ||
|
|
c1da681b2c |
No files matched your search
@@ -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")));
|
||||
}
|
||||
@@ -258,8 +258,15 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
|
||||
// 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, net.dns.relay);
|
||||
prepared.etc_files = write_etc_files(spec, &etc_dir, net.upstream_dns, embedded_dns).map_err(cleanup)?;
|
||||
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 {
|
||||
@@ -750,11 +763,23 @@ fn embedded_dns(spec: &RunSpec<'_>, upstream: &[[u8; 4]], relay: bool) -> bool {
|
||||
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"));
|
||||
@@ -1202,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())
|
||||
@@ -1362,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]
|
||||
@@ -1399,6 +1439,13 @@ mod tests {
|
||||
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]
|
||||
|
||||
@@ -33,6 +33,15 @@ 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.
|
||||
@@ -62,6 +71,8 @@ struct Pending {
|
||||
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,
|
||||
@@ -94,6 +105,8 @@ pub struct Dns {
|
||||
/// 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> {
|
||||
@@ -342,7 +355,7 @@ impl Dns {
|
||||
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()).copied();
|
||||
if self.pending.len() >= MAX_PENDING {
|
||||
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 {
|
||||
@@ -357,7 +370,7 @@ impl Dns {
|
||||
// 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 relay_stream(&msg) {
|
||||
None if may_relay => match self.relay_stream(&msg) {
|
||||
Some(s) => (s, true),
|
||||
None => return,
|
||||
},
|
||||
@@ -366,6 +379,7 @@ impl Dns {
|
||||
let p = Pending {
|
||||
sock,
|
||||
our,
|
||||
key,
|
||||
server: self.servers[server].sock.as_raw_fd(),
|
||||
client,
|
||||
id,
|
||||
@@ -389,12 +403,15 @@ impl Dns {
|
||||
|
||||
/// Sends pending query `at` again, through the host, once.
|
||||
fn relay(&mut self, at: usize) {
|
||||
let p = &mut self.pending[at];
|
||||
if !p.may_relay {
|
||||
if !self.pending[at].may_relay {
|
||||
return;
|
||||
}
|
||||
p.may_relay = false;
|
||||
if let Some(stream) = relay_stream(&p.query) {
|
||||
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();
|
||||
@@ -443,6 +460,29 @@ impl Dns {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -484,22 +524,6 @@ fn ask(dest: [u8; 4], msg: &[u8]) -> Option<OwnedFd> {
|
||||
Some(sock)
|
||||
}
|
||||
|
||||
/// A stream to the host's DNS relay with `msg` sent on it, non-blocking
|
||||
/// for the reply.
|
||||
fn relay_stream(msg: &[u8]) -> Option<OwnedFd> {
|
||||
let stream = super::transport::dial(kiri_proto::DNS_RELAY_PORT).ok()?;
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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;
|
||||
@@ -725,6 +749,7 @@ mod tests {
|
||||
Pending {
|
||||
sock: udp_socket().unwrap(),
|
||||
our: 1,
|
||||
key: [0; 4],
|
||||
server: -1,
|
||||
client: unsafe { std::mem::zeroed() },
|
||||
id: 7,
|
||||
@@ -736,6 +761,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
@@ -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]> {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -10,8 +10,9 @@
|
||||
|
||||
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, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The resolver file's port; unprivileged, so the daemon needs no root.
|
||||
@@ -84,36 +85,82 @@ fn answer(q: &[u8]) -> Option<Vec<u8>> {
|
||||
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) {
|
||||
let _ = std::thread::Builder::new().name("kiri-dns-relay".into()).spawn(move || {
|
||||
let Ok(fd) = stream.fd.try_clone() else { return };
|
||||
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 query.len() < 12 || conn.read_exact(&mut query).is_err() {
|
||||
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);
|
||||
drop(stream);
|
||||
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.
|
||||
@@ -305,6 +352,24 @@ mod tests {
|
||||
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);
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
+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