Author SHA1 Message Date
ahp 11d2e89a15 Merge branch 'libracoder:main' into guest-nftables 2026-11-06 09:15:04 +03:30
Precious Okwu 82e13b560b Volumes over a bind get the image's files, as on Docker (#37) 2026-11-06 05:11:37 +01:00
Precious Okwu f7d2cff89b -F (#36) 2026-11-06 00:59:54 +01:00
Precious Okwu 41abfd20da e2e: test the engine under test, never the installed Kiri (#34) 2026-11-06 00:47:46 +01:00
Precious Okwu 39a36ddec2 Release notes for 0.1.18 (#35) 2026-11-05 23:37:52 +01:00
Precious Okwu 07e78baad3 UI: window — built-in terminal panel (#31) 2026-11-05 23:17:23 +01:00
Precious Okwu d01c3edb23 Check for updates every 6 hours while Kiri runs (#32) 2026-11-05 23:17:02 +01:00
Precious Okwuandahp ffe980f0c8 Linux: privileged containers get their own /dev, never the host's (#28)
Co-authored-by: Amir Husayn Panahifar <ahp@panahifar.ir>
2026-11-05 19:41:33 +01:00
Precious Okwu f1237085bf e2e: wait for nginx on the internal network; ping without NET_RAW works, as on Docker (#21) 2026-11-05 18:06:47 +01:00
Precious Okwu 5fb10d6b05 Guest kernel: the rest of netfilter, tc, socket diagnostics and the usual interfaces (#20) 2026-11-05 18:06:03 +01:00
Precious Okwu 4c3aaefdd5 Containers can listen on any port and ping without root, as on Docker (#19) 2026-11-05 06:45:05 +01:00
Precious Okwu d314d6b3c2 Containers' connections no longer break as others start and stop (#17) 2026-11-05 06:28:01 +01:00
Precious Okwu e155900ddd Settings › Resources: panes beside the tabs, one slider look on every system, no needless restart on Windows (#15) 2026-11-05 06:27:12 +01:00
Precious Okwu 49d0d9fc10 Guest kernel: the rest of netfilter, tc, socket diagnostics and the usual interfaces 2026-11-05 06:23:39 +01:00
Precious Okwu c1da681b2c Security: Build steps keep the Mac's DNS; tighter limits on the DNS relay (#12) 2026-11-05 06:14:12 +01:00
43 changed files with 3563 additions and 129 deletions

No files matched your search

+28
View File
@@ -7436,3 +7436,31 @@ scripts/ci/kernel-source.sh target/Kiri-VERSION-kernel-source.tar.xz
This offer to provide the corresponding source is valid for three years from
the date of each release. The guest kernel is a separate work from the
Apache-2.0 Kiri application.
----------------------------------------------------------------------
xterm.js 6.0.0, @xterm/addon-fit 0.11.0, @xterm/addon-search 0.16.0,
@xterm/addon-web-links 0.12.0 — MIT
----------------------------------------------------------------------
Source: https://github.com/xtermjs/xterm.js (crates/kiri/src/ui/xterm)
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+160 -31
View File
@@ -8,7 +8,7 @@
use std::ffi::{CStr, CString};
use std::fs;
use std::io;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
@@ -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"));
@@ -842,9 +867,19 @@ fn parse_mounts(list: StrList<'_>) -> io::Result<Vec<Mount>> {
tmpfs_flags: 0,
});
}
// Parents before what's under them, as Docker sorts mounts: the CLI sends
// `-v` in no set order, and `/app/node_modules` mounted before `/app`
// would be hidden by it. The sort is stable, so equal depths keep theirs.
out.sort_by_key(|m| depth(&m.target));
Ok(out)
}
/// How deep a mount target is: `.` is 0, `app` 1, `app/node_modules` 2.
fn depth(target: &CStr) -> usize {
let t = target.to_bytes();
if t == b"." { 0 } else { t.split(|&b| b == b'/').filter(|c| !c.is_empty()).count() }
}
/// A tmpfs's mount flags from its flag words, in order, so `exec` after
/// Docker's default `noexec` wins.
fn tmpfs_flags(words: &[&str]) -> libc::c_ulong {
@@ -871,7 +906,7 @@ fn tmpfs_flags(words: &[&str]) -> libc::c_ulong {
/// pivot_root), creating the target as a directory or an empty file. The
/// target is looked up inside `root`, so an image's symlink cannot point
/// the mount, the copy-up or the new directory outside the container.
fn apply_mount(root: BorrowedFd<'_>, m: &Mount) -> io::Result<()> {
fn apply_mount(root: BorrowedFd<'_>, image: Option<BorrowedFd<'_>>, m: &Mount) -> io::Result<()> {
let t = Path::new(std::ffi::OsStr::from_bytes(m.target.to_bytes()));
if let Some(opts) = &m.tmpfs_opts {
let at = inroot::open(root, t, Last::Dir)?;
@@ -880,12 +915,27 @@ fn apply_mount(root: BorrowedFd<'_>, m: &Mount) -> io::Result<()> {
let src = m.source.as_ref().expect("bind mounts have a source");
let at = inroot::open(root, t, if m.dir { Last::Dir } else { Last::File })?;
let target = at.proc_path();
if m.dir && m.copy_up && !at.created {
let src_path = Path::new(std::ffi::OsStr::from_bytes(src.to_bytes()));
let image_path = Path::new(std::ffi::OsStr::from_bytes(target.to_bytes()));
let empty = fs::read_dir(src_path).map(|mut d| d.next().is_none()).unwrap_or(false);
if empty && image_path.is_dir() {
copy_tree(image_path, src_path)?;
if m.dir && m.copy_up {
// A new volume is filled from the image's directory, as Docker does,
// never from a bind mounted over it earlier (`./:/app` then
// `/app/node_modules` must get the image's node_modules, not the
// host's): looked up in the image's own tree when there is one.
let from = match image {
Some(img) => inroot::open(img, t, Last::Exists).ok(),
None => None,
};
let from_path = match &from {
Some(f) => Some(f.proc_path()),
None if image.is_none() && !at.created => Some(target.clone()),
None => None,
};
if let Some(from_path) = from_path {
let src_path = Path::new(std::ffi::OsStr::from_bytes(src.to_bytes()));
let image_path = Path::new(std::ffi::OsStr::from_bytes(from_path.to_bytes()));
let empty = fs::read_dir(src_path).map(|mut d| d.next().is_none()).unwrap_or(false);
if empty && image_path.is_dir() {
copy_tree(image_path, src_path)?;
}
}
}
sys::mount(src, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?;
@@ -898,6 +948,18 @@ fn apply_mount(root: BorrowedFd<'_>, m: &Mount) -> io::Result<()> {
Ok(())
}
/// A detached copy of the current directory's mount (the container's
/// root) without the mounts on it: the image as it is under any bind.
/// None where the kernel has no open_tree (before Linux 5.2); volumes are
/// then filled from what the path shows, as before.
fn image_tree() -> Option<OwnedFd> {
const OPEN_TREE_CLONE: libc::c_uint = 1;
// SAFETY: a valid NUL-terminated path; the result is a new descriptor or -1.
let fd = unsafe { libc::syscall(libc::SYS_open_tree, libc::AT_FDCWD, c".".as_ptr(), OPEN_TREE_CLONE | libc::O_CLOEXEC as libc::c_uint) };
// SAFETY: a descriptor the kernel just returned, owned only here.
(fd >= 0).then(|| unsafe { OwnedFd::from_raw_fd(fd as RawFd) })
}
/// Copies a directory tree keeping modes, owners and symlinks: what Docker
/// does to fill a new volume from the image. `from` may be a
/// `/proc/self/fd/N` path to the image's directory (see `apply_mount`): its
@@ -979,9 +1041,13 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio) -> ! {
for (src, target) in &p.etc_files {
bind_file(root, src, target).unwrap_or_else(|e| fail(&target.to_string_lossy(), e));
}
// The image's tree without the mounts made on it, for filling new
// volumes; closed (and so unmounted) once they are all in place.
let image = if p.mounts.iter().any(|m| m.copy_up) { image_tree() } else { None };
for m in &p.mounts {
apply_mount(root, m).unwrap_or_else(|e| fail(&format!("mount {}", m.target.to_string_lossy()), e));
apply_mount(root, image.as_ref().map(|f| f.as_fd()), m).unwrap_or_else(|e| fail(&format!("mount {}", m.target.to_string_lossy()), e));
}
drop(image);
// pivot_root(".", ".") stacks the old root under the new one; detaching
// it leaves only the container's filesystem visible.
@@ -1029,8 +1095,8 @@ fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildSt
finish_child(p, io, false)
}
/// Binds the container's terminal over /dev/console; a privileged
/// container's devtmpfs has the VM's there, an unprivileged one has none.
/// Binds the container's terminal over /dev/console; neither a privileged
/// nor an unprivileged container's /dev has one of its own.
fn bind_console(slave: &OwnedFd) {
let Ok(pts) = fs::read_link(format!("/proc/self/fd/{}", slave.as_raw_fd())) else { return };
let Ok(pts) = CString::new(pts.into_os_string().into_encoded_bytes()) else { return };
@@ -1173,10 +1239,15 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()
}
sys::mount(c"proc", c"proc", c"proc", nosuid_nodev_noexec, None)?;
sys::mount(c"sysfs", c"sys", c"sysfs", nosuid_nodev_noexec | ro, None)?;
// Never devtmpfs, even for a privileged container: the kernel has one
// devtmpfs, so mounting it again hands the container the host's own
// /dev, and the links made below (dev/ptmx -> pts/ptmx) would replace
// the host's device nodes. On a Linux host that broke every terminal on
// the machine. A privileged container gets copies of the host's devices
// on its own tmpfs instead, as runc does.
sys::mount(c"tmpfs", c"dev", c"tmpfs", libc::MS_NOSUID, Some(c"mode=755,size=65536k"))?;
if privileged {
sys::mount(c"devtmpfs", c"dev", c"devtmpfs", libc::MS_NOSUID, None)?;
} else {
sys::mount(c"tmpfs", c"dev", c"tmpfs", libc::MS_NOSUID, Some(c"mode=755,size=65536k"))?;
copy_host_devices(Path::new("/dev"), Path::new("dev"))?;
}
for (name, major, minor) in [
(c"dev/null", 1, 3),
@@ -1187,7 +1258,7 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()
(c"dev/tty", 5, 0),
] {
if privileged {
// devtmpfs has them already.
// Copied from the host already.
continue;
}
sys::mknod(name, libc::S_IFCHR | 0o666, major, minor)?;
@@ -1202,7 +1273,7 @@ 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.
// SAFETY: valid NUL-terminated strings; the host copy may have some.
unsafe {
libc::unlink(link.as_ptr());
libc::symlink(target.as_ptr(), link.as_ptr())
@@ -1223,6 +1294,48 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()
Ok(())
}
/// Recreates the host's character and block devices under `to` (the
/// container's fresh /dev tmpfs), keeping their mode and owner, for a
/// privileged container. Skips what the container gets its own of (pts,
/// shm, mqueue, console, the fd links) and symlinks, as runc does. Devices
/// that appear on the host later don't show up, as on Docker.
fn copy_host_devices(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::fs::{FileTypeExt, MetadataExt};
for entry in fs::read_dir(from)? {
let entry = entry?;
let name = entry.file_name();
if from == Path::new("/dev")
&& matches!(name.as_bytes(), b"pts" | b"shm" | b"mqueue" | b"fd" | b"console" | b".lxc" | b".lxd-mounts" | b".udev")
{
continue;
}
let Ok(meta) = fs::symlink_metadata(entry.path()) else { continue };
let ft = meta.file_type();
let dest = to.join(&name);
if ft.is_dir() {
if fs::create_dir(&dest).is_ok() {
let _ = copy_host_devices(&entry.path(), &dest);
}
continue;
}
if !(ft.is_char_device() || ft.is_block_device()) {
continue;
}
let Ok(c) = CString::new(dest.as_os_str().as_bytes()) else { continue };
// SAFETY: valid NUL-terminated path.
if unsafe { libc::mknod(c.as_ptr(), meta.mode() as libc::mode_t, meta.rdev() as libc::dev_t) } != 0 {
continue;
}
// mknod applies the umask; keep the host's permissions and owner.
// SAFETY: valid NUL-terminated path.
unsafe {
libc::chmod(c.as_ptr(), (meta.mode() & 0o7777) as libc::mode_t);
libc::chown(c.as_ptr(), meta.uid(), meta.gid());
}
}
Ok(())
}
/// Makes the dangerous parts of /proc read-only or hides them, as Docker's
/// default `readonlyPaths` and `maskedPaths` do. The container is real root
/// (no user namespace), and these sysctls and files are not namespaced, so
@@ -1357,12 +1470,21 @@ mod tests {
std::fs::remove_dir_all(&base).unwrap();
}
#[test]
fn mounts_go_parents_first_whatever_order_they_came_in() {
let m = |t: &str| super::Mount { source: None, target: std::ffi::CString::new(t).unwrap(), ro: false, dir: true, copy_up: false, tmpfs_opts: None, tmpfs_flags: 0 };
let mut mounts = vec![m("app/node_modules"), m("app"), m("data"), m("app/cache/x"), m(".")];
mounts.sort_by_key(|x| super::depth(&x.target));
let order: Vec<_> = mounts.iter().map(|x| x.target.to_str().unwrap()).collect();
assert_eq!(order, [".", "app", "data", "app/node_modules", "app/cache/x"]);
}
fn resolv(flags: u32, opts: &[&str], upstream: &[[u8; 4]]) -> String {
let mut buf = Vec::new();
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 +1521,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]
+76 -22
View File
@@ -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;
+30 -1
View File
@@ -164,7 +164,7 @@ fn walk(host: &Path, container: &Path, out: &mut Vec<(String, fs::Metadata)>) ->
/// Makes the device nodes in the container (relative paths looked up
/// inside `root`, its root before pivot_root). A node already there (a
/// privileged container's devtmpfs) is left alone.
/// privileged container's copy of the host's devices) is left alone.
pub fn make_nodes(root: BorrowedFd<'_>, nodes: &[Node]) -> io::Result<()> {
for n in nodes {
let path = Path::new(std::ffi::OsStr::from_bytes(n.target.as_bytes()));
@@ -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"]);
+29
View File
@@ -240,6 +240,10 @@ pub fn uplink() -> io::Result<Option<Dhcp>> {
let mut nl = Netlink::open(libc::NETLINK_ROUTE)?;
netlink::set_up(&mut nl, index)?;
sys::write_file("/proc/sys/net/ipv4/ip_forward", "1")?;
// The tunnel drivers are built in, and each would add its idle fallback
// device (tunl0, gre0, sit0, ip6tnl0...) to every container's network:
// they stay in the VM's own, as on a machine that loads them as modules.
let _ = sys::write_file("/proc/sys/net/core/fb_tunnels_only_for_init_net", "1");
install_nat(Nat { uplink: index, redirect: true, dnat: Vec::new(), gateway: [0; 4] })?;
let _ = VM_UPLINK_INDEX.set(index);
Ok(Some(Dhcp::start(index)?))
@@ -659,6 +663,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 +692,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)?;
+49 -5
View File
@@ -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
+29
View File
@@ -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]> {
+1 -1
View File
@@ -16,7 +16,7 @@ kiri-share-proto = { path = "../kiri-share-proto" }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
webpki-roots = "1"
libc = "0.2"
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Memory", "Win32_System_Diagnostics_ToolHelp", "Win32_System_ProcessStatus", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_Com", "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Pipes", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_Memory", "Win32_System_Diagnostics_ToolHelp", "Win32_System_ProcessStatus", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_Com", "Win32_System_Console", "Win32_System_DataExchange", "Win32_System_IO", "Win32_System_LibraryLoader", "Win32_System_Pipes", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"] }
# The window: WebView2 (part of Windows) and plain Win32, as the Mac app is
# AppKit and WebKit with no UI framework.
webview2-com = "0.39"
+1 -2
View File
@@ -57,9 +57,8 @@ pub fn in_setup() -> bool {
}
fn page_html() -> String {
if SETUP.load(Ordering::SeqCst) { SETUP_PAGE.to_owned() } else { PAGE.replacen("/*ICONS*/", ICONS_JS, 1) }
if SETUP.load(Ordering::SeqCst) { SETUP_PAGE.to_owned() } else { crate::assemble::page(PAGE) }
}
const ICONS_JS: &str = include_str!("../../kiri/src/ui/icons.js");
/// Kiri's icon cropped to its artwork for Windows (brand/windows-icons.ps1),
/// by size: the Mac's has Apple's margin and looks small in the taskbar.
const ICONS: [(i32, &[u8]); 8] = [
+23 -1
View File
@@ -777,7 +777,7 @@ pub fn prefs() -> Value {
}
fn set_pref(name: &str, value: Value) {
if !matches!(name, "font" | "mono" | "scale" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto") {
if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto") {
return;
}
let Some(path) = prefs_path() else { return };
@@ -946,6 +946,28 @@ pub fn on_message(msg: &str) {
"sharelogin" => sharing::sign_in(),
"sharecancel" => sharing::cancel_sign_in(),
"sharelogout" => sharing::sign_out(),
// The built-in terminal: its shells, and its own clipboard and links.
"term" => match c.name.as_str() {
// A selection can be a whole screen of output.
"copy" => {
if let Some(text) = c.value.as_str().filter(|t| !t.is_empty() && t.len() <= crate::term::COPY_MAX)
&& clipboard(text).is_err()
{
emit(notice("error", "Couldn't copy to the clipboard"));
}
}
"paste" => {
let id = c.id;
crate::term::paste(move |text| emit(crate::term::paste_event(&id, &text)));
}
// A link in a shell's output: web pages only, never a file or an app's scheme.
"link" => {
if let Some(url) = c.value.as_str().filter(|u| crate::term::web_link(u)) {
crate::app::open_url(url);
}
}
action => crate::term::handle(action, &c.id, &c.value, emit),
},
// The page can't write the clipboard itself; IDs and short text only.
"copy" => {
if !c.name.is_empty() && c.name.len() <= 4096 && clipboard(&c.name).is_err() {
+55 -3
View File
@@ -141,9 +141,43 @@ fn config() -> Config {
config_path().ok().and_then(|p| std::fs::read(p).ok()).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
/// What of the settings a node is made with, as its label keeps them.
/// What of the settings a node is made with, as its label keeps them. The
/// drives' folder is in it too, so a node made before it had it is made
/// again at its next start.
fn made_with(cfg: &Config) -> String {
serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port())).unwrap_or_default()
serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), drives())).unwrap_or_default()
}
/// Where WSL puts this PC's drives (`/mnt`, unless `[automount] root` in
/// the engine distro's wsl.conf moves it), found once. The node sees it at
/// the same path, so a pod's `hostPath: /mnt/d/...` is drive D, as it is
/// with k3s in WSL itself (Rancher Desktop). The bind is recursive: every
/// drive WSL has mounted when the node starts comes with it.
fn drives() -> Option<String> {
static ROOT: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
ROOT.get_or_init(|| {
let mut wsl = crate::win::tool("wsl.exe");
std::os::windows::process::CommandExt::creation_flags(&mut wsl, 0x0800_0000); // CREATE_NO_WINDOW
if let Some(d) = crate::engine::distro() {
wsl.args(["-d", &d]);
}
let out = wsl.args(["--", "wslpath", "-a", "C:/"]).stdin(std::process::Stdio::null()).output().ok()?;
drives_root(&String::from_utf8_lossy(&out.stdout))
})
.clone()
}
/// The drives' folder from `wslpath -a C:/` (`/mnt/c/` → `/mnt`); none
/// when drives sit at the top (`/c/`), which isn't a folder to bind.
fn drives_root(c: &str) -> Option<String> {
let c = c.trim().trim_end_matches('/');
let (root, letter) = c.rsplit_once('/')?;
(letter.eq_ignore_ascii_case("c") && root.starts_with('/') && root.len() > 1 && !root.contains(['\\', ':'])).then(|| root.to_owned())
}
/// The node's binds: its state, then the drives' folder.
fn binds() -> Vec<String> {
std::iter::once(format!("{VOLUME}:/var/lib/rancher/k3s")).chain(drives().map(|d| format!("{d}:{d}"))).collect()
}
/// The port a node container publishes its API server on: its live binding
@@ -425,7 +459,7 @@ fn start(say: &dyn Fn(&str)) -> io::Result<()> {
"HostConfig": {
"Privileged": true,
"Tmpfs": {"/run": "", "/var/run": ""},
"Binds": [format!("{VOLUME}:/var/lib/rancher/k3s")],
"Binds": binds(),
"PortBindings": {"6443/tcp": [{"HostIp": if cfg.lan { "0.0.0.0" } else { "127.0.0.1" }, "HostPort": port.to_string()}]},
"RestartPolicy": {"Name": "unless-stopped"},
},
@@ -707,6 +741,24 @@ fn stop_logs() {
#[cfg(test)]
mod tests {
#[test]
fn the_drives_folder_comes_from_wslpath() {
assert_eq!(super::drives_root("/mnt/c/\n").as_deref(), Some("/mnt"));
assert_eq!(super::drives_root("/windir/c/").as_deref(), Some("/windir"));
for none in ["/c/", "", "C:/", "wslpath: error", "/mnt/d/"] {
assert_eq!(super::drives_root(none), None, "{none}");
}
}
#[test]
fn the_node_sees_the_drives_at_their_own_paths() {
let b = super::binds();
assert_eq!(b[0], "kiri-k8s:/var/lib/rancher/k3s");
if let Some(d) = super::drives() {
assert!(b.contains(&format!("{d}:{d}")), "{b:?}");
}
}
#[test]
fn the_port_comes_from_the_binding_then_the_label() {
let running = serde_json::json!({"NetworkSettings": {"Ports": {"6443/tcp": [{"HostIp": "127.0.0.1", "HostPort": "6444"}]}}, "Config": {"Labels": {"dev.kiri.k8s.port": "6450"}}});
+7
View File
@@ -13,6 +13,10 @@
#[cfg(windows)]
mod app;
// The window's page, put together as on the Mac and Linux.
#[cfg(windows)]
#[path = "../../kiri/src/ui/assemble.rs"]
mod assemble;
#[cfg(windows)]
mod client;
#[cfg(windows)]
@@ -29,6 +33,9 @@ mod serve;
mod win;
#[cfg(windows)]
mod setup;
// The built-in terminal's shells, on ConPTY.
#[cfg(windows)]
mod term;
#[cfg(windows)]
mod hub;
#[cfg(windows)]
+1 -1
View File
@@ -200,7 +200,7 @@ fn wsl_installed() -> bool {
quiet("wsl.exe").arg("--version").stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())
}
fn distros() -> Vec<String> {
pub(crate) fn distros() -> Vec<String> {
quiet("wsl.exe").args(["-l", "-q"]).output().map(|o| wsl_text(&o.stdout).lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect()).unwrap_or_default()
}
+421
View File
@@ -0,0 +1,421 @@
//! The built-in terminal's shells on Windows: each tab or pane is a shell
//! on its own ConPTY (Windows' pseudo console), in the user's folder, with
//! Kiri's tools first on the PATH. PowerShell 7, Windows PowerShell, cmd,
//! and each WSL distro except Kiri's own. What goes to and from the page is
//! in termwire.rs, shared with the Mac and Linux (crates/kiri/src/ui/term.rs).
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Write};
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::PathBuf;
use std::sync::mpsc::{Sender, channel};
use std::sync::{Arc, Mutex, PoisonError};
use serde_json::Value;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, S_OK};
use windows_sys::Win32::System::Console::{COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON, ResizePseudoConsole};
use windows_sys::Win32::System::Pipes::CreatePipe;
use windows_sys::Win32::System::Threading::{
CREATE_UNICODE_ENVIRONMENT, CreateProcessW, DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, GetExitCodeProcess, INFINITE, InitializeProcThreadAttributeList, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOEXW, TerminateProcess, UpdateProcThreadAttribute, WaitForSingleObject,
};
#[path = "../../kiri/src/ui/termwire.rs"]
mod termwire;
use termwire::Shell;
pub use termwire::{COPY_MAX, paste as paste_event, web_link};
/// A pseudo console, closed once: by the page closing it, or after its
/// shell exits.
struct Console(Mutex<Option<HPCON>>);
impl Console {
fn close(&self) {
if let Some(h) = self.0.lock().unwrap_or_else(PoisonError::into_inner).take() {
// SAFETY: h came from CreatePseudoConsole and is closed only here.
unsafe { ClosePseudoConsole(h) };
}
}
fn resize(&self, cols: u16, rows: u16) {
if let Some(h) = *self.0.lock().unwrap_or_else(PoisonError::into_inner) {
// SAFETY: h is open while it is in the mutex.
unsafe { ResizePseudoConsole(h, COORD { X: cols as i16, Y: rows as i16 }) };
}
}
}
struct Session {
console: Arc<Console>,
process: Arc<OwnedHandle>,
input: Sender<Vec<u8>>,
}
static SESSIONS: Mutex<Option<HashMap<String, Session>>> = Mutex::new(None);
fn with<R>(f: impl FnOnce(&mut HashMap<String, Session>) -> R) -> R {
f(SESSIONS.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new))
}
/// One `term` command from the page (copy, paste and links are engine.rs's).
pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) {
match action {
"shells" => {
std::thread::spawn(move || {
let list = shells();
let default = list.first().map_or_else(String::new, |s| s.id.clone());
emit(termwire::shells(&list, &default));
});
}
"open" if termwire::valid_id(id) => {
let (cols, rows) = termwire::size(value);
let asked = value["shell"].as_str().unwrap_or("").to_owned();
let id = id.to_owned();
// Listing WSL's distros runs wsl.exe: not on the window's thread.
std::thread::spawn(move || {
let list = shells();
// Only a shell from the list: the page never names a program.
let Some(shell) = list.iter().find(|s| s.id == asked).or(list.first()) else {
return emit(termwire::exit(&id, None, Some("No shell found")));
};
if let Err(e) = open(&id, &command_line(&shell.id), cols, rows, emit) {
emit(termwire::exit(&id, None, Some(&e.to_string())));
}
});
}
"input" => {
if let Some(bytes) = value.as_str().and_then(termwire::unb64) {
with(|s| s.get(id).map(|s| s.input.send(bytes)));
}
}
"resize" => {
let (cols, rows) = termwire::size(value);
with(|s| s.get(id).map(|s| s.console.resize(cols, rows)));
}
"close" => {
if let Some(s) = with(|s| s.remove(id)) {
end(s);
}
}
"closeall" => {
for (_, s) in with(std::mem::take) {
end(s);
}
}
_ => {}
}
}
/// Closes a session's console, which ends what runs in it, and its shell.
fn end(s: Session) {
// ClosePseudoConsole can wait for its output to be read: off the window's thread.
std::thread::spawn(move || {
s.console.close();
// SAFETY: the process handle is open while s holds it.
unsafe { TerminateProcess(s.process.as_raw_handle() as HANDLE, 1) };
});
}
fn system32(exe: &str) -> PathBuf {
let root = std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from);
root.join("System32").join(exe)
}
fn pwsh() -> Option<PathBuf> {
let installed = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join(r"PowerShell\7\pwsh.exe")).filter(|p| p.is_file());
installed.or_else(|| std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join("pwsh.exe")).find(|p| p.is_file())))
}
/// The shells this PC has, the first one the default.
fn shells() -> Vec<Shell> {
let mut list = Vec::new();
if pwsh().is_some() {
list.push(Shell { id: "pwsh".into(), label: "PowerShell 7".into(), group: "" });
}
list.push(Shell { id: "powershell".into(), label: "Windows PowerShell".into(), group: "" });
list.push(Shell { id: "cmd".into(), label: "Command Prompt".into(), group: "" });
// Kiri's own distro runs the engine; Docker Desktop's aren't for logging into.
for d in crate::setup::distros() {
let lower = d.to_ascii_lowercase();
if !lower.starts_with("kiri") && !lower.starts_with("docker-desktop") && d.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) {
list.push(Shell { id: format!("wsl:{d}"), label: format!("WSL · {d}"), group: "WSL" });
}
}
list
}
/// The command line for a listed shell's id.
fn command_line(id: &str) -> String {
let quoted = |p: PathBuf| format!("\"{}\"", p.display());
match id {
"pwsh" => pwsh().map_or_else(|| quoted(system32(r"WindowsPowerShell\v1.0\powershell.exe")), quoted) + " -NoLogo",
"powershell" => quoted(system32(r"WindowsPowerShell\v1.0\powershell.exe")) + " -NoLogo",
// Distro names were checked to be plain in shells().
_ if id.starts_with("wsl:") => format!("{} -d {} --cd ~", quoted(system32("wsl.exe")), &id[4..]),
_ => quoted(system32("cmd.exe")),
}
}
/// This process's environment with Kiri's tools first on the PATH, as a
/// CreateProcessW block: `name=value` UTF-16 strings, sorted, each ending
/// in a NUL, and one more NUL at the end.
fn environment() -> Vec<u16> {
let ours = std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join(r"Kiri\bin")).filter(|d| d.is_dir());
let exe_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(|p| p.to_path_buf()));
let mut vars: Vec<(String, String)> = std::env::vars_os().map(|(k, v)| (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())).collect();
let path_at = vars.iter().position(|(k, _)| k.eq_ignore_ascii_case("PATH"));
let old = path_at.map(|i| vars[i].1.clone()).unwrap_or_default();
let dirs: Vec<PathBuf> = ours.into_iter().chain(exe_dir.map(|d| d.join("bin")).filter(|d| d.is_dir())).chain(std::env::split_paths(&old)).collect();
let path = std::env::join_paths(dirs).map(|p| p.to_string_lossy().into_owned()).unwrap_or(old);
match path_at {
Some(i) => vars[i].1 = path,
None => vars.push(("PATH".into(), path)),
}
vars.sort_by_key(|(k, _)| k.to_uppercase());
let mut block: Vec<u16> = Vec::new();
for (k, v) in vars {
block.extend(format!("{k}={v}").encode_utf16());
block.push(0);
}
block.push(0);
block
}
fn pipe() -> std::io::Result<(OwnedHandle, OwnedHandle)> {
let (mut r, mut w): (HANDLE, HANDLE) = (0, 0);
// SAFETY: CreatePipe fills both handles on success; each is owned once.
unsafe {
if CreatePipe(&mut r, &mut w, std::ptr::null(), 0) == 0 {
return Err(std::io::Error::last_os_error());
}
Ok((OwnedHandle::from_raw_handle(r as _), OwnedHandle::from_raw_handle(w as _)))
}
}
fn open(id: &str, command: &str, cols: u16, rows: u16, emit: fn(String)) -> std::io::Result<()> {
if let Some(old) = with(|s| s.remove(id)) {
end(old);
}
// The console reads what's typed from one pipe and writes the screen to the other.
let (con_in, typed_w) = pipe()?;
let (screen_r, con_out) = pipe()?;
let mut hpc: HPCON = 0;
// SAFETY: the console duplicates both handles; ours are closed after.
let hr = unsafe { CreatePseudoConsole(COORD { X: cols as i16, Y: rows as i16 }, con_in.as_raw_handle() as HANDLE, con_out.as_raw_handle() as HANDLE, 0, &mut hpc) };
drop((con_in, con_out));
if hr != S_OK {
return Err(std::io::Error::other(format!("CreatePseudoConsole failed ({hr:#x})")));
}
let console = Arc::new(Console(Mutex::new(Some(hpc))));
let process = match spawn(command, hpc) {
Ok(p) => Arc::new(p),
Err(e) => {
console.close();
return Err(e);
}
};
let (input, typed) = channel::<Vec<u8>>();
with(|s| s.insert(id.to_owned(), Session { console: console.clone(), process: process.clone(), input }));
let mut writer = File::from(typed_w);
std::thread::spawn(move || {
for bytes in typed {
if writer.write_all(&bytes).is_err() {
break;
}
}
});
// The shell ending: close its console, which ends the screen pipe.
let code = Arc::new(Mutex::new(None));
let waiter = {
let (code, console, process) = (code.clone(), console.clone(), process.clone());
std::thread::spawn(move || {
let h = process.as_raw_handle() as HANDLE;
let mut c = 0u32;
// SAFETY: the handle stays open while process is held.
unsafe {
WaitForSingleObject(h, INFINITE);
GetExitCodeProcess(h, &mut c);
}
*code.lock().unwrap_or_else(PoisonError::into_inner) = Some(c as i32);
console.close();
})
};
let id = id.to_owned();
let mut screen = File::from(screen_r);
std::thread::spawn(move || {
let mut buf = vec![0u8; 64 * 1024];
loop {
match screen.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => emit(termwire::data(&id, &buf[..n])),
}
}
let _ = waiter.join();
let mine = with(|s| {
let mine = s.get(&id).is_some_and(|s| Arc::ptr_eq(&s.process, &process));
if mine {
s.remove(&id);
}
mine
});
if mine {
emit(termwire::exit(&id, *code.lock().unwrap_or_else(PoisonError::into_inner), None));
}
});
Ok(())
}
/// Starts `command` attached to the pseudo console `hpc`, in the user's folder.
fn spawn(command: &str, hpc: HPCON) -> std::io::Result<OwnedHandle> {
let mut cmdline: Vec<u16> = command.encode_utf16().chain([0]).collect();
let cwd: Option<Vec<u16>> = std::env::var_os("USERPROFILE").map(|p| p.to_string_lossy().encode_utf16().chain([0]).collect());
let env = environment();
// SAFETY: the attribute list is sized by the first call and lives in
// `list` until after CreateProcessW; every pointer passed outlives the
// call that takes it.
unsafe {
let mut size = 0usize;
InitializeProcThreadAttributeList(std::ptr::null_mut(), 1, 0, &mut size);
let mut list = vec![0u8; size];
let attrs = list.as_mut_ptr().cast();
if InitializeProcThreadAttributeList(attrs, 1, 0, &mut size) == 0 {
return Err(std::io::Error::last_os_error());
}
let ok = UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE as usize, hpc as *const _, std::mem::size_of::<HPCON>(), std::ptr::null_mut(), std::ptr::null());
if ok == 0 {
let e = std::io::Error::last_os_error();
DeleteProcThreadAttributeList(attrs);
return Err(e);
}
let mut si: STARTUPINFOEXW = std::mem::zeroed();
si.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;
// No standard handles of the window's: the shell's are the console's.
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
si.lpAttributeList = attrs;
let mut pi: PROCESS_INFORMATION = std::mem::zeroed();
let ok = CreateProcessW(
std::ptr::null(),
cmdline.as_mut_ptr(),
std::ptr::null(),
std::ptr::null(),
0,
EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,
env.as_ptr().cast(),
cwd.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
&si.StartupInfo,
&mut pi,
);
let e = std::io::Error::last_os_error();
DeleteProcThreadAttributeList(attrs);
if ok == 0 {
return Err(e);
}
CloseHandle(pi.hThread);
Ok(OwnedHandle::from_raw_handle(pi.hProcess as _))
}
}
/// The clipboard's text, handed to `done` on a thread of its own.
pub fn paste(done: impl FnOnce(String) + Send + 'static) {
use windows_sys::Win32::System::DataExchange::{CloseClipboard, GetClipboardData, OpenClipboard};
use windows_sys::Win32::System::Memory::{GlobalLock, GlobalUnlock};
const CF_UNICODETEXT: u32 = 13;
std::thread::spawn(move || {
// SAFETY: the clipboard is opened, read and closed here; the locked
// memory is a NUL-terminated UTF-16 string while it stays locked.
let text = unsafe {
// Another program may have it open for a moment.
let mut opened = false;
for _ in 0..10 {
if OpenClipboard(0) != 0 {
opened = true;
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
if !opened {
return;
}
let h = GetClipboardData(CF_UNICODETEXT);
let mut text = String::new();
if h != 0 {
let p = GlobalLock(h as _) as *const u16;
if !p.is_null() {
let len = (0..).take_while(|&i| *p.add(i) != 0).count();
text = String::from_utf16_lossy(std::slice::from_raw_parts(p, len));
GlobalUnlock(h as _);
}
}
CloseClipboard();
text
};
done(text);
});
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};
static EVENTS: Mutex<Vec<Sender<String>>> = Mutex::new(Vec::new());
fn record(json: String) {
for tx in EVENTS.lock().unwrap().iter() {
let _ = tx.send(json.clone());
}
}
fn output_until(rx: &Receiver<String>, id: &str, want: &str) -> (String, Option<Value>) {
let mut out = Vec::new();
let deadline = Instant::now() + Duration::from_secs(20);
while let Ok(ev) = rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
let ev: Value = serde_json::from_str(&ev).unwrap();
if ev["id"] != id {
continue;
}
match ev["ev"].as_str() {
Some("data") => {
out.extend(termwire::unb64(ev["b64"].as_str().unwrap()).unwrap());
if String::from_utf8_lossy(&out).contains(want) {
return (String::from_utf8_lossy(&out).into_owned(), None);
}
}
Some("exit") => return (String::from_utf8_lossy(&out).into_owned(), Some(ev)),
_ => {}
}
}
panic!("no {want:?} in {:?}", String::from_utf8_lossy(&out));
}
#[test]
fn cmd_runs_on_a_pseudo_console_and_says_when_it_ends() {
let (tx, rx) = channel();
EVENTS.lock().unwrap().push(tx);
handle("open", "w1", &serde_json::json!({"shell": "cmd", "cols": 100, "rows": 20}), record);
let typed = |s: &str| handle("input", "w1", &Value::String(termwire::b64(s.as_bytes())), record);
// cmd prints its prompt once it's ready for input.
output_until(&rx, "w1", ">");
typed("set /a 40+2 & echo. & echo DONE\r");
let (out, _) = output_until(&rx, "w1", "DONE");
assert!(out.contains("42"), "{out}");
typed("exit 7\r");
let (_, exit) = output_until(&rx, "w1", "\u{0}never");
assert_eq!(exit.unwrap()["code"], 7);
}
#[test]
fn the_list_never_offers_kiris_own_distro() {
let list = shells();
assert!(list.iter().any(|s| s.id == "cmd"));
assert!(!list.iter().any(|s| s.id.to_ascii_lowercase().starts_with("wsl:kiri")));
assert!(command_line("wsl:Ubuntu").ends_with("-d Ubuntu --cd ~"));
}
}
+15 -1
View File
@@ -32,6 +32,9 @@ use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[path = "../../kiri/src/ui/recheck.rs"]
mod recheck;
use serde_json::json;
use crate::engine::{emit, notice};
@@ -449,6 +452,16 @@ pub fn check_now(manual: bool) {
{
emit(json!({"type": "enginestale", "version": v}).to_string());
}
feed_check(manual);
});
// And every 6 hours while Kiri runs (recheck.rs), as on the Mac.
recheck::start(|| feed_check(false));
}
/// Whether the feed has a newer release, and one already staged; the
/// window's check and the 6-hourly one.
fn feed_check(manual: bool) {
{
// A test build (0.1.8-dev.42, scripts/ci/test-version.sh) isn't
// updated from the feed: it would "update" back to its release.
if CURRENT.contains("-dev") {
@@ -465,6 +478,7 @@ pub fn check_now(manual: bool) {
if !manual && crate::engine::prefs()["updateAuto"] == false {
return;
}
recheck::checked();
match latest() {
Ok(r) if newer(&r.version, CURRENT) => {
update_state("available", Some(&r.version), None);
@@ -483,7 +497,7 @@ pub fn check_now(manual: bool) {
}
}
}
});
}
}
/// Download on the card: fetches, checks and stages the release in the
+28 -5
View File
@@ -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));
+89 -24
View File
@@ -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);
+32 -3
View File
@@ -156,9 +156,27 @@ fn set(args: &[String]) -> io::Result<()> {
/// The label that keeps the settings a node was made with.
const CONFIG_LABEL: &str = "dev.kiri.k8s.config";
/// What of the settings a node is made with, as its label keeps them.
/// What of the settings a node is made with, as its label keeps them. The
/// host folders are in it too, so a node made before it had them (or before
/// one existed) is made again at its next start.
fn made_with(cfg: &Config) -> String {
serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port())).unwrap_or_default()
serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), host_folders())).unwrap_or_default()
}
/// The folders of this computer the node sees at their own paths, so a pod's
/// `hostPath` names a file here as it would with k3s on the host itself
/// (Rancher Desktop, k3s): the Mac's /Users and /Volumes, a Linux host's
/// /home, /mnt and /media. Binds are recursive, so what is mounted under
/// them when the node starts comes too.
const HOST_FOLDERS: &[&str] = if cfg!(target_os = "macos") { &["/Users", "/Volumes"] } else { &["/home", "/mnt", "/media"] };
fn host_folders() -> Vec<&'static str> {
HOST_FOLDERS.iter().copied().filter(|d| std::path::Path::new(d).is_dir()).collect()
}
/// The node's binds: its state, then the host folders.
fn binds() -> Vec<String> {
std::iter::once(format!("{VOLUME}:/var/lib/rancher/k3s")).chain(host_folders().into_iter().map(|d| format!("{d}:{d}"))).collect()
}
fn ensure_daemon() -> io::Result<()> {
@@ -262,7 +280,7 @@ fn start(use_context: bool) -> io::Result<()> {
"HostConfig": {
"Privileged": true,
"Tmpfs": {"/run": "", "/var/run": ""},
"Binds": [format!("{VOLUME}:/var/lib/rancher/k3s")],
"Binds": binds(),
"PortBindings": {"6443/tcp": [{"HostIp": if cfg.lan { "0.0.0.0" } else { "127.0.0.1" }, "HostPort": port.to_string()}]},
"RestartPolicy": {"Name": "unless-stopped"},
},
@@ -511,6 +529,17 @@ mod tests {
assert_eq!(super::bound_port(&serde_json::json!({})), None);
}
#[test]
fn the_node_sees_the_host_folders_at_their_own_paths() {
let b = super::binds();
assert_eq!(b[0], "kiri-k8s:/var/lib/rancher/k3s");
let home = if cfg!(target_os = "macos") { "/Users" } else { "/home" };
assert!(b.contains(&format!("{home}:{home}")), "{b:?}");
// A node made before the folders were bound is made again.
let old = serde_json::to_string(&(false, Vec::<String>::new(), 6443u16)).unwrap();
assert_ne!(super::made_with(&super::Config::default()), old);
}
#[test]
fn api_ports_are_unprivileged() {
assert_eq!(super::valid_port("6444"), Some(6444));
+39
View File
@@ -0,0 +1,39 @@
//! The window's page as every system loads it: index.html with its icons
//! and the terminal emulator (xterm.js, vendored unmodified in `xterm/`)
//! spliced into their placeholders. The Mac and Linux window (crates/kiri)
//! and Windows (kiri-win includes this file) load the same string, and
//! scripts/ui-test.py builds it the same way.
//!
//! The page is loaded as a string, and WebView2's NavigateToString takes at
//! most 2 MB: with xterm.js it is about 1.3 MB.
const ICONS_JS: &str = include_str!("icons.js");
const XTERM_CSS: &str = include_str!("xterm/xterm.css");
/// xterm.js 6.0.0 and its fit, search and web-links add-ons (UMD builds,
/// each defining a global), in the order they load.
const XTERM_JS: [&str; 4] = [include_str!("xterm/xterm.js"), include_str!("xterm/addon-fit.js"), include_str!("xterm/addon-search.js"), include_str!("xterm/addon-web-links.js")];
/// `index` (index.html) with everything spliced in.
pub fn page(index: &str) -> String {
let mut js = String::with_capacity(XTERM_JS.iter().map(|s| s.len() + 1).sum());
for part in XTERM_JS {
js.push_str(part);
// Each ends in a source-map comment: the next must start on a line of its own.
js.push('\n');
}
index.replacen("/*ICONS*/", ICONS_JS, 1).replacen("/*XTERM_CSS*/", XTERM_CSS, 1).replacen("/*XTERM_JS*/", &js, 1)
}
#[cfg(test)]
mod tests {
#[test]
fn every_placeholder_is_filled_once_and_the_page_fits_webview2() {
let page = super::page(include_str!("index.html"));
for p in ["/*ICONS*/", "/*XTERM_CSS*/", "/*XTERM_JS*/"] {
assert!(!page.contains(p), "{p} left in the page");
}
assert!(page.contains(".xterm-viewport"), "xterm.css missing");
// NavigateToString's limit is 2 MB; keep a margin for the page to grow.
assert!(page.encode_utf16().count() < 1_800_000, "page is {} UTF-16 units", page.encode_utf16().count());
}
}
+9 -2
View File
@@ -16,7 +16,7 @@ use gtk::prelude::*;
use javascriptcore::ValueExt;
use webkit2gtk::{SettingsExt, UserContentInjectedFrames, UserContentManager, UserContentManagerExt, UserScript, UserScriptInjectionTime, WebView, WebViewExt};
use super::{Cmd, ICONS_JS, PAGE, engine, prefs};
use super::{Cmd, PAGE, engine, prefs};
thread_local! {
/// The page and its window. Only ever touched on GTK's main thread.
@@ -76,7 +76,7 @@ pub fn run(autostart: bool, view: Option<String>) -> io::Result<()> {
}
// The page paints its own background: no white flash before it does.
webview.set_background_color(&gtk::gdk::RGBA::new(0.0, 0.0, 0.0, 0.0));
webview.load_html(&PAGE.replacen("/*ICONS*/", ICONS_JS, 1), None);
webview.load_html(&super::assemble::page(PAGE), None);
window.add(&webview);
set_appearance(prefs()["theme"].as_str().unwrap_or("system"));
@@ -171,6 +171,13 @@ pub(super) fn copy(text: &str) {
});
}
/// The clipboard's text, handed to `done` once GTK has it.
pub(super) fn paste(done: impl FnOnce(String) + Send + 'static) {
glib::MainContext::default().invoke(move || {
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).request_text(move |_, text| done(text.map(|t| t.to_string()).unwrap_or_default()));
});
}
/// The installed font families, sorted; `mono` keeps the fixed-pitch ones.
pub(super) fn font_families(mono: bool) -> Vec<String> {
let spacing = if mono { ":spacing=mono" } else { ":" };
+725 -7
View File
@@ -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)); }
@@ -1908,7 +1919,108 @@ body.beat { --beat: ring 1.6s ease-out; }
.rp-id .val { font: 600 var(--fs-head) var(--mono-font); color: var(--text); user-select: text; -webkit-user-select: text; }
.rp-id .btn { margin-left: auto; }
.rp-dialog .err { font-size: var(--fs); color: var(--red-text); }
/* --- The built-in terminal: a panel under the page (tests/ui/terminal.js) ----------- */
:root { --term-bg: #0B0F13; --term-fg: #D7DCE1; }
@media (prefers-color-scheme: light) { :root { --term-bg: #FFFFFF; --term-fg: #1F2328; } }
main { position: relative; }
/* Raised above the page: a shadow up onto it, a lighter top edge and a lifted
header, so the panel never reads as more of the page. */
.htdrawer { flex: none; height: var(--ht-h, 300px); border-top: 1px solid color-mix(in srgb, var(--text) 16%, var(--line)); position: relative; z-index: 3; display: flex; flex-direction: column; min-height: 0; background: var(--panel);
box-shadow: 0 -10px 28px rgb(0 0 0 / .32), 0 -1px 0 rgb(0 0 0 / .25); }
@media (prefers-color-scheme: light) { .htdrawer { box-shadow: 0 -8px 22px rgb(0 0 0 / .10); } }
.htdrawer[hidden] { display: none; }
.htdrawer.max { position: absolute; inset: 0; height: auto; border-top: 0; z-index: 10; }
.htgrip { position: absolute; top: -3px; left: 0; right: 0; height: 6px; cursor: row-resize; z-index: 5; }
.htdrawer.max .htgrip { display: none; }
.hthead { display: flex; align-items: center; height: 32px; padding: 0 6px 0 4px; border-bottom: 1px solid var(--line); gap: 2px; flex: none; background: color-mix(in srgb, var(--raised) 75%, var(--panel)); }
.httabs { display: flex; align-items: center; gap: 2px; min-width: 0; overflow: hidden; }
.httab { display: flex; align-items: center; gap: 6px; height: 24px; padding: 0 4px 0 9px; border-radius: 6px; color: var(--muted); cursor: pointer; white-space: nowrap; font-size: var(--fs); border: 0; background: none; font-family: inherit; }
.httab:hover { background: var(--row-hover); color: var(--text); }
.httab.on { background: var(--raised); color: var(--text); box-shadow: inset 0 0 0 1px var(--line); }
.httab .x { width: 16px; height: 16px; display: grid; place-items: center; border-radius: 4px; color: var(--faint); opacity: 0; }
.httab:hover .x, .httab.on .x { opacity: 1; }
.httab .pin { width: 16px; height: 16px; display: grid; place-items: center; color: var(--blue-light); }
.httab .pin svg { width: 11px; height: 11px; stroke-width: 2; }
.htctx { position: absolute; z-index: 35; width: 170px; padding: 5px; background: var(--raised); border: 1px solid var(--line); border-radius: 10px; box-shadow: 0 14px 40px rgb(0 0 0 / .45); }
.htctx[hidden] { display: none; }
.htctx .mi { display: flex; align-items: center; gap: 8px; width: 100%; height: 28px; padding: 0 8px; border: 0; border-radius: 6px; background: none; cursor: pointer; color: var(--text); font: var(--fs) var(--ui-font); text-align: left; }
.htctx .mi:hover { background: var(--blue); color: #fff; }
.htctx .mi:disabled { color: var(--faint); background: none; cursor: default; }
.httab .x:hover { background: color-mix(in srgb, var(--text) 10%, transparent); color: var(--text); }
.hthead .grow { flex: 1; min-width: 10px; align-self: stretch; }
.hthead .sep { width: 1px; height: 16px; background: var(--line); margin: 0 4px; }
.hthead .sb { width: 26px; height: 26px; }
/* The panel's icons are lines: every one of them (tab ×, find arrows) gets a stroke. */
.htdrawer svg, .httoggle svg { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.httab .x svg { width: 11px; height: 11px; stroke-width: 2; }
.htfind .sb svg { width: 14px; height: 14px; }
.htwrap { position: relative; flex: none; }
.htbody { flex: 1; min-height: 0; display: flex; background: var(--term-bg); position: relative; }
.htsplit { display: flex; flex: 1; min-width: 0; min-height: 0; }
.htsplit.v { flex-direction: column; }
.htcell { display: flex; min-width: 0; min-height: 0; }
/* Thick enough to see where one pane ends, with a wider grab area. */
.htdiv { flex: none; background: color-mix(in srgb, var(--text) 12%, var(--panel)); position: relative; z-index: 2; transition: background-color .12s; }
.htsplit.h > .htdiv { width: 4px; cursor: col-resize; }
.htsplit.v > .htdiv { height: 4px; cursor: row-resize; }
.htdiv::after { content: ""; position: absolute; inset: -3px; }
.htdiv:hover, .htdiv.drag { background: var(--blue); }
.htpane { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; position: relative; }
.htpt { flex: none; height: 20px; display: none; align-items: center; gap: 6px; padding: 0 8px; font-size: var(--fs-small); color: var(--faint); border-bottom: 1px solid color-mix(in srgb, var(--line) 50%, transparent); white-space: nowrap; overflow: hidden; }
.htbody.many .htpt { display: flex; }
.htname { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.htpx { width: 16px; height: 16px; display: grid; place-items: center; padding: 0; border: 0; border-radius: 4px; background: none; color: var(--faint); cursor: pointer; flex: none; opacity: 0; }
.htpane:hover .htpx, .htpane.focus .htpx { opacity: 1; }
.htpx:hover { background: color-mix(in srgb, var(--text) 10%, transparent); color: var(--text); }
.htpx svg { width: 10px; height: 10px; stroke-width: 2; }
.htpane.focus .htpt { color: var(--muted); }
.htpane.focus .htpt::before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: var(--blue-light); flex: none; }
.htbody.many .htpane:not(.focus) .htx { opacity: .62; }
.htbody.zoomed .htsplit > .htdiv, .htbody.zoomed .htcell:not(:has(.htpane.focus)), .htbody.zoomed .htpane:not(.focus) { display: none; }
/* xterm measures the page in pixels: the window's text size (zoom on the
body) is undone here, and the terminal has its own size instead. */
.htx { flex: 1; min-height: 0; min-width: 0; padding: 4px 0 0 10px; zoom: var(--ht-unzoom, 1); }
.htx .xterm { height: 100%; }
.htx .xterm-viewport { scrollbar-width: thin; }
.htmsg { position: absolute; left: 50%; top: 40%; transform: translate(-50%, -50%); max-width: 80%; text-align: center; color: var(--muted); }
.htmsg b { display: block; color: var(--text); margin-bottom: 4px; }
.htpop, .htmenu { position: absolute; z-index: 30; top: 30px; background: var(--raised); border: 1px solid var(--line); border-radius: 10px; box-shadow: 0 14px 40px rgb(0 0 0 / .45); }
.htpop[hidden], .htmenu[hidden] { display: none; }
.htpop { right: 0; width: 248px; padding: 12px; }
.htpop .row { display: flex; align-items: center; gap: 8px; }
.htpop .lbl { color: var(--muted); font-size: var(--fs-small); margin-bottom: 6px; display: flex; justify-content: space-between; }
.htpop .lbl b { color: var(--text); font-variant-numeric: tabular-nums; }
.htpop input[type=range] { flex: 1; accent-color: var(--blue); }
.htpop .st { width: 24px; height: 24px; border-radius: 6px; border: 1px solid var(--line); background: var(--panel); color: var(--text); cursor: pointer; font: 600 var(--fs-head) var(--ui-font); }
.htpop hr { border: 0; border-top: 1px solid var(--line); margin: 10px 0; }
.htpop select { width: 100%; height: 26px; background: var(--panel); color: var(--text); border: 1px solid var(--line); border-radius: 6px; font: var(--fs) var(--ui-font); padding: 0 6px; }
.htpop .keys { color: var(--faint); font-size: var(--fs-small); margin-top: 8px; line-height: 1.8; }
.htmenu { left: 0; width: 230px; padding: 5px; max-height: 320px; overflow: auto; }
.htmenu .mi { display: flex; align-items: center; gap: 8px; width: 100%; height: 28px; padding: 0 8px; border: 0; border-radius: 6px; background: none; cursor: pointer; color: var(--text); font: var(--fs) var(--ui-font); text-align: left; }
.htmenu .mi:hover { background: var(--blue); color: #fff; }
.htmenu .mi .k { margin-left: auto; color: var(--faint); font-size: var(--fs-small); }
.htmenu .mi:hover .k { color: #dbe7ff; }
.htmenu .ml { color: var(--faint); font-size: var(--fs-small); padding: 6px 8px 3px; }
.htmenu hr { border: 0; border-top: 1px solid var(--line); margin: 4px 2px; }
.httoast { position: absolute; z-index: 40; top: 44px; left: 50%; transform: translateX(-50%); background: var(--raised); border: 1px solid var(--line); padding: 5px 12px; border-radius: 8px; font: 600 var(--fs) var(--ui-font); pointer-events: none; opacity: 0; transition: opacity .15s; }
.httoast.show { opacity: 1; }
.htfind { position: absolute; z-index: 20; top: 6px; right: 14px; display: flex; align-items: center; gap: 6px; background: var(--raised); border: 1px solid var(--line); border-radius: 8px; padding: 3px 4px 3px 10px; box-shadow: 0 8px 24px rgb(0 0 0 / .35); }
.htfind[hidden] { display: none; }
.htfind input { background: transparent; border: 0; outline: none; color: var(--text); width: 160px; font: var(--fs) var(--ui-font); -webkit-user-select: text; user-select: text; }
.htfind span { color: var(--faint); font-size: var(--fs-small); min-width: 46px; text-align: right; }
.htfind .sb { width: 22px; height: 22px; }
.htask { position: absolute; z-index: 25; left: 50%; top: 14px; transform: translateX(-50%); background: var(--raised); border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; box-shadow: 0 14px 40px rgb(0 0 0 / .45); width: min(420px, 90%); }
.htask p { margin-bottom: 6px; }
.htask pre { font: var(--fs-mono) var(--mono-font); color: var(--muted); max-height: 90px; overflow: hidden; white-space: pre-wrap; word-break: break-all; margin-bottom: 10px; }
.htask .acts { display: flex; justify-content: flex-end; gap: 8px; }
.htask .btn { height: 26px; padding: 0 12px; }
.statusbar .httoggle { display: inline-flex; align-items: center; gap: 5px; }
.statusbar .httoggle svg { width: 13px; height: 13px; }
.statusbar .httoggle kbd { font: 500 var(--fs-small) var(--ui-font); color: var(--faint); }
.statusbar .httoggle.on { color: var(--text); }
#strip-term svg { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; width: 17px; height: 17px; }
</style>
<style>/*XTERM_CSS*/</style>
</head>
<body data-vm="stopped">
@@ -1979,6 +2091,8 @@ body.beat { --beat: ring 1.6s ease-out; }
<div id="ctxcard" class="updcard" aria-live="polite" hidden></div>
<script>/*ICONS*/</script>
<!-- The built-in terminal's emulator: xterm.js and its add-ons (xterm/, spliced in by assemble.rs). -->
<script>/*XTERM_JS*/</script>
<script>
"use strict";
const $ = (id) => document.getElementById(id);
@@ -2195,6 +2309,7 @@ function applyPrefs() {
r.setProperty("--blue-hover", `color-mix(in srgb, ${accent} 88%, black)`);
r.setProperty("--blue-active", `color-mix(in srgb, ${accent} 78%, black)`);
r.setProperty("--blue-light", `color-mix(in srgb, ${accent} 60%, white)`);
window.htApply?.();
}
/* A right-click gets no browser menu (Reload, Back, Inspect): this is an app,
not a web page. Text fields and selected text keep theirs, for Copy and Paste. */
@@ -3148,6 +3263,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 +3291,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 +3380,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 +3401,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();
});
@@ -4366,6 +4488,7 @@ function renderStatus() {
usageItem(),
updateChip(),
pullItem(),
htStatusItem(),
`<span class="grow"></span>`,
shareOn() ? shStatusItem() : "",
`<span class="item"><i class="dot ${esc(vshown)}"></i>${esc(vmText)}</span>`,
@@ -5747,7 +5870,10 @@ window.kiri = {
if (ui.view === "images") render();
break;
case "removed": if (!batchHas("images", e.name)) removedToast(e); break;
case "textsize": stepTextSize(e.step); break;
// ⌘+ / ⌘− / ⌘0 size the terminal's text while it has the focus.
case "textsize": if (htHasFocus()) htStep(e.step); else stepTextSize(e.step); break;
case "term": htOn(e); break;
case "closekey": htCloseKey(); break;
case "enginerestarted": engineToast(e); break;
case "view": if (empty[e.view] || e.view === "settings") show(e.view); break;
case "prefs": Object.assign(prefs, e.prefs || {}); prefsIn = true; applyPrefs(); render(); paintEngine(); renderStatus(); break;
@@ -5768,6 +5894,8 @@ window.kiri = {
if (!e.manual && (prefs.updateSkip === r.version || (prefs.updateSnoozeUntil || 0) > Date.now())) break;
if (e.manual) { setPref("updateSkip", null); setPref("updateSnoozeUntil", null); }
if (ui.upd && ui.upd.phase !== "available") break;
// The 6-hourly check finds the same release: a card closed until the next launch stays closed.
if (!e.manual && ui.upd?.hidden && ui.upd.version === r.version) break;
ui.upd = { phase: "available", version: r.version, current: e.current, notes: r.notes || "", notesUrl: r.notes_url || "", hidden: false };
renderUpdate(); break;
}
@@ -5776,7 +5904,7 @@ window.kiri = {
if (ui.upd.phase !== "downloading") Object.assign(ui.upd, { phase: "downloading", t0: Date.now(), g0: e.got });
Object.assign(ui.upd, { got: e.got, total: e.total }); renderUpdate(); break;
case "updatestate": ui.updState = { ...e, checking: false }; if (ui.view === "settings" && prefs.tab === "about") render(); break;
case "updateready": ui.upd = { ...(ui.upd || {}), phase: "ready", version: e.version, hidden: false, error: "" }; renderUpdate(); break;
case "updateready": if (ui.upd?.phase === "ready" && ui.upd.version === e.version && ui.upd.hidden) break; ui.upd = { ...(ui.upd || {}), phase: "ready", version: e.version, hidden: false, error: "" }; renderUpdate(); break;
case "updatecancelled": if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: true }); renderUpdate(); break;
case "updateerror": if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: false, error: e.error }); else toast("error", e.error); renderUpdate(); break;
case "enginestale": ui.engineStale = e.version; ui.staleHidden = false; renderUpdate(); break;
@@ -5844,7 +5972,7 @@ window.kiri = {
case "exec": if (ui.detail?.id === e.id) finishExec(e); break;
case "files": if (ui.detail?.name === e.name) { Object.assign(ui.detail.files, { path: e.path, entries: e.entries, error: e.error, loading: false }); render(); } break;
case "preview": if (ui.detail?.name === e.name && ui.detail.files.selected === e.path) { ui.detail.files.preview = e; render(); } break;
case "fonts": fontLists.families = e.families || []; fontLists.mono = e.mono || []; if (ui.view === "settings") render(); break;
case "fonts": fontLists.families = e.families || []; fontLists.mono = e.mono || []; if (ui.view === "settings") render(); if (!htQ(".htpop").hidden) htFontMenu(); break;
case "about": about = e; if (ui.view === "settings") render(); break;
case "k8s": case "k8sop": case "k8slogs": case "k8slogs-end": k8sOn(e); break;
}
@@ -5957,6 +6085,7 @@ $("impstrip").addEventListener("click", (ev) => {
else if (ev.target.closest("[data-impdismiss]")) dismissImportStrip();
});
$("statusbar").addEventListener("click", (ev) => {
if (ev.target.closest("[data-htterm]")) return htToggle();
if (ev.target.closest("[data-shstatus]")) return $("sh-modal") ? shCard(null) : shCard("list");
if (ev.target.closest("[data-ctxswitch]")) return ctxDialog();
const el = ev.target.closest("[data-upd], [data-status-go], [data-open-site]");
@@ -8490,6 +8619,595 @@ function registriesPane() {
${rows}${form}</div>`;
}
/* --- The built-in terminal -----------------------------------------------------------
A shell on this computer in a panel under whatever page is open, like the
F4 terminal in Dolphin or VS Code's panel: tabs, each with its own shell,
split right and down, find, its own text size. ui/term.rs (Mac, Linux) and
kiri-win's term.rs (Windows) run the shells on a real terminal; xterm.js
draws them. The shells keep running while the panel is hidden. */
const HT_KEYS = WIN
? { toggle: "Ctrl+`", zin: "Ctrl+=", zout: "Ctrl+−", z0: "Ctrl+0", newtab: "Ctrl+Shift+T", close: "Ctrl+Shift+W", sr: "Alt+Shift+=", sd: "Alt+Shift+−", zoom: "Ctrl+Shift+Z", find: "Ctrl+Shift+F", mod: "Ctrl" }
: LINUX
? { toggle: "F4", zin: "Ctrl+=", zout: "Ctrl+−", z0: "Ctrl+0", newtab: "Ctrl+Shift+T", close: "Ctrl+Shift+W", sr: "Ctrl+Shift+(", sd: "Ctrl+Shift+)", zoom: "Ctrl+Shift+E", find: "Ctrl+Shift+F", mod: "Ctrl" }
: { toggle: "⌃`", zin: "⌘=", zout: "⌘−", z0: "⌘0", newtab: "⌘T", close: "⌘W", sr: "⌘D", sd: "⌘⇧D", zoom: "⌘⇧↵", find: "⌘F", mod: "⌘" };
const HT_SVG = (d) => `<svg viewBox="0 0 24 24" aria-hidden="true">${d}</svg>`;
const HT_ICON = {
term: HT_SVG('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9.5l3 2.5-3 2.5M12.5 15H17"/>'),
plus: HT_SVG('<path d="M12 5v14M5 12h14"/>'),
sr: HT_SVG('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16"/>'),
sd: HT_SVG('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18"/>'),
find: HT_SVG('<circle cx="11" cy="11" r="6"/><path d="M20 20l-4.5-4.5"/>'),
aa: HT_SVG('<path d="M3 18l5-12 5 12M4.8 14h6.4M15 18l3.5-8 3.5 8M16 15.5h5"/>'),
max: HT_SVG('<path d="M5 10V5h5M19 14v5h-5M5 5l6 6M19 19l-6-6"/>'),
restore: HT_SVG('<path d="M10 5v5H5M14 19v-5h5M4 4l6 6M20 20l-6-6"/>'),
hide: HT_SVG('<path d="M6 9l6 6 6-6"/>'),
up: HT_SVG('<path d="M6 15l6-6 6 6"/>'),
down: HT_SVG('<path d="M6 9l6 6 6-6"/>'),
x: HT_SVG('<path d="M7 7l10 10M17 7L7 17"/>'),
pin: HT_SVG('<path d="M9 4h6l-1 5 3 3v2H7v-2l3-3-1-5zM12 14v6"/>'),
};
const HT_FS = { min: 9, max: 24, def: 12 };
var ht = { open: false, max: false, zoom: false, tabs: [], at: 0, focus: null, shells: null, def: "", panes: new Map(), n: 0, wantTab: false, findQ: "" };
const htEl = document.createElement("section");
htEl.className = "htdrawer";
htEl.id = "htdrawer";
htEl.hidden = true;
htEl.setAttribute("aria-label", "Terminal");
htEl.innerHTML = `<div class="htgrip" title="Drag to resize"></div>
<div class="hthead">
<div class="httabs" role="tablist"></div>
<div class="htwrap"><button class="sb" data-ht="menu" title="New tab (${HT_KEYS.newtab})" aria-label="New tab">${HT_ICON.plus}</button><div class="htmenu" hidden></div></div>
<div class="grow"></div>
<button class="sb" data-ht="sr" title="Split right (${HT_KEYS.sr})" aria-label="Split right">${HT_ICON.sr}</button>
<button class="sb" data-ht="sd" title="Split down (${HT_KEYS.sd})" aria-label="Split down">${HT_ICON.sd}</button>
<span class="sep"></span>
<button class="sb" data-ht="find" title="Find (${HT_KEYS.find})" aria-label="Find">${HT_ICON.find}</button>
<div class="htwrap"><button class="sb" data-ht="aa" title="Text size" aria-label="Text size">${HT_ICON.aa}</button>
<div class="htpop" hidden>
<div class="lbl">Text size <b class="htfsv"></b></div>
<div class="row"><button class="st" data-ht="zout" aria-label="Smaller">−</button><input type="range" min="${HT_FS.min}" max="${HT_FS.max}" step="1" aria-label="Text size"><button class="st" data-ht="zin" aria-label="Bigger">+</button></div>
<hr>
<div class="lbl">Font</div>
<select class="htfont" aria-label="Font"></select>
<div class="keys">${esc(HT_KEYS.zout)} smaller · ${esc(HT_KEYS.zin)} bigger · ${esc(HT_KEYS.z0)} reset<br>or hold ${esc(HT_KEYS.mod)} and scroll</div>
</div></div>
<button class="sb" data-ht="max" title="Maximise" aria-label="Maximise">${HT_ICON.max}</button>
<button class="sb" data-ht="hide" title="Hide (${HT_KEYS.toggle})" aria-label="Hide">${HT_ICON.hide}</button>
</div>
<div class="htbody"><div class="htfind" hidden><input placeholder="Find" spellcheck="false" aria-label="Find in the terminal"><span class="htcount"></span><button class="sb" data-ht="prev" aria-label="Previous match">${HT_ICON.up}</button><button class="sb" data-ht="next" aria-label="Next match">${HT_ICON.down}</button><button class="sb" data-ht="findx" aria-label="Close find">${HT_ICON.x}</button></div></div>
<div class="httoast" aria-live="polite"></div>
<div class="htctx" role="menu" hidden></div>`;
$("impstrip").after(htEl);
const htQ = (s) => htEl.querySelector(s);
const htBody = htQ(".htbody");
/* The strip's button, next to Settings. */
const htStripBtn = Object.assign(document.createElement("button"), { className: "sb", id: "strip-term", title: `Terminal (${HT_KEYS.toggle})`, innerHTML: HT_ICON.term });
htStripBtn.setAttribute("aria-label", "Terminal");
htStripBtn.setAttribute("aria-pressed", "false");
$("strip-settings").before(htStripBtn);
htStripBtn.addEventListener("click", () => htToggle());
const htFs = () => Math.max(HT_FS.min, Math.min(HT_FS.max, Number(prefs.termFs) || HT_FS.def));
const htFont = () => prefs.termFont || getComputedStyle(document.documentElement).getPropertyValue("--mono-font").trim() || "monospace";
function htTheme() {
const css = getComputedStyle(document.documentElement), v = (n) => css.getPropertyValue(n).trim();
const dark = darkNow();
return { background: v("--term-bg") || (dark ? "#0B0F13" : "#FFFFFF"), foreground: v("--term-fg") || (dark ? "#D7DCE1" : "#1F2328"),
cursor: dark ? "#D7DCE1" : "#1F2328", cursorAccent: dark ? "#0B0F13" : "#FFFFFF",
selectionBackground: dark ? "rgba(110,168,254,.35)" : "rgba(13,110,253,.22)" };
}
let htToastT;
function htToast(text) {
const t = htQ(".httoast");
t.textContent = text;
t.classList.add("show");
clearTimeout(htToastT);
htToastT = setTimeout(() => t.classList.remove("show"), 900);
}
/* Bytes to and from the app go as base64 (termwire.rs). */
function htB64(text) {
const bytes = new TextEncoder().encode(text);
let bin = "";
for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
return btoa(bin);
}
const htUnB64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
const htLeaves = (nd, out = []) => (nd.t === "pane" ? out.push(nd.id) : (htLeaves(nd.a, out), htLeaves(nd.b, out)), out);
const htTab = () => ht.tabs[ht.at];
const htPane = (id = ht.focus) => ht.panes.get(id);
const htShellLabel = (id) => ht.shells?.find((s) => s.id === id)?.label || id.split(/[\\/]/).pop();
/* A pane: its element, kept across re-renders, and its terminal. */
function htNewPane(shell) {
const id = `t${++ht.n}`;
const el = document.createElement("div");
el.className = "htpane";
el.dataset.id = id;
el.innerHTML = `<div class="htpt"><span class="htname"></span><button class="htpx" data-htpx title="Close (${esc(HT_KEYS.close)})" aria-label="Close pane">${HT_ICON.x}</button></div><div class="htx"></div>`;
const p = { id, shell, el, term: null, fit: null, search: null, title: "", exited: false, opened: false };
ht.panes.set(id, p);
return p;
}
function htStart(p) {
if (p.term || typeof Terminal !== "function") return;
const term = new Terminal({ fontFamily: htFont(), fontSize: htFs(), theme: htTheme(), cursorBlink: true, scrollback: 10000, allowProposedApi: true,
macOptionIsMeta: false, rightClickSelectsWord: false, drawBoldTextInBrightColors: true });
p.term = term;
p.fit = new FitAddon.FitAddon();
p.search = new SearchAddon.SearchAddon();
term.loadAddon(p.fit);
term.loadAddon(p.search);
// Links in the output open in the browser; the app only opens http(s).
term.loadAddon(new WebLinksAddon.WebLinksAddon((ev, uri) => { ev.preventDefault?.(); send("term", { name: "link", value: uri }); }));
term.open(p.el.querySelector(".htx"));
term.attachCustomKeyEventHandler((ev) => htKey(ev, p));
term.onData((d) => !p.exited && send("term", { name: "input", id: p.id, value: htB64(d) }));
term.onBinary((d) => !p.exited && send("term", { name: "input", id: p.id, value: btoa(d) }));
term.onResize(({ cols, rows }) => p.opened && send("term", { name: "resize", id: p.id, value: { cols, rows } }));
term.onTitleChange((t) => { p.title = t; htTitles(); });
term.textarea?.addEventListener("focus", () => htSetFocus(p.id, false));
p.search.onDidChangeResults?.(({ resultIndex, resultCount }) => { if (p.id === ht.focus) htQ(".htcount").textContent = resultCount ? `${resultIndex + 1} of ${resultCount}` : ht.findQ ? "No results" : ""; });
htFitOne(p);
send("term", { name: "open", id: p.id, value: { shell: p.shell, cols: term.cols, rows: term.rows } });
p.opened = true;
}
function htFitOne(p) {
if (!p.term || !p.el.isConnected || !p.el.offsetWidth) return;
try { p.fit.fit(); } catch { /* not laid out yet */ }
}
function htFitAll() { for (const id of htTab() ? htLeaves(htTab().tree) : []) htFitOne(htPane(id)); }
let htFitQueued = false;
function htQueueFit() {
if (htFitQueued) return;
htFitQueued = true;
requestAnimationFrame(() => { htFitQueued = false; htFitAll(); });
}
new ResizeObserver(htQueueFit).observe(htBody);
function htTitles() {
for (const id of htTab() ? htLeaves(htTab().tree) : []) {
const p = htPane(id);
p.el.querySelector(".htname").textContent = p.title || htShellLabel(p.shell);
}
}
function htRenderTabs() {
setHTML(htQ(".httabs"), ht.tabs.map((t, i) => {
const p = htPane(htLeaves(t.tree)[0]);
return `<button class="httab${i === ht.at ? " on" : ""}" role="tab" aria-selected="${i === ht.at}" data-httab="${i}" title="${esc(p?.title || "")}">${esc(htShellLabel(t.shell))}${t.pinned ? `<span class="pin" title="Pinned: right-click to unpin" aria-label="Pinned">${HT_ICON.pin}</span>` : `<span class="x" data-htx="${i}" title="Close (${esc(HT_KEYS.close)})" aria-label="Close tab">${HT_ICON.x}</span>`}</button>`;
}).join(""));
}
function htRender() {
htRenderTabs();
for (const el of [...htBody.children]) if (!el.classList.contains("htfind")) el.remove();
const t = htTab();
if (!t) return;
const ids = htLeaves(t.tree);
if (!ids.includes(ht.focus)) ht.focus = ids[ids.length - 1];
const node = (nd) => {
if (nd.t === "pane") {
const p = htPane(nd.id);
p.el.classList.toggle("focus", nd.id === ht.focus);
return p.el;
}
const s = document.createElement("div");
s.className = `htsplit ${nd.d}`;
const cell = (child, r) => { const c = document.createElement("div"); c.className = "htcell"; c.style.flex = `${r} 1 0`; c.append(node(child)); return c; };
const div = document.createElement("div");
div.className = "htdiv";
div.addEventListener("mousedown", (ev) => htDragDivider(ev, nd, div));
s.append(cell(nd.a, nd.r), div, cell(nd.b, 1 - nd.r));
return s;
};
htBody.append(node(t.tree));
htBody.classList.toggle("many", ids.length > 1);
htBody.classList.toggle("zoomed", ht.zoom && ids.length > 1);
htTitles();
for (const id of ids) htStart(htPane(id));
htFitAll();
}
function htDragDivider(ev, nd, div) {
ev.preventDefault();
div.classList.add("drag");
const box = div.parentElement.getBoundingClientRect();
const move = (e) => {
nd.r = Math.max(0.15, Math.min(0.85, nd.d === "h" ? (e.clientX - box.left) / box.width : (e.clientY - box.top) / box.height));
div.previousElementSibling.style.flex = `${nd.r} 1 0`;
div.nextElementSibling.style.flex = `${1 - nd.r} 1 0`;
};
const up = () => { div.classList.remove("drag"); removeEventListener("mousemove", move); removeEventListener("mouseup", up); htFitAll(); htPane()?.term?.focus(); };
addEventListener("mousemove", move);
addEventListener("mouseup", up);
}
function htSetFocus(id, focusTerm = true) {
if (!htPane(id)) return;
ht.focus = id;
htBody.querySelectorAll(".htpane").forEach((el) => el.classList.toggle("focus", el.dataset.id === id));
if (focusTerm) htPane(id).term?.focus();
}
const htHasFocus = () => !htEl.hidden && htEl.contains(document.activeElement);
function htShow(open) {
ht.open = open;
htEl.hidden = !open;
htStripBtn.setAttribute("aria-pressed", String(open));
renderStatus();
if (!open) return;
if (!ht.tabs.length) htNewTab();
else { htRender(); requestAnimationFrame(() => htPane()?.term?.focus()); }
}
function htToggle() {
if (ht.open && !htHasFocus() && htPane()) return htPane().term?.focus();
htShow(!ht.open);
if (!ht.open) document.activeElement?.blur?.();
}
function htNewTab(shell) {
if (!ht.shells) { ht.wantTab = shell || true; return send("term", { name: "shells" }); }
const p = htNewPane(shell || ht.def);
ht.tabs.push({ shell: p.shell, tree: { t: "pane", id: p.id } });
ht.at = ht.tabs.length - 1;
ht.focus = p.id;
ht.zoom = false;
if (!ht.open) { ht.open = true; htEl.hidden = false; htStripBtn.setAttribute("aria-pressed", "true"); renderStatus(); }
htRender();
requestAnimationFrame(() => p.term?.focus());
}
function htReplace(tree, id, fn) {
if (tree.t === "pane") return tree.id === id ? fn(tree) : tree;
return { ...tree, a: htReplace(tree.a, id, fn), b: htReplace(tree.b, id, fn) };
}
function htSplit(d) {
const t = htTab();
if (!t) return htNewTab();
const p = htNewPane(htPane()?.shell || t.shell);
t.tree = htReplace(t.tree, ht.focus, (leaf) => ({ t: "split", d, r: 0.5, a: leaf, b: { t: "pane", id: p.id } }));
ht.focus = p.id;
ht.zoom = false;
htRender();
requestAnimationFrame(() => p.term?.focus());
}
/* Ends a pane's shell and takes it out of its tab; the last pane closes the tab. */
function htDrop(id, hang = true) {
const p = htPane(id);
if (!p) return;
// A pinned tab's last pane is closed only by unpinning first (or its shell ending).
const owner = ht.tabs.find((t) => htLeaves(t.tree).includes(id));
if (hang && owner?.pinned && owner.tree.t === "pane") return htToast("Pinned: unpin the tab to close it");
if (hang && !p.exited) send("term", { name: "close", id });
p.term?.dispose();
ht.panes.delete(id);
const ti = ht.tabs.findIndex((t) => htLeaves(t.tree).includes(id));
if (ti < 0) return;
const t = ht.tabs[ti];
if (t.tree.t === "pane") {
ht.tabs.splice(ti, 1);
if (ht.at >= ti) ht.at = Math.max(0, ht.at - 1);
} else {
const rm = (nd) => (nd.t === "pane" ? nd : nd.a.t === "pane" && nd.a.id === id ? nd.b : nd.b.t === "pane" && nd.b.id === id ? nd.a : { ...nd, a: rm(nd.a), b: rm(nd.b) });
t.tree = rm(t.tree);
}
if (ht.focus === id) ht.focus = null;
if (!ht.tabs.length) { ht.zoom = false; htRender(); htShow(false); return; }
htRender();
if (ht.open) requestAnimationFrame(() => htPane()?.term?.focus());
}
function htCloseTab(i) {
const t = ht.tabs[i];
if (!t) return;
ht.at = i;
for (const id of htLeaves(t.tree)) htDrop(id);
}
function htMove(dir) {
const ids = htTab() ? htLeaves(htTab().tree) : [];
const from = htPane()?.el.getBoundingClientRect();
if (!from || ids.length < 2) return;
const cx = from.left + from.width / 2, cy = from.top + from.height / 2;
let best = null, bestD = Infinity;
for (const id of ids) {
if (id === ht.focus) continue;
const r = htPane(id).el.getBoundingClientRect(), x = r.left + r.width / 2, y = r.top + r.height / 2;
const ok = { left: x < cx - 1, right: x > cx + 1, up: y < cy - 1, down: y > cy + 1 }[dir];
const d = Math.hypot(x - cx, y - cy);
if (ok && d < bestD) { best = id; bestD = d; }
}
if (best) htSetFocus(best);
}
function htSetFs(v, quiet) {
const fs = Math.max(HT_FS.min, Math.min(HT_FS.max, v));
if (fs !== htFs()) { prefs.termFs = fs; send("setpref", { name: "termFs", value: fs }); }
for (const p of ht.panes.values()) if (p.term) p.term.options.fontSize = fs;
htQ("input[type=range]").value = fs;
htQ(".htfsv").textContent = `${fs} px`;
htQueueFit();
if (!quiet) htToast(`Text size ${fs} px`);
}
const htStep = (step) => htSetFs(step === 0 ? HT_FS.def : htFs() + step);
/* The window's text size is CSS zoom on the body; xterm measures in real
pixels, so its element undoes the zoom (and has its own size instead). */
function htApply() {
htEl.style.setProperty("--ht-h", `${Math.max(120, Number(prefs.termH) || 300)}px`);
htEl.style.setProperty("--ht-unzoom", String(1 / (Number(prefs.scale) || 1)));
const theme = htTheme(), font = htFont();
for (const p of ht.panes.values()) if (p.term) { p.term.options.theme = theme; p.term.options.fontFamily = font; }
htQueueFit();
}
window.htApply = htApply;
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", htApply);
function htMax(on = !ht.max) {
ht.max = on;
htEl.classList.toggle("max", on);
const b = htQ('[data-ht="max"]');
b.innerHTML = on ? HT_ICON.restore : HT_ICON.max;
b.title = on ? "Restore" : "Maximise";
b.setAttribute("aria-label", b.title);
htQueueFit();
}
function htFind(open = true) {
const f = htQ(".htfind");
f.hidden = !open;
if (open) { const i = f.querySelector("input"); i.focus(); i.select(); }
else { htPane()?.search?.clearDecorations(); htQ(".htcount").textContent = ""; htPane()?.term?.focus(); }
}
const HT_DECO = { matchBackground: "#6EA8FE55", activeMatchBackground: "#FFC23D", matchOverviewRuler: "#6EA8FE", activeMatchColorOverviewRuler: "#FFC23D" };
function htFindGo(back) {
const s = htPane()?.search, q = htQ(".htfind input").value;
ht.findQ = q;
if (!s) return;
if (!q) { s.clearDecorations(); htQ(".htcount").textContent = ""; return; }
const found = back ? s.findPrevious(q, { decorations: HT_DECO }) : s.findNext(q, { decorations: HT_DECO, incremental: false });
if (!found) htQ(".htcount").textContent = "No results";
}
htQ(".htfind input").addEventListener("input", () => {
const s = htPane()?.search, q = htQ(".htfind input").value;
ht.findQ = q;
if (!s) return;
if (!q) { s.clearDecorations(); htQ(".htcount").textContent = ""; return; }
if (!s.findNext(q, { decorations: HT_DECO, incremental: true })) htQ(".htcount").textContent = "No results";
});
htQ(".htfind input").addEventListener("keydown", (ev) => {
ev.stopPropagation();
if (ev.key === "Enter") { ev.preventDefault(); htFindGo(ev.shiftKey); }
else if (ev.key === "Escape") { ev.preventDefault(); htFind(false); }
});
/* Pasting more than one line runs each line as a command: ask first. */
function htPaste(id, text) {
const p = htPane(id);
if (!p?.term || !text || p.exited) return;
const lines = text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n").length;
if (lines < 2) return p.term.paste(text);
p.el.querySelector(".htask")?.remove();
const ask = document.createElement("div");
ask.className = "htask";
ask.setAttribute("role", "alertdialog");
ask.innerHTML = `<p>Paste ${lines} lines? Each line runs as a command.</p><pre>${esc(text.slice(0, 400))}</pre><div class="acts"><button class="btn" data-htask="no">Cancel</button><button class="btn primary" data-htask="yes">Paste</button></div>`;
p.el.append(ask);
const done = (yes) => { ask.remove(); if (yes) p.term.paste(text); p.term.focus(); };
ask.addEventListener("click", (ev) => { const b = ev.target.closest("[data-htask]"); if (b) done(b.dataset.htask === "yes"); });
ask.addEventListener("keydown", (ev) => { ev.stopPropagation(); if (ev.key === "Escape") done(false); else if (ev.key === "Enter") done(true); });
ask.querySelector('[data-htask="yes"]').focus();
}
function htCopy(p) {
const text = p.term?.getSelection();
if (!text) return false;
send("term", { name: "copy", value: text });
htToast("Copied");
return true;
}
/* The browser's own paste (a menu, or a key the WebView handles itself)
goes through the same check. */
htEl.addEventListener("paste", (ev) => {
if (!ev.target.closest?.(".htx")) return;
ev.preventDefault();
ev.stopPropagation();
const id = ev.target.closest(".htpane")?.dataset.id;
htPaste(id, ev.clipboardData?.getData("text/plain") || "");
}, true);
/* The panel's keys (HT_KEYS), per system. */
function htAction(ev) {
const k = ev.key, low = k.length === 1 ? k.toLowerCase() : k;
const mod = WIN || LINUX ? ev.ctrlKey && !ev.metaKey : ev.metaKey && !ev.ctrlKey;
const arrow = { ArrowLeft: "left", ArrowRight: "right", ArrowUp: "up", ArrowDown: "down" }[k];
if (WIN || LINUX) {
if (ev.ctrlKey && ev.shiftKey && !ev.altKey) {
const a = { t: "newtab", w: "close", f: "find", c: "copy", v: "paste", [LINUX ? "e" : "z"]: "zoom" }[low];
if (a) return a;
if (LINUX && (k === "(" || k === "9")) return "sr";
if (LINUX && (k === ")" || k === "0")) return "sd";
}
if (WIN && ev.altKey && ev.shiftKey && !ev.ctrlKey && (k === "+" || k === "=" || ev.code === "Equal")) return "sr";
if (WIN && ev.altKey && ev.shiftKey && !ev.ctrlKey && (k === "_" || k === "-" || ev.code === "Minus")) return "sd";
if (ev.altKey && !ev.ctrlKey && !ev.shiftKey && arrow) return `move-${arrow}`;
if (WIN && ev.ctrlKey && !ev.shiftKey && !ev.altKey && low === "v") return "paste";
if (WIN && ev.ctrlKey && !ev.shiftKey && !ev.altKey && low === "c") return "copysel";
} else {
if (mod && !ev.altKey && !ev.shiftKey) {
const a = { t: "newtab", w: "close", d: "sr", f: "find", c: "copy", v: "paste" }[low];
if (a) return a;
}
if (mod && ev.shiftKey && !ev.altKey && low === "d") return "sd";
if (mod && ev.shiftKey && k === "Enter") return "zoom";
if (mod && ev.altKey && arrow) return `move-${arrow}`;
}
if (mod && !ev.altKey && (k === "=" || k === "+")) return "zin";
if (mod && !ev.altKey && !ev.shiftKey && k === "-") return "zout";
if (mod && !ev.altKey && !ev.shiftKey && k === "0") return "z0";
return null;
}
const htToggleKey = (ev) => (ev.ctrlKey && !ev.metaKey && !ev.altKey && (ev.code === "Backquote" || ev.key === "`")) || (LINUX && ev.key === "F4" && !ev.ctrlKey && !ev.altKey && !ev.shiftKey && !ev.metaKey);
function htKey(ev, p) {
if (ev.type !== "keydown") return true;
if (htToggleKey(ev)) { ev.preventDefault(); ev.stopPropagation(); htToggle(); return false; }
const a = htAction(ev);
if (!a) return true;
// Ctrl+C copies only with a selection; otherwise it is the shell's interrupt.
if (a === "copysel" && !p.term.hasSelection()) return true;
ev.preventDefault();
ev.stopPropagation();
htDo(a, p);
return false;
}
function htDo(a, p = htPane()) {
if (a === "copy" || a === "copysel") { if (p) htCopy(p); }
else if (a === "paste") { if (p) send("term", { name: "paste", id: p.id }); }
else if (a === "newtab") htNewTab();
else if (a === "close") { if (p) htDrop(p.id); }
else if (a === "sr") htSplit("h");
else if (a === "sd") htSplit("v");
else if (a === "find") htFind(true);
else if (a === "zoom") { if (htTab() && htLeaves(htTab().tree).length > 1) { ht.zoom = !ht.zoom; htRender(); htToast(ht.zoom ? "Pane zoomed" : "Pane restored"); requestAnimationFrame(() => htPane()?.term?.focus()); } }
else if (a === "zin") htStep(1);
else if (a === "zout") htStep(-1);
else if (a === "z0") htStep(0);
else if (a.startsWith("move-")) htMove(a.slice(5));
}
/* The toggle works from anywhere in the window. */
document.addEventListener("keydown", (ev) => {
if (htToggleKey(ev)) { ev.preventDefault(); htToggle(); }
});
htBody.addEventListener("wheel", (ev) => {
if (!(WIN || LINUX ? ev.ctrlKey : ev.metaKey || ev.ctrlKey)) return;
ev.preventDefault();
ev.stopPropagation();
htStep(ev.deltaY < 0 ? 1 : -1);
}, { passive: false, capture: true });
/* Right-click a tab: pin it (first in the row, no ×), or close it. */
function htPin(i, on) {
const t = ht.tabs[i];
if (!t) return;
const cur = htTab();
t.pinned = on;
ht.tabs.splice(i, 1);
const lastPinned = ht.tabs.reduce((n, x, j) => (x.pinned ? j + 1 : n), 0);
ht.tabs.splice(lastPinned, 0, t);
ht.at = ht.tabs.indexOf(cur);
htRender();
htToast(on ? "Tab pinned" : "Tab unpinned");
}
function htCtx(ev, i) {
const m = htQ(".htctx"), t = ht.tabs[i], box = htEl.getBoundingClientRect(), zoom = Number(prefs.scale) || 1;
setHTML(m, `<button class="mi" role="menuitem" data-htpin="${i}">${t.pinned ? "Unpin tab" : "Pin tab"}</button><button class="mi" role="menuitem" data-htclose="${i}"${t.pinned ? " disabled" : ""}>Close tab</button>`);
m.hidden = false;
m.style.left = `${Math.min(ev.clientX - box.left, box.width - 180) / zoom}px`;
m.style.top = `${(ev.clientY - box.top) / zoom}px`;
}
htQ(".httabs").addEventListener("contextmenu", (ev) => {
const tab = ev.target.closest("[data-httab]");
if (!tab) return;
ev.preventDefault();
ev.stopPropagation();
htCtx(ev, Number(tab.dataset.httab));
});
htQ(".htctx").addEventListener("click", (ev) => {
const pin = ev.target.closest("[data-htpin]"), close = ev.target.closest("[data-htclose]");
htQ(".htctx").hidden = true;
if (pin) htPin(Number(pin.dataset.htpin), !ht.tabs[Number(pin.dataset.htpin)].pinned);
else if (close && !close.disabled) htCloseTab(Number(close.dataset.htclose));
});
function htMenu() {
const m = htQ(".htmenu"), list = ht.shells || [];
const item = (s, i) => `<button class="mi" data-htshell="${esc(s.id)}">${esc(s.label)}${i === 0 ? `<span class="k">${esc(HT_KEYS.newtab)}</span>` : ""}</button>`;
const def = list.find((s) => s.id === ht.def);
const rest = list.filter((s) => s !== def);
const plain = rest.filter((s) => !s.group), groups = [...new Set(rest.filter((s) => s.group).map((s) => s.group))];
setHTML(m, [def ? item(def, 0) : "", ...plain.map((s) => item(s, 1)),
...groups.map((g) => `<hr><div class="ml">${esc(g)}</div>${rest.filter((s) => s.group === g).map((s) => item(s, 1)).join("")}`)].join("") || `<div class="ml">Looking for shells…</div>`);
}
function htFontMenu() {
const sel = htQ(".htfont"), names = fontLists.mono.length ? fontLists.mono : [];
const cur = prefs.termFont || "";
setHTML(sel, `<option value="">Same as the window (${esc(prefs.mono || "System Mono")})</option>` + names.map((n) => `<option value="${esc(n)}"${n === cur ? " selected" : ""}>${esc(n)}</option>`).join(""));
sel.value = cur;
}
htEl.addEventListener("click", (ev) => {
const t = ev.target;
// A split pane's own ×, in its title bar.
const px = t.closest("[data-htpx]");
if (px) { ev.stopPropagation(); return htDrop(px.closest(".htpane").dataset.id); }
const x = t.closest("[data-htx]");
if (x) { ev.stopPropagation(); return htCloseTab(Number(x.dataset.htx)); }
const tab = t.closest("[data-httab]");
if (tab) { ht.at = Number(tab.dataset.httab); ht.focus = null; ht.zoom = false; htRender(); requestAnimationFrame(() => htPane()?.term?.focus()); return; }
const sh = t.closest("[data-htshell]");
if (sh) { htQ(".htmenu").hidden = true; return htNewTab(sh.dataset.htshell); }
const b = t.closest("[data-ht]");
if (!t.closest(".htpop, .htmenu") && b?.dataset.ht !== "menu" && b?.dataset.ht !== "aa") htEl.querySelectorAll(".htpop, .htmenu").forEach((m) => (m.hidden = true));
if (b) {
const k = b.dataset.ht;
if (k === "menu") { const m = htQ(".htmenu"); htQ(".htpop").hidden = true; m.hidden = !m.hidden; if (!m.hidden) { htMenu(); if (!ht.shells) send("term", { name: "shells" }); } }
else if (k === "aa") { const pop = htQ(".htpop"); htQ(".htmenu").hidden = true; pop.hidden = !pop.hidden; if (!pop.hidden) { htSetFs(htFs(), true); htFontMenu(); if (!fontLists.mono.length) send("fonts"); } }
else if (k === "max") htMax();
else if (k === "hide") htShow(false);
else if (k === "prev") htFindGo(true);
else if (k === "next") htFindGo(false);
else if (k === "findx") htFind(false);
else htDo(k);
return;
}
const pane = t.closest(".htpane");
if (pane && !t.closest(".htask")) htSetFocus(pane.dataset.id);
});
htQ("input[type=range]").addEventListener("input", (ev) => htSetFs(Number(ev.target.value)));
htQ(".htfont").addEventListener("change", (ev) => { prefs.termFont = ev.target.value; send("setpref", { name: "termFont", value: ev.target.value }); htApply(); });
document.addEventListener("mousedown", (ev) => {
if (!ev.target.closest?.(".htwrap")) htEl.querySelectorAll(".htpop, .htmenu").forEach((m) => (m.hidden = true));
if (!ev.target.closest?.(".htctx")) htQ(".htctx").hidden = true;
});
/* The grip on the top edge sets the panel's height. */
htQ(".htgrip").addEventListener("mousedown", (ev) => {
ev.preventDefault();
// Mouse positions are the screen's; the panel's height is in the zoomed page's pixels.
const zoom = Number(prefs.scale) || 1, startY = ev.clientY, startH = Math.max(120, Number(prefs.termH) || 300);
const maxH = () => htEl.parentElement.getBoundingClientRect().height / zoom - 80;
let h = startH;
const move = (e) => { h = Math.round(Math.max(120, Math.min(maxH(), startH + (startY - e.clientY) / zoom))); htEl.style.setProperty("--ht-h", `${h}px`); };
const up = () => { removeEventListener("mousemove", move); removeEventListener("mouseup", up); prefs.termH = h; send("setpref", { name: "termH", value: h }); htFitAll(); htPane()?.term?.focus(); };
addEventListener("mousemove", move);
addEventListener("mouseup", up);
});
/* What the app says back (termwire.rs). */
function htOn(e) {
if (e.ev === "shells") {
ht.shells = e.shells || [];
ht.def = e.default || ht.shells[0]?.id || "";
if (!htQ(".htmenu").hidden) htMenu();
if (ht.wantTab) { const want = ht.wantTab; ht.wantTab = false; htNewTab(want === true ? undefined : want); }
return;
}
const p = htPane(e.id);
if (!p?.term) return;
if (e.ev === "data") p.term.write(htUnB64(e.b64));
else if (e.ev === "paste") htPaste(e.id, e.text || "");
else if (e.ev === "exit") {
p.exited = true;
// A shell that ends by itself closes its pane, as other terminals do;
// one that couldn't start says why.
if (e.error) p.term.write(`\r\n\x1b[31mCouldn't start ${htShellLabel(p.shell)}: ${String(e.error).replace(/[\x00-\x1f]/g, " ")}\x1b[0m\r\n`);
else htDrop(p.id, false);
}
}
/* ⌘W on the Mac comes here first from the menu (mac.rs). */
function htCloseKey() {
if (htHasFocus() && htPane()) htDrop(ht.focus);
else send("closewindow");
}
function htStatusItem() {
// renderStatus can run before this part of the script has.
if (!ht) return "";
return `<button class="item httoggle${ht.open ? " on" : ""}" data-htterm title="${ht.open ? "Hide" : "Show"} the terminal (${esc(HT_KEYS.toggle)})">${HT_ICON.term}<span>Terminal</span><kbd>${esc(HT_KEYS.toggle)}</kbd></button>`;
}
htApply();
// Shells from before a reload have nothing on screen any more.
send("term", { name: "closeall" });
document.querySelectorAll("svg[data-ph]").forEach((el) => (el.innerHTML = `<path d="${PH[el.dataset.ph]}"/>`));
render();
send("ready");
+29 -3
View File
@@ -19,7 +19,7 @@ use objc2_app_kit::{
use objc2_foundation::{NSNotification, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString};
use objc2_web_kit::{WKScriptMessage, WKScriptMessageHandler, WKUserContentController, WKWebView, WKWebViewConfiguration};
use super::{Cmd, ICONS_JS, PAGE, diag, emit, engine, json_str, menu_state, prefs, reopen_after_exit, update_check};
use super::{Cmd, PAGE, diag, emit, engine, json_str, menu_state, prefs, reopen_after_exit, update_check};
thread_local! {
/// The page, reachable from closures the engine thread schedules on the
@@ -123,7 +123,7 @@ fn make_window(mtm: MainThreadMarker, tx: Sender<Cmd>, autostart: bool, view: Op
// Let the page paint its own background instead of white.
let no: Retained<AnyObject> = msg_send![objc2::class!(NSNumber), numberWithBool: false];
let _: () = msg_send![&webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")];
webview.loadHTMLString_baseURL(&NSString::from_str(&PAGE.replacen("/*ICONS*/", ICONS_JS, 1)), None);
webview.loadHTMLString_baseURL(&NSString::from_str(&super::assemble::page(PAGE)), None);
webview
};
window.setContentView(Some(&webview));
@@ -259,7 +259,8 @@ fn main_menu(mtm: MainThreadMarker) -> Retained<NSMenu> {
app_menu.addItem(&item("Settings…", sel!(openSettings:), ","));
app_menu.addItem(&NSMenuItem::separatorItem(mtm));
app_menu.addItem(&item(&format!("Hide {}", crate::flavor::APP), sel!(hide:), "h"));
app_menu.addItem(&item("Close Window", sel!(performClose:), "w"));
// ⌘W asks the page first: in the built-in terminal it closes a pane.
app_menu.addItem(&item("Close Window", sel!(closeKey:), "w"));
app_menu.addItem(&NSMenuItem::separatorItem(mtm));
app_menu.addItem(&item(&format!("Quit {}", crate::flavor::APP), sel!(terminate:), "q"));
let app_item = NSMenuItem::new(mtm);
@@ -317,6 +318,15 @@ pub(super) fn drag() {
});
}
/// Closes the window, as the menu's Close Window did before ⌘W went to the page.
pub(super) fn close_window() {
WINDOW.with(|w| {
if let Some(window) = w.borrow().as_ref() {
window.performClose(None);
}
});
}
pub(super) fn zoom() {
WINDOW.with(|w| {
if let Some(window) = w.borrow().as_ref() {
@@ -334,6 +344,15 @@ pub(super) fn copy(text: &str) {
}
}
/// The clipboard's text, handed to `done` off the main thread.
pub(super) fn paste(done: impl FnOnce(String) + Send + 'static) {
std::thread::spawn(move || {
if let Ok(out) = std::process::Command::new("/usr/bin/pbpaste").output() {
done(String::from_utf8_lossy(&out.stdout).into_owned());
}
});
}
/// The installed font families, sorted; `mono` keeps the fixed-pitch ones.
pub(super) fn font_families(mono: bool) -> Vec<String> {
use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFString, CFType};
@@ -494,6 +513,13 @@ define_class!(
std::thread::spawn(|| update_check(true));
}
/// ⌘W: the page closes the terminal's pane when it has the focus,
/// and otherwise asks for the window to close (`close_window`).
#[unsafe(method(closeKey:))]
fn close_key(&self, _sender: Option<&AnyObject>) {
emit(r#"{"type":"closekey"}"#.to_owned());
}
#[unsafe(method(textBigger:))]
fn text_bigger(&self, _sender: Option<&AnyObject>) {
emit(r#"{"type":"textsize","step":1}"#.to_owned());
+46 -6
View File
@@ -30,7 +30,12 @@ mod linux;
#[cfg(target_os = "linux")]
use linux::{import, setup, update};
mod assemble;
#[cfg(unix)]
mod term;
mod termwire;
mod brands;
mod recheck;
mod detail;
mod hub;
mod k8s;
@@ -44,8 +49,6 @@ use crate::client;
use crate::diag;
const PAGE: &str = include_str!("index.html");
/// The page's UI icons, spliced into its `/*ICONS*/` placeholder.
const ICONS_JS: &str = include_str!("icons.js");
/// How often the VM panel's figures refresh. The lists refresh on events.
const TICK: Duration = Duration::from_secs(2);
@@ -438,7 +441,7 @@ pub(crate) fn prefs() -> serde_json::Value {
}
fn set_pref(name: &str, value: serde_json::Value) {
if !matches!(name, "font" | "mono" | "scale" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip") {
if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip") {
return;
}
let Some(path) = prefs_path() else { return };
@@ -566,7 +569,12 @@ fn update_check(manual: bool) {
{
emit(serde_json::json!({"type": "enginestale", "version": v}).to_string());
}
// Kiri Dev is rebuilt from source, never updated from the feed, unless
feed_check(manual);
}
/// Whether the feed has a newer release, and one already staged; the
/// window's check and the 6-hourly one (recheck.rs).
fn feed_check(manual: bool) { // Kiri Dev is rebuilt from source, never updated from the feed, unless
// KIRI_UPDATE_URL names a test feed (to try the update card and What's new).
if crate::flavor::dev() && std::env::var_os("KIRI_UPDATE_URL").is_none() {
if manual {
@@ -591,6 +599,7 @@ fn update_check(manual: bool) {
if !manual && prefs()["updateAuto"] == false {
return;
}
recheck::checked();
// Linux's kiri comes from a .deb or .rpm: the feed only says whether a
// newer one exists, and About links to the releases page, so no card.
if cfg!(target_os = "linux") {
@@ -1579,6 +1588,29 @@ fn handle(text: &str, tx: &Sender<Cmd>, autostart: bool, view: Option<&str>) {
sharing::sign_out();
Ok(())
}
// The built-in terminal: its shells, and its own clipboard and links.
"term" => {
match msg.name.as_str() {
// A selection can be a whole screen of output.
"copy" => {
if let Some(text) = msg.value.as_str().filter(|t| !t.is_empty() && t.len() <= termwire::COPY_MAX) {
window::copy(text);
}
}
"paste" => {
let id = msg.id;
window::paste(move |text| emit(termwire::paste(&id, &text)));
}
// A link in a shell's output: web pages only, never a file or an app's scheme.
"link" => {
if let Some(url) = msg.value.as_str().filter(|u| termwire::web_link(u)) {
open(url);
}
}
action => term::handle(action, &msg.id, &msg.value, emit),
}
Ok(())
}
// The page can't write the clipboard itself; IDs and short text only.
"copy" => {
if !msg.name.is_empty() && msg.name.len() <= 4096 {
@@ -1846,6 +1878,12 @@ fn handle(text: &str, tx: &Sender<Cmd>, autostart: bool, view: Option<&str>) {
window::drag();
Ok(())
}
// ⌘W when the built-in terminal doesn't have the focus.
#[cfg(target_os = "macos")]
"closewindow" => {
window::close_window();
Ok(())
}
"zoom" => {
window::zoom();
Ok(())
@@ -1947,9 +1985,11 @@ fn handle(text: &str, tx: &Sender<Cmd>, autostart: bool, view: Option<&str>) {
}
});
diag::report::spawn_crash_sender(Duration::from_secs(5), None);
// A newer release, checked once per window, quietly; one
// already downloaded; an engine still on an older build.
// A newer release, checked when the window opens and every 6
// hours after (recheck.rs), quietly; one already downloaded; an
// engine still on an older build.
std::thread::spawn(|| update_check(false));
recheck::start(|| feed_check(false));
// The first time the app opens: ask, once, whether to use *.kiri.local (the Mac only, so far).
if cfg!(target_os = "macos") && !crate::flavor::dev() && !crate::daemon::dns::installed() && prefs()["domainsAsked"] != true {
set_pref("domainsAsked", true.into());
+66
View File
@@ -0,0 +1,66 @@
//! Asking for a newer release again while Kiri keeps running. The window
//! checks when it opens; a laptop that stays up for days, sleeping and
//! waking with Kiri open, would otherwise never hear of a release until
//! Kiri was quit. Every 6 hours by the wall clock, so time asleep counts:
//! a Mac that wakes after a night checks within minutes. The Mac and Linux
//! (ui/mod.rs) and Windows (kiri-win's update.rs, which includes this file)
//! use it the same way.
use std::sync::{Mutex, Once, PoisonError};
use std::time::{Duration, SystemTime};
/// How long after one check the next is due.
pub const EVERY: Duration = Duration::from_secs(6 * 60 * 60);
/// How often the timer looks at the clock: a monotonic sleep stops while
/// the computer sleeps, so it wakes often and compares wall-clock times.
const TICK: Duration = Duration::from_secs(10 * 60);
static LAST: Mutex<Option<SystemTime>> = Mutex::new(None);
/// A check asked the feed just now.
pub fn checked() {
*LAST.lock().unwrap_or_else(PoisonError::into_inner) = Some(SystemTime::now());
}
fn due(last: Option<SystemTime>, now: SystemTime) -> bool {
match last {
None => true,
// A clock set back: check, and count from now.
Some(l) => now.duration_since(l).map_or(true, |d| d >= EVERY),
}
}
/// Starts the timer once for the life of the process (a page reload asks
/// again): `check` runs whenever a check is due.
pub fn start(check: fn()) {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
let _ = std::thread::Builder::new().name("kiri-recheck".into()).spawn(move || {
loop {
std::thread::sleep(TICK);
let last = *LAST.lock().unwrap_or_else(PoisonError::into_inner);
if due(last, SystemTime::now()) {
checked();
check();
}
}
});
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn due_six_hours_after_the_last_check_by_the_wall_clock() {
let t = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
assert!(due(None, t));
assert!(!due(Some(t), t + Duration::from_secs(5 * 3600)));
assert!(due(Some(t), t + EVERY));
// Asleep all night: due the moment it wakes.
assert!(due(Some(t), t + Duration::from_secs(14 * 3600)));
// The clock went back.
assert!(due(Some(t), t - Duration::from_secs(60)));
}
}
+443
View File
@@ -0,0 +1,443 @@
//! The built-in terminal's shells on the Mac and Linux: each tab or pane is
//! a shell on its own pseudo-terminal, in the home folder, with Kiri's
//! tools first on the PATH. What goes to and from the page is in
//! termwire.rs; Windows does the same with a ConPTY (kiri-win's term.rs).
use std::collections::HashMap;
use std::ffi::CStr;
use std::fs::File;
use std::io::{Read, Write};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc::{Sender, channel};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use serde_json::Value;
use super::termwire::{self, Shell};
struct Session {
/// The pseudo-terminal's master side: resized here, read by the
/// session's reader and written by its writer.
master: Arc<File>,
/// The shell, which leads its own session and process group.
pid: i32,
input: Sender<Vec<u8>>,
/// Set once the shell has exited and been reaped.
done: Arc<AtomicBool>,
}
static SESSIONS: Mutex<Option<HashMap<String, Session>>> = Mutex::new(None);
fn with<R>(f: impl FnOnce(&mut HashMap<String, Session>) -> R) -> R {
f(SESSIONS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashMap::new))
}
/// One `term` command from the page.
pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) {
match action {
"shells" => {
let (list, default) = shells();
emit(termwire::shells(&list, &default));
}
"open" if termwire::valid_id(id) => {
let (cols, rows) = termwire::size(value);
let asked = value["shell"].as_str().unwrap_or("");
let (list, default) = shells();
// Only a shell from the list: the page never names a program.
let path = list.iter().find(|s| s.id == asked).map_or(default, |s| s.id.clone());
if let Err(e) = open(id, Path::new(&path), cols, rows, emit) {
emit(termwire::exit(id, None, Some(&e.to_string())));
}
}
"input" => {
if let Some(bytes) = value.as_str().and_then(termwire::unb64) {
with(|s| s.get(id).map(|s| s.input.send(bytes)));
}
}
"resize" => {
let (cols, rows) = termwire::size(value);
with(|s| s.get(id).map(|s| set_size(&s.master, cols, rows)));
}
"close" => {
if let Some(s) = with(|s| s.remove(id)) {
end(&s);
}
}
// The page (re)loaded: nothing it had is on screen any more.
"closeall" => {
for (_, s) in with(std::mem::take) {
end(&s);
}
}
_ => {}
}
}
/// Ends a closed session's shell: a hang-up, as closing a terminal window
/// sends, then SIGKILL to its process group if it is still there 2 seconds
/// later (a shell that traps SIGHUP, or a busy one).
fn end(s: &Session) {
hang_up(s.pid);
let (pid, done) = (s.pid, s.done.clone());
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(2));
// Not after it was reaped: the number could belong to another process by then.
if !done.load(Ordering::SeqCst) {
// SAFETY: kill only sends a signal.
unsafe { libc::kill(-pid, libc::SIGKILL) };
}
});
}
/// SIGHUP to a shell's process group, so what it started in the background goes too.
fn hang_up(pid: i32) {
// SAFETY: kill only sends a signal.
unsafe { libc::kill(-pid, libc::SIGHUP) };
}
/// The shells in /etc/shells that a person would open, plus Homebrew's, and
/// which one is the user's own.
fn shells() -> (Vec<Shell>, String) {
let mut paths: Vec<PathBuf> = std::fs::read_to_string("/etc/shells").unwrap_or_default().lines().map(str::trim).filter(|l| l.starts_with('/')).map(PathBuf::from).collect();
for dir in ["/opt/homebrew/bin", "/usr/local/bin", "/home/linuxbrew/.linuxbrew/bin"] {
for name in ["zsh", "bash", "fish", "nu", "pwsh"] {
paths.push(Path::new(dir).join(name));
}
}
let own = login_shell();
paths.insert(0, own.clone());
let mut seen = Vec::new();
let mut list: Vec<Shell> = Vec::new();
for p in paths {
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("").to_owned();
// Shells nobody opens a tab of, and the ones that only refuse logins.
if name.is_empty() || ["nologin", "false", "true", "rbash", "git-shell", "screen", "tmux", "sh"].contains(&name.as_str()) || !executable(&p) {
continue;
}
// /bin/bash and /usr/bin/bash are one file where /bin is a link.
let real = std::fs::canonicalize(&p).unwrap_or_else(|_| p.clone());
if seen.contains(&real) {
continue;
}
seen.push(real);
let label = if list.iter().any(|s| s.label == name) { format!("{name} ({})", p.parent().map_or(String::new(), |d| d.display().to_string())) } else { name };
list.push(Shell { id: p.display().to_string(), label, group: "" });
}
let default = if list.iter().any(|s| Path::new(&s.id) == own) { own.display().to_string() } else { list.first().map_or_else(|| "/bin/sh".to_owned(), |s| s.id.clone()) };
if list.is_empty() {
list.push(Shell { id: default.clone(), label: "sh".into(), group: "" });
}
(list, default)
}
/// The user's shell: $SHELL, else the account's, else zsh or bash.
fn login_shell() -> PathBuf {
if let Some(s) = std::env::var_os("SHELL").filter(|s| !s.is_empty()) {
return s.into();
}
// SAFETY: getpwuid returns the calling thread's account record or null;
// pw_shell is read at once, before another call could replace it.
let from_passwd = unsafe {
let pw = libc::getpwuid(libc::getuid());
(!pw.is_null() && !(*pw).pw_shell.is_null()).then(|| CStr::from_ptr((*pw).pw_shell).to_string_lossy().into_owned())
};
from_passwd.map_or_else(|| PathBuf::from(if cfg!(target_os = "macos") { "/bin/zsh" } else { "/bin/bash" }), PathBuf::from)
}
fn executable(p: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
/// Kiri's own tools, put first on the shell's PATH: `kiri`, `docker` and
/// the rest of what Kiri installs, and the copies inside the app.
fn tool_dirs() -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Some(home) = std::env::var_os("HOME") {
dirs.push(PathBuf::from(home).join(crate::flavor::STATE.get()).join("bin"));
}
if let Some(exe_dir) = std::env::current_exe().ok().and_then(|e| e.parent().map(Path::to_path_buf)) {
dirs.push(exe_dir.join("../Resources/bin"));
dirs.push(exe_dir);
}
dirs.into_iter().filter(|d| d.is_dir()).filter_map(|d| std::fs::canonicalize(d).ok()).collect()
}
/// A new pseudo-terminal: its master, and the path of its other side.
fn new_pty() -> std::io::Result<(OwnedFd, PathBuf)> {
// SAFETY: plain libc calls on a descriptor this function owns from the
// moment posix_openpt returns it.
unsafe {
let fd = libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY);
if fd < 0 {
return Err(std::io::Error::last_os_error());
}
let master = OwnedFd::from_raw_fd(fd);
if libc::grantpt(fd) != 0 || libc::unlockpt(fd) != 0 {
return Err(std::io::Error::last_os_error());
}
libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
Ok((master, slave_name(fd)?))
}
}
#[cfg(target_os = "linux")]
fn slave_name(fd: i32) -> std::io::Result<PathBuf> {
let mut buf = [0 as libc::c_char; 128];
// SAFETY: ptsname_r writes at most buf.len() bytes, NUL included.
if unsafe { libc::ptsname_r(fd, buf.as_mut_ptr(), buf.len()) } != 0 {
return Err(std::io::Error::last_os_error());
}
// SAFETY: on success buf holds a NUL-terminated path.
Ok(PathBuf::from(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().into_owned()))
}
#[cfg(not(target_os = "linux"))]
fn slave_name(fd: i32) -> std::io::Result<PathBuf> {
// ptsname shares one buffer: one caller at a time.
static ONE: Mutex<()> = Mutex::new(());
let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: the result is copied out before the lock is released.
unsafe {
let p = libc::ptsname(fd);
if p.is_null() {
return Err(std::io::Error::last_os_error());
}
Ok(PathBuf::from(CStr::from_ptr(p).to_string_lossy().into_owned()))
}
}
fn set_size(master: &File, cols: u16, rows: u16) {
let ws = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
// SAFETY: TIOCSWINSZ reads one winsize.
unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCSWINSZ, &ws) };
}
fn open(id: &str, shell: &Path, cols: u16, rows: u16, emit: fn(String)) -> std::io::Result<()> {
// A tab the page reopens under the same name replaces the old one.
if let Some(old) = with(|s| s.remove(id)) {
end(&old);
}
let (master, slave_path) = new_pty()?;
let master = Arc::new(File::from(master));
let slave = std::fs::OpenOptions::new().read(true).write(true).custom_flags_noctty().open(&slave_path)?;
// After the other side is open: macOS forgets a size set before.
set_size(&master, cols, rows);
let name = shell.file_name().and_then(|n| n.to_str()).unwrap_or("sh");
let mut cmd = Command::new(shell);
// A login shell on the Mac, as Terminal starts one, so the profile sets
// up the PATH; on Linux terminals start an interactive shell.
if cfg!(target_os = "macos") {
cmd.arg0(format!("-{name}"));
}
let path = std::env::var_os("PATH").unwrap_or_default();
let path = std::env::join_paths(tool_dirs().into_iter().chain(std::env::split_paths(&path))).unwrap_or(path);
cmd.env("PATH", path).env("TERM", "xterm-256color").env("COLORTERM", "truecolor").env("TERM_PROGRAM", "Kiri").env_remove("TERM_PROGRAM_VERSION");
if std::env::var_os("LANG").is_none() {
cmd.env("LANG", "en_US.UTF-8");
}
if let Some(home) = std::env::var_os("HOME") {
cmd.current_dir(home);
}
cmd.stdin(Stdio::from(slave.try_clone()?)).stdout(Stdio::from(slave.try_clone()?)).stderr(Stdio::from(slave));
// SAFETY: setsid and ioctl are async-signal-safe; they run in the child
// after its stdio is the terminal, making it the controlling terminal
// of the shell's own session.
unsafe {
cmd.pre_exec(|| {
if libc::setsid() < 0 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let mut child = cmd.spawn()?;
// Dropping cmd closes the parent's copies of the terminal's other side,
// so the reader sees the end once the shell and its children are gone.
drop(cmd);
let pid = child.id() as i32;
let (input, typed) = channel::<Vec<u8>>();
let done = Arc::new(AtomicBool::new(false));
with(|s| s.insert(id.to_owned(), Session { master: master.clone(), pid, input, done: done.clone() }));
// Writes go through their own thread: a shell that stops reading can't
// hold up the window.
let writer = master.clone();
std::thread::spawn(move || {
for bytes in typed {
if (&*writer).write_all(&bytes).is_err() {
break;
}
}
});
// The shell ending: hang up whatever it left on the terminal, so the
// reader reaches the end.
let code = Arc::new(Mutex::new(None));
let waiter = {
let code = code.clone();
std::thread::spawn(move || {
let status = child.wait().ok();
*code.lock().unwrap_or_else(|e| e.into_inner()) = status.and_then(|s| s.code());
// Its group may outlive it (a job it started); the number is still ours to signal
// until the reaped shell's group is empty.
hang_up(pid);
done.store(true, Ordering::SeqCst);
})
};
let id = id.to_owned();
std::thread::spawn(move || {
let mut buf = vec![0u8; 64 * 1024];
loop {
match (&*master).read(&mut buf) {
Ok(0) => break,
Ok(n) => emit(termwire::data(&id, &buf[..n])),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
// EIO: the other side is closed.
Err(_) => break,
}
}
let _ = waiter.join();
// Only when it is still this session: a close or reopen replaced it.
let mine = with(|s| {
let mine = s.get(&id).is_some_and(|s| s.pid == pid);
if mine {
s.remove(&id);
}
mine
});
if mine {
emit(termwire::exit(&id, *code.lock().unwrap_or_else(|e| e.into_inner()), None));
}
});
Ok(())
}
/// Opening the terminal's other side without it becoming the window's
/// controlling terminal.
trait NoCtty {
fn custom_flags_noctty(&mut self) -> &mut Self;
}
impl NoCtty for std::fs::OpenOptions {
fn custom_flags_noctty(&mut self) -> &mut Self {
use std::os::unix::fs::OpenOptionsExt;
self.custom_flags(libc::O_NOCTTY)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};
// Every test's listener hears every event; each keeps its own session's.
static EVENTS: Mutex<Vec<Sender<String>>> = Mutex::new(Vec::new());
fn record(json: String) {
for tx in EVENTS.lock().unwrap().iter() {
let _ = tx.send(json.clone());
}
}
fn listen() -> Receiver<String> {
let (tx, rx) = channel();
EVENTS.lock().unwrap().push(tx);
rx
}
fn output_until(rx: &Receiver<String>, id: &str, want: &str) -> (String, Option<Value>) {
let mut out = Vec::new();
let deadline = Instant::now() + Duration::from_secs(10);
while let Ok(ev) = rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
let ev: Value = serde_json::from_str(&ev).unwrap();
if ev["id"] != id {
continue;
}
match ev["ev"].as_str() {
Some("data") => {
out.extend(termwire::unb64(ev["b64"].as_str().unwrap()).unwrap());
if String::from_utf8_lossy(&out).contains(want) {
return (String::from_utf8_lossy(&out).into_owned(), None);
}
}
Some("exit") => return (String::from_utf8_lossy(&out).into_owned(), Some(ev)),
_ => {}
}
}
panic!("no {want:?} in {:?}", String::from_utf8_lossy(&out));
}
#[test]
fn a_shell_runs_on_a_real_terminal_and_says_when_it_ends() {
let rx = listen();
let (list, default) = shells();
assert!(list.iter().any(|s| s.id == default), "default {default} not in the list");
handle("open", "t1", &serde_json::json!({"shell": "/bin/bash", "cols": 91, "rows": 17}), record);
let typed = |s: &str| handle("input", "t1", &Value::String(termwire::b64(s.as_bytes())), record);
// A terminal of the size asked for, Kiri's tools on the PATH, and
// the TERM programs expect.
typed("stty size; echo \"T=$TERM\"; test -t 0 && echo IS-A-TTY; echo DONE$((40+2))\n");
let (out, _) = output_until(&rx, "t1", "DONE42");
assert!(out.contains("17 91"), "{out}");
assert!(out.contains("T=xterm-256color") && out.contains("IS-A-TTY"), "{out}");
handle("resize", "t1", &serde_json::json!({"cols": 120, "rows": 30}), record);
typed("stty size; echo AGAIN$((1+1))\n");
let (out, _) = output_until(&rx, "t1", "AGAIN2");
assert!(out.contains("30 120"), "{out}");
typed("exit 7\n");
let (_, exit) = output_until(&rx, "t1", "\u{0}never");
assert_eq!(exit.unwrap()["code"], 7);
assert!(with(|s| !s.contains_key("t1")));
}
#[test]
fn closing_hangs_up_the_shell_and_what_it_started() {
let rx = listen();
handle("open", "t2", &serde_json::json!({"shell": "/bin/bash"}), record);
handle("input", "t2", &Value::String(termwire::b64(b"sleep 600 & echo STARTED$((2*3))\n")), record);
output_until(&rx, "t2", "STARTED6");
let pid = with(|s| s["t2"].pid);
handle("close", "t2", &Value::Null, record);
let deadline = Instant::now() + Duration::from_secs(5);
// SAFETY: kill with signal 0 only checks the group exists.
while unsafe { libc::kill(-pid, 0) } == 0 {
assert!(Instant::now() < deadline, "process group {pid} still there");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn a_shell_that_ignores_the_hang_up_still_goes() {
let rx = listen();
handle("open", "t3", &serde_json::json!({"shell": "/bin/bash"}), record);
handle("input", "t3", &Value::String(termwire::b64(b"trap '' HUP; echo TRAPPED$((3*3))\n")), record);
output_until(&rx, "t3", "TRAPPED9");
let pid = with(|s| s["t3"].pid);
handle("close", "t3", &Value::Null, record);
let deadline = Instant::now() + Duration::from_secs(6);
// SAFETY: kill with signal 0 only checks the process exists.
while unsafe { libc::kill(pid, 0) } == 0 {
assert!(Instant::now() < deadline, "shell {pid} survived its close");
std::thread::sleep(Duration::from_millis(50));
}
}
#[test]
fn a_page_can_only_start_a_listed_shell() {
let (list, default) = shells();
assert!(!list.iter().any(|s| s.id.ends_with("/nologin") || s.id.ends_with("/false")));
assert!(Path::new(&default).is_absolute());
}
}
+136
View File
@@ -0,0 +1,136 @@
//! What the built-in terminal says between the page and the app, the same on
//! every system: the Mac and Linux run shells on a pseudo-terminal
//! (ui/term.rs), Windows on a ConPTY (kiri-win's term.rs, which includes
//! this file).
//!
//! The page sends `{"cmd":"term","name":ACTION,"id":SESSION,"value":…}`:
//! `shells`; `open` with `{shell, cols, rows}`; `input` with the bytes typed
//! (base64); `resize` with `{cols, rows}`; `close`; `closeall` when the page
//! starts; `paste`; and `copy` with the text. The app answers with events of
//! type `term`: `shells`, `data` (output, base64), `exit`, `paste`.
//!
//! Output and input go as base64: a read can end in the middle of a UTF-8
//! character, and programs send bytes that aren't text at all.
use serde_json::{Value, json};
/// A shell the terminal can start: `id` is what the page asks for, so a
/// page can only start a shell from this list, never a program it names.
pub struct Shell {
pub id: String,
pub label: String,
/// What the new-tab menu groups it under ("" for none).
pub group: &'static str,
}
/// A session's name from the page: short, letters and digits only.
pub fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 16 && id.bytes().all(|b| b.is_ascii_alphanumeric())
}
/// Columns and rows from `{cols, rows}`, kept to what a terminal can be.
pub fn size(v: &Value) -> (u16, u16) {
let get = |k: &str, d: u64| v[k].as_u64().unwrap_or(d).clamp(2, 1000) as u16;
(get("cols", 80), get("rows", 24))
}
pub fn shells(list: &[Shell], default: &str) -> String {
let list: Vec<Value> = list.iter().map(|s| json!({"id": s.id, "label": s.label, "group": s.group})).collect();
json!({"type": "term", "ev": "shells", "shells": list, "default": default}).to_string()
}
pub fn data(id: &str, bytes: &[u8]) -> String {
json!({"type": "term", "ev": "data", "id": id, "b64": b64(bytes)}).to_string()
}
/// The session ended: `code` when the shell exited by itself, `error` when
/// it couldn't start.
pub fn exit(id: &str, code: Option<i32>, error: Option<&str>) -> String {
json!({"type": "term", "ev": "exit", "id": id, "code": code, "error": error}).to_string()
}
pub fn paste(id: &str, text: &str) -> String {
json!({"type": "term", "ev": "paste", "id": id, "text": text}).to_string()
}
/// A link the terminal may open: http or https with a host, and nothing
/// that would read as more than one address.
pub fn web_link(url: &str) -> bool {
let rest = url.strip_prefix("https://").or_else(|| url.strip_prefix("http://"));
rest.is_some_and(|r| !r.is_empty() && !r.starts_with('/')) && url.len() <= 2048 && url.chars().all(|c| c.is_ascii_graphic())
}
/// The most a copy may put on the clipboard: a whole screen of scrollback.
pub const COPY_MAX: usize = 4 << 20;
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn b64(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for c in bytes.chunks(3) {
let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0));
for i in 0..4 {
out.push(if i <= c.len() { B64[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
}
}
out
}
pub fn unb64(s: &str) -> Option<Vec<u8>> {
let s = s.trim_end_matches('=').as_bytes();
let val = |b: u8| B64.iter().position(|&x| x == b).map(|p| p as u32);
let mut out = Vec::with_capacity(s.len() * 3 / 4);
for c in s.chunks(4) {
if c.len() == 1 {
return None;
}
let mut n = 0;
for (i, &b) in c.iter().enumerate() {
n |= val(b)? << (18 - 6 * i);
}
out.push((n >> 16) as u8);
if c.len() > 2 {
out.push((n >> 8) as u8);
}
if c.len() > 3 {
out.push(n as u8);
}
}
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_goes_both_ways_at_every_length() {
for n in 0..70u8 {
let bytes: Vec<u8> = (0..n).map(|i| i.wrapping_mul(37).wrapping_add(200)).collect();
assert_eq!(unb64(&b64(&bytes)).as_deref(), Some(&bytes[..]), "{n} bytes");
}
assert_eq!(b64(b"Kiri"), "S2lyaQ==");
assert_eq!(unb64("not base64!"), None);
}
#[test]
fn a_page_cant_name_a_session_that_isnt_plain() {
assert!(valid_id("t12"));
assert!(!valid_id("") && !valid_id("../x") && !valid_id("a b") && !valid_id(&"a".repeat(17)));
}
#[test]
fn only_web_links_open() {
assert!(web_link("https://example.com/a?b=c") && web_link("http://localhost:3000"));
for bad in ["file:///etc/passwd", "javascript:alert(1)", "https://", "http:///x", "https://a b", "vscode://x", "ssh://h"] {
assert!(!web_link(bad), "{bad}");
}
}
#[test]
fn sizes_are_kept_sane() {
assert_eq!(size(&json!({"cols": 120, "rows": 40})), (120, 40));
assert_eq!(size(&json!({"cols": 0, "rows": 99999})), (2, 1000));
assert_eq!(size(&json!({})), (80, 24));
}
}
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+17
View File
@@ -0,0 +1,17 @@
# xterm.js, vendored
The built-in terminal's emulator. These files are the published builds,
unmodified, and assemble.rs splices them into the window's page.
| File | Package | SHA-256 |
|---|---|---|
| xterm.js, xterm.css | `@xterm/xterm@6.0.0` (lib/xterm.js, css/xterm.css) | 14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972, 854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6 |
| addon-fit.js | `@xterm/addon-fit@0.11.0` (lib/addon-fit.js) | ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527 |
| addon-search.js | `@xterm/addon-search@0.16.0` (lib/addon-search.js) | 7bc1b8c7b3549411f6f6f779524c4ded6ca621fd80d64b40a70ae7c78aefbf55 |
| addon-web-links.js | `@xterm/addon-web-links@0.12.0` (lib/addon-web-links.js) | b74864125ef3889753b94e61eb4dabb99b2a27f920f0c9a7bd53cbe6d10f032a |
MIT licence: LICENSE here, and in the repository's NOTICE.
To update: download the same paths from https://unpkg.com/<package>@<version>/,
replace the files, update this table, and run `cargo test -p kiri assemble`
(the page must stay under WebView2's 2 MB limit) and `python3 scripts/ui-test.py`.
+2
View File
@@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(globalThis,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core._renderService.dimensions;if(0===e.css.cell.width||0===e.css.cell.height)return;const t=0===this._terminal.options.scrollback?0:this._terminal.options.overviewRuler?.width||14,r=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(r.getPropertyValue("height")),o=Math.max(0,parseInt(r.getPropertyValue("width"))),s=window.getComputedStyle(this._terminal.element),n=i-(parseInt(s.getPropertyValue("padding-top"))+parseInt(s.getPropertyValue("padding-bottom"))),l=o-(parseInt(s.getPropertyValue("padding-right"))+parseInt(s.getPropertyValue("padding-left")))-t;return{cols:Math.max(2,Math.floor(l/e.css.cell.width)),rows:Math.max(1,Math.floor(n/e.css.cell.height))}}}})(),e})()));
//# sourceMappingURL=addon-fit.js.map
+2
View File
@@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.SearchAddon=t():e.SearchAddon=t()}(globalThis,(()=>(()=>{"use strict";var e={864:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationManager=void 0;const i=s(540);class r extends i.Disposable{constructor(e){super(),this._terminal=e,this._highlightDecorations=[],this._highlightedLines=new Set,this._register((0,i.toDisposable)((()=>this.clearHighlightDecorations())))}createHighlightDecorations(e,t){this.clearHighlightDecorations();for(const s of e){const e=this._createResultDecorations(s,t,!1);if(e)for(const t of e)this._storeDecoration(t,s)}}createActiveDecoration(e,t){const s=this._createResultDecorations(e,t,!0);if(s)return{decorations:s,match:e,dispose(){(0,i.dispose)(s)}}}clearHighlightDecorations(){(0,i.dispose)(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear()}_storeDecoration(e,t){this._highlightedLines.add(e.marker.line),this._highlightDecorations.push({decoration:e,match:t,dispose(){e.dispose()}})}_applyStyles(e,t,s){e.classList.contains("xterm-find-result-decoration")||(e.classList.add("xterm-find-result-decoration"),t&&(e.style.outline=`1px solid ${t}`)),s&&e.classList.add("xterm-find-active-result-decoration")}_createResultDecorations(e,t,s){const r=[];let n=e.col,o=e.size,a=-this._terminal.buffer.active.baseY-this._terminal.buffer.active.cursorY+e.row;for(;o>0;){const e=Math.min(this._terminal.cols-n,o);r.push([a,n,e]),n=0,o-=e,a++}const l=[];for(const e of r){const r=this._terminal.registerMarker(e[0]),n=this._terminal.registerDecoration({marker:r,x:e[1],width:e[2],backgroundColor:s?t.activeMatchBackground:t.matchBackground,overviewRulerOptions:this._highlightedLines.has(r.line)?void 0:{color:s?t.activeMatchColorOverviewRuler:t.matchOverviewRuler,position:"center"}});if(n){const e=[];e.push(r),e.push(n.onRender((e=>this._applyStyles(e,s?t.activeMatchBorder:t.matchBorder,!1)))),e.push(n.onDispose((()=>(0,i.dispose)(e)))),l.push(n)}}return 0===l.length?void 0:l}}t.DecorationManager=r},615:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SearchEngine=void 0,t.SearchEngine=class{constructor(e,t){this._terminal=e,this._lineCache=t}find(e,t,s,i){if(!e||0===e.length)return void this._terminal.clearSelection();if(s>this._terminal.cols)throw new Error(`Invalid col: ${s} to search in terminal of ${this._terminal.cols} cols`);this._lineCache.initLinesCache();const r={startRow:t,startCol:s};let n=this._findInLine(e,r,i);if(!n)for(let s=t+1;s<this._terminal.buffer.active.baseY+this._terminal.rows&&(r.startRow=s,r.startCol=0,n=this._findInLine(e,r,i),!n);s++);return n}findNextWithSelection(e,t,s){if(!e||0===e.length)return void this._terminal.clearSelection();const i=this._terminal.getSelectionPosition();this._terminal.clearSelection();let r=0,n=0;i&&(s===e?(r=i.end.x,n=i.end.y):(r=i.start.x,n=i.start.y)),this._lineCache.initLinesCache();const o={startRow:n,startCol:r};let a=this._findInLine(e,o,t);if(!a)for(let s=n+1;s<this._terminal.buffer.active.baseY+this._terminal.rows&&(o.startRow=s,o.startCol=0,a=this._findInLine(e,o,t),!a);s++);if(!a&&0!==n)for(let s=0;s<n&&(o.startRow=s,o.startCol=0,a=this._findInLine(e,o,t),!a);s++);return!a&&i&&(o.startRow=i.start.y,o.startCol=0,a=this._findInLine(e,o,t)),a}findPreviousWithSelection(e,t,s){if(!e||0===e.length)return void this._terminal.clearSelection();const i=this._terminal.getSelectionPosition();this._terminal.clearSelection();let r=this._terminal.buffer.active.baseY+this._terminal.rows-1,n=this._terminal.cols;const o=!0;this._lineCache.initLinesCache();const a={startRow:r,startCol:n};let l;if(i&&(a.startRow=r=i.start.y,a.startCol=n=i.start.x,s!==e&&(l=this._findInLine(e,a,t,!1),l||(a.startRow=r=i.end.y,a.startCol=n=i.end.x))),l||(l=this._findInLine(e,a,t,o)),!l){a.startCol=Math.max(a.startCol,this._terminal.cols);for(let s=r-1;s>=0&&(a.startRow=s,l=this._findInLine(e,a,t,o),!l);s--);}if(!l&&r!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let s=this._terminal.buffer.active.baseY+this._terminal.rows-1;s>=r&&(a.startRow=s,l=this._findInLine(e,a,t,o),!l);s--);return l}_isWholeWord(e,t,s){return(0===e||" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?".includes(t[e-1]))&&(e+s.length===t.length||" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?".includes(t[e+s.length]))}_findInLine(e,t,s={},i=!1){const r=t.startRow,n=t.startCol,o=this._terminal.buffer.active.getLine(r);if(o?.isWrapped)return i?void(t.startCol+=this._terminal.cols):(t.startRow--,t.startCol+=this._terminal.cols,this._findInLine(e,t,s));let a=this._lineCache.getLineFromCache(r);a||(a=this._lineCache.translateBufferLineToStringWithWrap(r,!0),this._lineCache.setLineInCache(r,a));const[l,h]=a,c=this._bufferColsToStringOffset(r,n);let u=e,d=l;s.regex||(u=s.caseSensitive?e:e.toLowerCase(),d=s.caseSensitive?l:l.toLowerCase());let f=-1;if(s.regex){const t=RegExp(u,s.caseSensitive?"g":"gi"Line truncated
//# sourceMappingURL=addon-search.js.map
@@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.WebLinksAddon=t():e.WebLinksAddon=t()}(globalThis,(()=>(()=>{"use strict";var e={490:(e,t)=>{function n(e){try{const t=new URL(e),n=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(n.toLocaleLowerCase())}catch(e){return!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0,t.WebLinkProvider=class{constructor(e,t,n,o={}){this._terminal=e,this._regex=t,this._handler=n,this._options=o}provideLinks(e,t){const n=o.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(n))}_addCallbacks(e){return e.map((e=>(e.leave=this._options.leave,e.hover=(t,n)=>{if(this._options.hover){const{range:o}=e;this._options.hover(t,n,o)}},e)))}};class o{static computeLink(e,t,r,i){const s=new RegExp(t.source,(t.flags||"")+"g"),[a,c]=o._getWindowedLineStrings(e-1,r),l=a.join("");let d;const p=[];for(;d=s.exec(l);){const e=d[0];if(!n(e))continue;const[t,s]=o._mapStrIdx(r,c,0,d.index),[a,l]=o._mapStrIdx(r,t,s,e.length);if(-1===t||-1===s||-1===a||-1===l)continue;const h={start:{x:s+1,y:t+1},end:{x:l,y:a+1}};p.push({range:h,text:e,activate:i})}return p}static _getWindowedLineStrings(e,t){let n,o=e,r=e,i=0,s="";const a=[];if(n=t.buffer.active.getLine(e)){const e=n.translateToString(!0);if(n.isWrapped&&" "!==e[0]){for(i=0;(n=t.buffer.active.getLine(--o))&&i<2048&&(s=n.translateToString(!0),i+=s.length,a.push(s),n.isWrapped&&-1===s.indexOf(" ")););a.reverse()}for(a.push(e),i=0;(n=t.buffer.active.getLine(++r))&&n.isWrapped&&i<2048&&(s=n.translateToString(!0),i+=s.length,a.push(s),-1===s.indexOf(" ")););}return[a,o]}static _mapStrIdx(e,t,n,o){const r=e.buffer.active,i=r.getNullCell();let s=n;for(;o;){const e=r.getLine(t);if(!e)return[-1,-1];for(let n=s;n<e.length;++n){e.getCell(n,i);const s=i.getChars();if(i.getWidth()&&(o-=s.length||1,n===e.length-1&&""===s)){const e=r.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,i),2===i.getWidth()&&(o+=1))}if(o<0)return[t,n]}t++,s=0}return[t,s]}}t.LinkComputer=o}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}var o={};return(()=>{var e=o;Object.defineProperty(e,"__esModule",{value:!0}),e.WebLinksAddon=void 0;const t=n(490),r=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function i(e,t){const n=window.open();if(n){try{n.opener=null}catch{}n.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}e.WebLinksAddon=class{constructor(e=i,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;const n=this._options,o=n.urlRegex||r;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,o,this._handler,n))}dispose(){this._linkProvider?.dispose()}}})(),o})()));
//# sourceMappingURL=addon-web-links.js.map
+285
View File
@@ -0,0 +1,285 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility:not(.debug),
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .xterm-accessibility-tree:not(.debug) *::selection {
color: transparent;
}
.xterm .xterm-accessibility-tree {
font-family: monospace;
user-select: text;
white-space: pre;
}
.xterm .xterm-accessibility-tree > div {
transform-origin: left;
width: fit-content;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}
/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */
/* xterm.js customization: Override xterm's cursor style */
.xterm .xterm-scrollable-element > .scrollbar {
cursor: default;
}
/* Arrows */
.xterm .xterm-scrollable-element > .scrollbar > .scra {
cursor: pointer;
font-size: 11px !important;
}
.xterm .xterm-scrollable-element > .visible {
opacity: 1;
/* Background rule added for IE9 - to allow clicks on dom node */
background:rgba(0,0,0,0);
transition: opacity 100ms linear;
/* In front of peek view */
z-index: 11;
}
.xterm .xterm-scrollable-element > .invisible {
opacity: 0;
pointer-events: none;
}
.xterm .xterm-scrollable-element > .invisible.fade {
transition: opacity 800ms linear;
}
/* Scrollable Content Inset Shadow */
.xterm .xterm-scrollable-element > .shadow {
position: absolute;
display: none;
}
.xterm .xterm-scrollable-element > .shadow.top {
display: block;
top: 0;
left: 3px;
height: 3px;
width: 100%;
box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset;
}
.xterm .xterm-scrollable-element > .shadow.left {
display: block;
top: 3px;
left: 0;
height: 100%;
width: 3px;
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
}
.xterm .xterm-scrollable-element > .shadow.top-left-corner {
display: block;
top: 0;
left: 0;
height: 3px;
width: 3px;
}
.xterm .xterm-scrollable-element > .shadow.top.left {
box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
}
+2
View File
@@ -0,0 +1,2 @@
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var s in i)("object"==typeof exports?exports:e)[s]=i[s]}}(globalThis,(()=>(()=>{"use strict";var e={2840:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=i(7721),o=i(4292),a=i(7150),l=i(7098),h=i(6501),c=i(7093);let d=class extends a.Disposable{constructor(e,t,i,s){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=s,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";const r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new o.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this._register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this._register(this._terminal.onScroll((()=>this._refreshRows()))),this._register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this._register(this._terminal.onLineFeed((()=>this._handleChar("\n")))),this._register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this._register(this._terminal.onKey((e=>this._handleKey(e.key)))),this._register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this._register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this._register((0,c.addDisposableListener)(r,"selectionchange",(()=>this._handleSelectionChange()))),this._register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRowsDimensions(),this._refreshRows(),this._register((0,a.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=n.tooMuchOutput.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){const e=i.lines.get(i.ydisp+r),t=[],n=e?.translateToString(!0,void 0,void 0,t)||"",o=(i.ydisp+r+1).toString(),a=this._rowElements[r];a&&(0===n.length?(a.textContent=" ",this._rowColumns.set(a,[0,1])):(a.textContent=n,this._rowColumns.set(a,t)),a.setAttribute("aria-posinset",o),a.setAttribute("aria-setsize",s),this._alignRowWidth(a))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const i=e.target,s=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")===(0===t?"1":`${this._terminal.buffer.lines.length}`))return;if(e.relatedTarget!==s)return;let r,n;if(0===t?(r=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(r=this._rowElements.shift(),n=i,this._rowContainer.removeChild(r)),r.removeLine truncated
//# sourceMappingURL=xterm.js.map
+14
View File
@@ -0,0 +1,14 @@
## New
- **A terminal in the window.** Click Terminal in the status bar, or press Control and the backtick key (F4 on Linux). Your own shell with tabs, splits, find and pinned tabs, and Kiri's `docker` first on the PATH.
## Fixed and improved
- **Kubernetes pods can use your own folders.** A pod's `hostPath` reaches your drives at `/mnt/c`, `/mnt/d` on Windows, `/Users` on the Mac and `/home` on Linux. Stop and start the cluster once to get it.
- **Linux: Kubernetes no longer breaks your terminals.** Privileged containers get their own `/dev`, as on Docker.
- **Containers keep their connections** while others start and stop.
- **Ports below 1024 and `ping` work without root,** as on Docker.
- **Container DNS keeps working** when the VM's resolver goes down, and `docker build` uses your Mac's DNS.
- **Deleting Kiri no longer breaks `docker build`.**
- **Firewall tools work in containers:** nftables, iptables, ipset, IPVS and traffic control.
- **A volume over part of a bind gets the image's files,** as on Docker. With `./:/app` and `/app/node_modules`, the container keeps its own Linux `node_modules`, not your computer's.
- **Kiri checks for updates every 6 hours** while it stays open.
- **Settings › Resources** looks the same on Mac, Windows and Linux.
+281
View File
@@ -218,3 +218,284 @@ CONFIG_IP_NF_IPTABLES_LEGACY=y
CONFIG_IP6_NF_IPTABLES_LEGACY=y
CONFIG_NF_TABLES_IPV6=y
CONFIG_NF_TABLES_BRIDGE=y
# --- the rest of netfilter, tc and the usual interfaces ------------------------
# What firewall rulesets, router configs, IDS/IPS (NFQUEUE), transparent proxies
# and network tests expect of a Linux kernel, as Docker Desktop's and OrbStack's
# kernels have them. All built in: the guest loads no modules (issue #14).
# nftables expressions and families
CONFIG_NFT_REJECT=y
CONFIG_NFT_REJECT_INET=y
CONFIG_NFT_REJECT_IPV4=y
CONFIG_NFT_REJECT_IPV6=y
CONFIG_NF_REJECT_IPV6=y
CONFIG_NFT_QUEUE=y
CONFIG_NETFILTER_NETLINK_QUEUE=y
CONFIG_NFT_LOG=y
CONFIG_NETFILTER_NETLINK_LOG=y
CONFIG_NF_LOG_SYSLOG=y
CONFIG_NFT_LIMIT=y
CONFIG_NFT_QUOTA=y
CONFIG_NFT_CONNLIMIT=y
CONFIG_NFT_NUMGEN=y
CONFIG_NFT_HASH=y
CONFIG_NFT_SOCKET=y
CONFIG_NF_SOCKET_IPV4=y
CONFIG_NF_SOCKET_IPV6=y
CONFIG_NFT_TPROXY=y
CONFIG_NF_TPROXY_IPV4=y
CONFIG_NF_TPROXY_IPV6=y
CONFIG_NFT_SYNPROXY=y
CONFIG_NFT_OSF=y
CONFIG_NETFILTER_NETLINK_OSF=y
CONFIG_NFT_TUNNEL=y
CONFIG_NFT_XFRM=y
CONFIG_NFT_DUP_IPV4=y
CONFIG_NFT_DUP_IPV6=y
CONFIG_NF_TABLES_NETDEV=y
CONFIG_NFT_FWD_NETDEV=y
CONFIG_NFT_DUP_NETDEV=y
CONFIG_NF_TABLES_ARP=y
CONFIG_NFT_BRIDGE_META=y
CONFIG_NFT_BRIDGE_REJECT=y
CONFIG_NF_FLOW_TABLE=y
CONFIG_NF_FLOW_TABLE_INET=y
CONFIG_NFT_FLOW_OFFLOAD=y
CONFIG_NETFILTER_INGRESS=y
CONFIG_NETFILTER_EGRESS=y
# conntrack: labels, zones, events, timeouts, accounting, and the helpers
CONFIG_NF_CONNTRACK_LABELS=y
CONFIG_NF_CONNTRACK_MARK=y
CONFIG_NF_CONNTRACK_ZONES=y
CONFIG_NF_CONNTRACK_EVENTS=y
CONFIG_NF_CONNTRACK_TIMEOUT=y
CONFIG_NF_CONNTRACK_TIMESTAMP=y
CONFIG_NF_CONNTRACK_PROCFS=y
CONFIG_NF_CT_NETLINK_TIMEOUT=y
CONFIG_NF_CT_NETLINK_HELPER=y
CONFIG_NETFILTER_NETLINK_GLUE_CT=y
CONFIG_NETFILTER_NETLINK_ACCT=y
CONFIG_NF_CT_PROTO_SCTP=y
CONFIG_NF_CT_PROTO_UDPLITE=y
CONFIG_NF_CONNTRACK_FTP=y
CONFIG_NF_CONNTRACK_TFTP=y
CONFIG_NF_CONNTRACK_SIP=y
CONFIG_NF_CONNTRACK_PPTP=y
CONFIG_NF_CONNTRACK_H323=y
CONFIG_NF_CONNTRACK_IRC=y
CONFIG_NF_CONNTRACK_NETBIOS_NS=y
# iptables (iptables-nft hands these to the kernel's xtables): matches
CONFIG_NETFILTER_XT_MATCH_BPF=y
CONFIG_NETFILTER_XT_MATCH_CGROUP=y
CONFIG_NETFILTER_XT_MATCH_CLUSTER=y
CONFIG_NETFILTER_XT_MATCH_CONNBYTES=y
CONFIG_NETFILTER_XT_MATCH_CONNLABEL=y
CONFIG_NETFILTER_XT_MATCH_CONNLIMIT=y
CONFIG_NETFILTER_XT_MATCH_CONNMARK=y
CONFIG_NETFILTER_XT_MATCH_CPU=y
CONFIG_NETFILTER_XT_MATCH_DEVGROUP=y
CONFIG_NETFILTER_XT_MATCH_DSCP=y
CONFIG_NETFILTER_XT_MATCH_ECN=y
CONFIG_NETFILTER_XT_MATCH_ESP=y
CONFIG_NETFILTER_XT_MATCH_HASHLIMIT=y
CONFIG_NETFILTER_XT_MATCH_HELPER=y
CONFIG_NETFILTER_XT_MATCH_HL=y
CONFIG_NETFILTER_XT_MATCH_IPCOMP=y
CONFIG_NETFILTER_XT_MATCH_IPVS=y
CONFIG_NETFILTER_XT_MATCH_LENGTH=y
CONFIG_NETFILTER_XT_MATCH_MAC=y
CONFIG_NETFILTER_XT_MATCH_NFACCT=y
CONFIG_NETFILTER_XT_MATCH_OSF=y
CONFIG_NETFILTER_XT_MATCH_POLICY=y
CONFIG_NETFILTER_XT_MATCH_QUOTA=y
CONFIG_NETFILTER_XT_MATCH_RATEEST=y
CONFIG_NETFILTER_XT_MATCH_RECENT=y
CONFIG_NETFILTER_XT_MATCH_SCTP=y
CONFIG_NETFILTER_XT_MATCH_SOCKET=y
CONFIG_NETFILTER_XT_MATCH_STATE=y
CONFIG_NETFILTER_XT_MATCH_STRING=y
CONFIG_NETFILTER_XT_MATCH_TIME=y
CONFIG_NETFILTER_XT_MATCH_U32=y
CONFIG_IP_NF_MATCH_AH=y
CONFIG_IP_NF_MATCH_ECN=y
CONFIG_IP_NF_MATCH_RPFILTER=y
CONFIG_IP_NF_MATCH_TTL=y
CONFIG_IP6_NF_MATCH_AH=y
CONFIG_IP6_NF_MATCH_EUI64=y
CONFIG_IP6_NF_MATCH_FRAG=y
CONFIG_IP6_NF_MATCH_HL=y
CONFIG_IP6_NF_MATCH_IPV6HEADER=y
CONFIG_IP6_NF_MATCH_MH=y
CONFIG_IP6_NF_MATCH_OPTS=y
CONFIG_IP6_NF_MATCH_RPFILTER=y
CONFIG_IP6_NF_MATCH_RT=y
# iptables targets and tables
CONFIG_NETFILTER_XT_TARGET_CHECKSUM=y
CONFIG_NETFILTER_XT_TARGET_CLASSIFY=y
CONFIG_NETFILTER_XT_TARGET_CONNMARK=y
CONFIG_NETFILTER_XT_TARGET_DSCP=y
CONFIG_NETFILTER_XT_TARGET_HL=y
CONFIG_NETFILTER_XT_TARGET_HMARK=y
CONFIG_NETFILTER_XT_TARGET_IDLETIMER=y
CONFIG_NETFILTER_XT_TARGET_MARK=y
CONFIG_NETFILTER_XT_TARGET_NETMAP=y
CONFIG_NETFILTER_XT_TARGET_NFLOG=y
CONFIG_NETFILTER_XT_TARGET_NFQUEUE=y
CONFIG_NETFILTER_XT_TARGET_NOTRACK=y
CONFIG_NETFILTER_XT_TARGET_RATEEST=y
CONFIG_NETFILTER_XT_TARGET_TCPMSS=y
CONFIG_NETFILTER_XT_TARGET_TCPOPTSTRIP=y
CONFIG_NETFILTER_XT_TARGET_TEE=y
CONFIG_NETFILTER_XT_TARGET_TPROXY=y
CONFIG_NETFILTER_XT_TARGET_TRACE=y
CONFIG_IP_NF_TARGET_ECN=y
CONFIG_IP_NF_TARGET_NETMAP=y
CONFIG_IP_NF_TARGET_SYNPROXY=y
CONFIG_IP_NF_TARGET_TTL=y
CONFIG_IP6_NF_RAW=y
CONFIG_IP6_NF_TARGET_HL=y
CONFIG_IP6_NF_TARGET_NPT=y
CONFIG_IP6_NF_TARGET_SYNPROXY=y
CONFIG_IP_NF_ARPTABLES=y
CONFIG_IP_NF_ARPFILTER=y
CONFIG_IP_NF_ARP_MANGLE=y
# ebtables (Docker-in-Docker, libvirt)
CONFIG_BRIDGE_NF_EBTABLES_LEGACY=y
CONFIG_BRIDGE_NF_EBTABLES=y
CONFIG_BRIDGE_EBT_BROUTE=y
CONFIG_BRIDGE_EBT_T_FILTER=y
CONFIG_BRIDGE_EBT_T_NAT=y
CONFIG_BRIDGE_EBT_802_3=y
CONFIG_BRIDGE_EBT_AMONG=y
CONFIG_BRIDGE_EBT_ARP=y
CONFIG_BRIDGE_EBT_IP=y
CONFIG_BRIDGE_EBT_IP6=y
CONFIG_BRIDGE_EBT_LIMIT=y
CONFIG_BRIDGE_EBT_MARK=y
CONFIG_BRIDGE_EBT_PKTTYPE=y
CONFIG_BRIDGE_EBT_STP=y
CONFIG_BRIDGE_EBT_VLAN=y
CONFIG_BRIDGE_EBT_ARPREPLY=y
CONFIG_BRIDGE_EBT_DNAT=y
CONFIG_BRIDGE_EBT_MARK_T=y
CONFIG_BRIDGE_EBT_REDIRECT=y
CONFIG_BRIDGE_EBT_SNAT=y
CONFIG_BRIDGE_EBT_LOG=y
CONFIG_BRIDGE_EBT_NFLOG=y
# ipset: every common type
CONFIG_IP_SET_BITMAP_IP=y
CONFIG_IP_SET_BITMAP_IPMAC=y
CONFIG_IP_SET_HASH_IPMAC=y
CONFIG_IP_SET_HASH_IPMARK=y
CONFIG_IP_SET_HASH_MAC=y
CONFIG_IP_SET_HASH_NETIFACE=y
CONFIG_IP_SET_HASH_NETNET=y
CONFIG_IP_SET_HASH_NETPORTNET=y
CONFIG_IP_SET_LIST_SET=y
# IPVS, for kube-proxy's ipvs mode
CONFIG_IP_VS=y
CONFIG_IP_VS_IPV6=y
CONFIG_IP_VS_PROTO_TCP=y
CONFIG_IP_VS_PROTO_UDP=y
CONFIG_IP_VS_PROTO_SCTP=y
CONFIG_IP_VS_RR=y
CONFIG_IP_VS_WRR=y
CONFIG_IP_VS_LC=y
CONFIG_IP_VS_WLC=y
CONFIG_IP_VS_SH=y
CONFIG_IP_VS_MH=y
CONFIG_IP_VS_SED=y
CONFIG_IP_VS_NQ=y
CONFIG_IP_VS_NFCT=y
# traffic control: qdiscs (netem for delay and loss), classifiers, actions
CONFIG_NET_SCH_HTB=y
CONFIG_NET_SCH_HFSC=y
CONFIG_NET_SCH_PRIO=y
CONFIG_NET_SCH_MULTIQ=y
CONFIG_NET_SCH_RED=y
CONFIG_NET_SCH_SFQ=y
CONFIG_NET_SCH_TBF=y
CONFIG_NET_SCH_NETEM=y
CONFIG_NET_SCH_DRR=y
CONFIG_NET_SCH_MQPRIO=y
CONFIG_NET_SCH_CODEL=y
CONFIG_NET_SCH_FQ_CODEL=y
CONFIG_NET_SCH_CAKE=y
CONFIG_NET_SCH_FQ=y
CONFIG_NET_SCH_ETF=y
CONFIG_NET_SCH_PLUG=y
CONFIG_NET_SCH_INGRESS=y
CONFIG_NET_CLS=y
CONFIG_NET_CLS_BASIC=y
CONFIG_NET_CLS_FW=y
CONFIG_NET_CLS_U32=y
CONFIG_NET_CLS_FLOW=y
CONFIG_NET_CLS_BPF=y
CONFIG_NET_CLS_FLOWER=y
CONFIG_NET_CLS_MATCHALL=y
CONFIG_NET_EMATCH=y
CONFIG_NET_EMATCH_CMP=y
CONFIG_NET_EMATCH_NBYTE=y
CONFIG_NET_EMATCH_U32=y
CONFIG_NET_EMATCH_META=y
CONFIG_NET_EMATCH_TEXT=y
CONFIG_NET_EMATCH_IPSET=y
CONFIG_NET_CLS_ACT=y
CONFIG_NET_ACT_POLICE=y
CONFIG_NET_ACT_GACT=y
CONFIG_NET_ACT_MIRRED=y
CONFIG_NET_ACT_NAT=y
CONFIG_NET_ACT_PEDIT=y
CONFIG_NET_ACT_SKBEDIT=y
CONFIG_NET_ACT_CSUM=y
CONFIG_NET_ACT_VLAN=y
CONFIG_NET_ACT_BPF=y
CONFIG_NET_ACT_CONNMARK=y
CONFIG_NET_ACT_CT=y
CONFIG_NET_ACT_TUNNEL_KEY=y
CONFIG_IFB=y
# socket diagnostics (ss, ss -K)
CONFIG_INET_DIAG=y
CONFIG_INET_TCP_DIAG=y
CONFIG_INET_UDP_DIAG=y
CONFIG_INET_RAW_DIAG=y
CONFIG_INET_DIAG_DESTROY=y
CONFIG_UNIX_DIAG=y
CONFIG_PACKET_DIAG=y
CONFIG_NETLINK_DIAG=y
# interfaces and tunnels: macvlan/ipvlan networks, VLANs, WireGuard, IPsec.
# Not PF_KEY (NET_KEY, IPsec's old interface; ip xfrm uses XFRM_USER) or
# the route4 classifier: rarely used, and both have had privilege bugs.
CONFIG_MACVLAN=y
CONFIG_IPVLAN=y
CONFIG_VLAN_8021Q=y
CONFIG_IPV6_MULTIPLE_TABLES=y
CONFIG_NET_L3_MASTER_DEV=y
CONFIG_NET_VRF=y
CONFIG_BONDING=y
CONFIG_WIREGUARD=y
CONFIG_GENEVE=y
CONFIG_NET_IPIP=y
CONFIG_NET_IPGRE_DEMUX=y
CONFIG_NET_IPGRE=y
CONFIG_IPV6_TUNNEL=y
CONFIG_IPV6_SIT=y
CONFIG_IPV6_GRE=y
CONFIG_XFRM_USER=y
CONFIG_XFRM_INTERFACE=y
CONFIG_INET_AH=y
CONFIG_INET_ESP=y
CONFIG_INET_IPCOMP=y
CONFIG_INET6_AH=y
CONFIG_INET6_ESP=y
CONFIG_INET6_IPCOMP=y
Binary file not shown.
+5 -1
View File
@@ -15,7 +15,11 @@ UI = os.path.join(ROOT, "crates/kiri/src/ui")
def page(test, os_name=None):
index = open(os.path.join(UI, "index.html")).read().replace("/*ICONS*/", open(os.path.join(UI, "icons.js")).read())
# As assemble.rs builds it: the icons and xterm.js spliced in.
xterm = lambda f: open(os.path.join(UI, "xterm", f)).read()
index = (open(os.path.join(UI, "index.html")).read().replace("/*ICONS*/", open(os.path.join(UI, "icons.js")).read(), 1)
.replace("/*XTERM_CSS*/", xterm("xterm.css"), 1)
.replace("/*XTERM_JS*/", "".join(xterm(f) + "\n" for f in ["xterm.js", "addon-fit.js", "addon-search.js", "addon-web-links.js"]), 1))
if os_name and os_name != "macos":
index = index.replace("<head>", f'<head><script>window.KIRI_OS = "{os_name}";</script>', 1)
fixture = open(os.path.join(ROOT, "tests/ui/fixture.js")).read()
+60 -9
View File
@@ -18,6 +18,12 @@ FAILED=()
# own Finder folder (~/Kiri Dev) and no *.kiri.localhost routers: there is
# one pair of ports 80 and 443 on a Mac, and the installed Kiri has them.
FEATURE=${DOCKER_CONTEXT#kiri}; FEATURE=${FEATURE#-}
# The engine under test's socket. Every `kiri` command (machines, k8s) and
# every direct API call goes there, never to another Kiri on this Mac: once,
# the Kubernetes checks ran on the installed Kiri and deleted its cluster.
SOCK=$(docker context inspect "$DOCKER_CONTEXT" --format '{{.Endpoints.docker.Host}}' 2>/dev/null); SOCK=${SOCK#unix://}
[ -S "$SOCK" ] || { echo "e2e: no engine socket for context $DOCKER_CONTEXT ($SOCK)"; exit 1; }
export KIRI_SOCKET=$SOCK
if [ -z "$FEATURE" ]; then KF="$HOME/Kiri"; else KF="$HOME/Kiri $(printf %s "${FEATURE:0:1}" | tr a-z A-Z)${FEATURE:1}"; fi
KFQ=$(printf %q "$KF")
@@ -180,7 +186,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
@@ -215,6 +234,7 @@ code network-rm-builtin 1 $D network rm bridge
# (as with Docker), while the network itself still works.
$D network create --internal intnet >/dev/null
$D run -d --name intweb --network intnet nginx:alpine >/dev/null
nginx_up intweb
t internal-same-net "Welcome to nginx" $D run --rm --network intnet alpine wget -qO- -T 5 http://intweb
t internal-no-route "unreachable" $D run --rm --network intnet alpine sh -c 'ping -c 1 -W 2 1.1.1.1 2>&1; true'
t internal-no-default "none" $D run --rm --network intnet alpine sh -c 'ip route | grep -q default && echo default || echo none'
@@ -401,6 +421,9 @@ t vol-copyup-owner "same:redis:redis 755" bash -c "i=\$($D run --rm redis:7-alpi
t vol-copyup-tree "same" bash -c "i=\$($D run --rm alpine sh -c 'cd /etc/apk && { find . -exec stat -c \"%n %A %u %g\" {} +; find . -type f -exec md5sum {} +; } | sort | md5sum'); v=\$($D run --rm -v tapk:/etc/apk alpine sh -c 'cd /etc/apk && { find . -exec stat -c \"%n %A %u %g\" {} +; find . -type f -exec md5sum {} +; } | sort | md5sum'); [ \"\$i\" = \"\$v\" ] && echo same"
t vol-copyup-not-over "1 mine" bash -c "$D run --rm -v tkeep:/usr/share/nginx/html nginx:alpine sh -c 'rm /usr/share/nginx/html/*; echo mine > /usr/share/nginx/html/mine' && $D run --rm -v tkeep:/usr/share/nginx/html nginx:alpine sh -c 'echo \$(ls /usr/share/nginx/html | wc -l) \$(cat /usr/share/nginx/html/mine)'"
t redis-volume "PONG OK running" bash -c "$D run -d --name rv -v tredis:/data redis:7-alpine >/dev/null; for i in \$(seq 50); do $D exec rv redis-cli ping 2>/dev/null | grep -q PONG && break; sleep 0.2; done; p=\$($D exec rv redis-cli ping); s=\$($D exec rv redis-cli save); sleep 1; echo \$p \$s \$($D inspect -f '{{.State.Status}}' rv)"
# A volume over part of a bind (`./:/app` and `/app/node_modules`) is filled
# from the image, as Docker does, never from the host's folder under it.
t vol-copyup-under-bind "index.html" bash -c "h=\$(mktemp -d); mkdir \$h/html; echo mac > \$h/html/from-host.txt; $D run --rm -v \$h:/usr/share/nginx -v /usr/share/nginx/html nginx:alpine sh -c 'cd /usr/share/nginx/html; [ -e from-host.txt ] && echo from the host || ls'; rm -rf \$h"
$D rm -f rv >/dev/null 2>&1; $D volume rm towner tapk tkeep tredis >/dev/null 2>&1
t vol-in-use "in use" bash -c "$D run -d --name vu -v tvol:/v alpine sleep 30 >/dev/null; $D volume rm tvol"
$D rm -f vu >/dev/null
@@ -514,6 +537,17 @@ t priv-inspect "true" bash -c "$D run -d --name pv --privileged alpine sleep 30
t priv-exec-caps "000001ffffffffff" $D exec pv grep CapEff /proc/self/status
$D rm -f pv >/dev/null
section "kernel: netfilter, tc and interfaces"
# Every line of tests/kernel-features.sh (nftables expressions, the iptables
# matches and targets, ipset, IPVS, tc, ss, macvlan/WireGuard/IPsec...) is
# one check: Kiri's guest kernel builds them all in, as it loads no modules.
KFEAT=$(perl -e 'alarm 180; exec @ARGV' $D run --rm --privileged -v "$(cd "$(dirname "$0")" && pwd)/kernel-features.sh:/k.sh:ro" alpine:3.22 sh /k.sh 2>&1 | tr -d '\r')
# One check per line; the line itself is what shows when it fails.
for name in $(printf '%s\n' "$KFEAT" | grep -E '^[a-z0-9-]+ (ok|FAIL)' | cut -d' ' -f1); do
t "kernel-$name" "$name ok" bash -c 'printf "%s\n" "$1" | grep -E "^$2 (ok|FAIL)"' _ "$KFEAT" "$name"
done
printf '%s\n' "$KFEAT" | grep -qE '^[a-z0-9-]+ (ok|FAIL)' || t kernel-features "ok" printf '%s\n' "$KFEAT"
section "images: tag, save, load"
IMD=$(mktemp -d)
t tag "kiri-test/alp:v1" bash -c "$D tag alpine kiri-test/alp:v1 && $D images --format '{{.Repository}}:{{.Tag}}'"
@@ -540,6 +574,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 +682,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'"
@@ -659,7 +704,10 @@ t stdin-slow-reader "30000000" bash -c "head -c 30000000 /dev/zero | $D run --rm
t seccomp-fork "node ok" $D run --rm node:22-alpine node -e 'require("child_process").execSync("true"); console.log("node ok")'
t cap-default "00000000a80425fb" $D run --rm alpine grep CapEff /proc/self/status
t cap-drop-all "0000000000000000" $D run --rm --cap-drop ALL alpine grep CapEff /proc/self/status
t cap-drop-net-raw "permission denied" $D run --rm --cap-drop NET_RAW alpine ping -c1 -W1 127.0.0.1
# ping needs no NET_RAW: it uses ping sockets, which ping_group_range opens
# to every group, as on Docker. Without them, dropping NET_RAW stops it.
t cap-drop-net-raw-ping "round-trip" $D run --rm --cap-drop NET_RAW alpine ping -c1 -W1 127.0.0.1
t cap-drop-net-raw "permission denied" $D run --rm --cap-drop NET_RAW --sysctl net.ipv4.ping_group_range="1 0" alpine ping -c1 -W1 127.0.0.1
t cap-add-net-admin "ok" bash -c "$D run --rm --cap-add NET_ADMIN alpine sh -c 'ip link set lo mtu 1400 && echo ok'"
t cap-add-sys-admin "mounted" $D run --rm --cap-add SYS_ADMIN alpine sh -c 'mount -t tmpfs t /mnt && echo mounted'
t cap-inspect "NET_ADMIN]" bash -c "$D create --name capi --cap-add NET_ADMIN alpine >/dev/null; $D inspect -f '{{.HostConfig.CapAdd}}' capi; $D rm capi >/dev/null"
@@ -683,7 +731,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
@@ -711,14 +760,16 @@ fi
if [ "${K8S:-0}" = 1 ]; then
section "Kubernetes (K8S=1)"
KH=$(mktemp -d); mkdir -p "$KH/.kube"
KK="env HOME=$KH KIRI_SOCKET=$HOME/.kiri/run/docker.sock $KQ k8s"
KK="env HOME=$KH KIRI_SOCKET=$SOCK $KQ k8s"
t k8s-start "is ready" bash -c "$KK start"
t k8s-node "Ready" env HOME="$KH" kubectl --context kiri get nodes
t k8s-deploy "successfully rolled out" bash -c "env HOME=$KH kubectl --context kiri create deployment web --image=nginx:alpine >/dev/null && env HOME=$KH kubectl --context kiri rollout status deploy/web --timeout=120s"
# The context `kiri k8s start` wrote: named after the Kiri build, not always `kiri`.
KCTX=$(env HOME="$KH" kubectl config get-contexts -o name 2>/dev/null | head -1); KCTX=${KCTX:-kiri}
t k8s-node "Ready" env HOME="$KH" kubectl --context $KCTX get nodes
t k8s-deploy "successfully rolled out" bash -c "env HOME=$KH kubectl --context $KCTX create deployment web --image=nginx:alpine >/dev/null && env HOME=$KH kubectl --context $KCTX rollout status deploy/web --timeout=120s"
# CoreDNS may still be starting: ask a few times, as a client would.
t k8s-service-dns "Welcome to nginx" bash -c "env HOME=$KH kubectl --context kiri expose deploy web --port 80 >/dev/null; for i in 1 2 3 4 5 6; do out=\$(env HOME=$KH kubectl --context kiri run t\$i --rm -i --restart=Never --image=alpine -- wget -qO- -T 5 http://web.default.svc.cluster.local 2>/dev/null); echo \"\$out\" | grep -q Welcome && break; sleep 3; done; echo \"\$out\""
t k8s-loadbalancer "Welcome to nginx" bash -c "env HOME=$KH kubectl --context kiri expose deploy web --name web-lb --type=LoadBalancer --port 18091 --target-port 80 >/dev/null; for i in \$(seq 60); do curl -s -m 2 http://localhost:18091 | grep -q Welcome && break; sleep 2; done; curl -s -m 2 http://localhost:18091"
t k8s-loadbalancer-gone "gone" bash -c "env HOME=$KH kubectl --context kiri delete svc web-lb >/dev/null; sleep 7; curl -s -m 2 http://localhost:18091 || echo gone"
t k8s-service-dns "Welcome to nginx" bash -c "env HOME=$KH kubectl --context $KCTX expose deploy web --port 80 >/dev/null; for i in 1 2 3 4 5 6; do out=\$(env HOME=$KH kubectl --context $KCTX run t\$i --rm -i --restart=Never --image=alpine -- wget -qO- -T 5 http://web.default.svc.cluster.local 2>/dev/null); echo \"\$out\" | grep -q Welcome && break; sleep 3; done; echo \"\$out\""
t k8s-loadbalancer "Welcome to nginx" bash -c "env HOME=$KH kubectl --context $KCTX expose deploy web --name web-lb --type=LoadBalancer --port 18091 --target-port 80 >/dev/null; for i in \$(seq 60); do curl -s -m 2 http://localhost:18091 | grep -q Welcome && break; sleep 2; done; curl -s -m 2 http://localhost:18091"
t k8s-loadbalancer-gone "gone" bash -c "env HOME=$KH kubectl --context $KCTX delete svc web-lb >/dev/null; sleep 7; curl -s -m 2 http://localhost:18091 || echo gone"
t k8s-stop "exited" bash -c "$KK stop >/dev/null && $KK status"
t k8s-resume "is ready" bash -c "$KK start"
t k8s-delete "deleted" bash -c "$KK delete"
@@ -739,7 +790,7 @@ if [ "${SOAK:-0}" -gt 0 ]; then
fds() { lsof -p "$DPID" 2>/dev/null | wc -l | tr -d ' '; }
guest() { $D run --rm --network host alpine sh -c 'echo "$(ls /var/lib/kiri/containers 2>/dev/null | wc -l) $(ls -d /sys/fs/cgroup/kiri/*/ 2>/dev/null | wc -l) $(ip -o link | grep -c " kv") $(ls /run/kiri 2>/dev/null | wc -l) $(awk "/MemTotal/{t=\$2} /MemAvailable/{a=\$2} END{print t-a}" /proc/meminfo)"' 2>/dev/null; }
# The balloon's pages count as used inside the guest; take them out.
ballooned() { curl -s --unix-socket "$HOME/.kiri/run/docker.sock" http://d/info | python3 -c 'import json,sys; d=json.load(sys.stdin); print((d["KiriMemoryCeiling"] - d["KiriMemoryTarget"]) // 1024)'; }
ballooned() { curl -s --unix-socket "$SOCK" http://d/info | python3 -c 'import json,sys; d=json.load(sys.stdin); print((d["KiriMemoryCeiling"] - d["KiriMemoryTarget"]) // 1024)'; }
# Warm up, then take the baseline.
for i in $(seq 20); do $D run --rm alpine true >/dev/null 2>&1; done
read -r c0 g0 v0 r0 m0 <<<"$(guest)"; m0=$((m0 - $(ballooned)))
+99
View File
@@ -0,0 +1,99 @@
#!/bin/sh
# What firewall rulesets, IDS/IPS, transparent proxies and network tests ask
# of the kernel: nftables expressions and families, the iptables matches and
# targets iptables-nft hands to xtables, ipset types, tc, socket diagnostics
# and the usual interfaces. Runs inside a privileged Alpine container and
# prints "<name> ok" or "<name> FAIL: <why>" for each; tests/e2e.sh checks
# every line. Started from issue #14's probe. Any engine can run it:
#
# docker run --rm --privileged -v "$PWD/tests/kernel-features.sh:/k.sh" alpine:3.22 sh /k.sh
timeout 120 apk add -q nftables iptables ip6tables ebtables iproute2 iproute2-ss ipset ipvsadm >/dev/null 2>&1 || { echo "setup FAIL: apk add"; exit 1; }
say() { if [ "$2" = 0 ]; then echo "$1 ok"; else echo "$1 FAIL: $(head -c 200 /tmp/e | tr '\n' ' ')"; fi; }
# run NAME COMMAND...: one check, ok when the command succeeds.
run() { n=$1; shift; "$@" >/tmp/e 2>&1; say "$n" $?; }
# nft NAME FAMILY HOOK RULE: a chain with RULE in it loads.
nftr() {
printf 'table %s probe {\n chain c {\n type filter hook %s priority 0;\n %s\n }\n}\n' "$2" "$3" "$4" > /tmp/r
nft -f /tmp/r >/tmp/e 2>&1; say "nft-$1" $?
nft delete table "$2" probe 2>/dev/null
}
# nftables expressions (issue #14's list first)
nftr reject-tcp inet prerouting "meta l4proto tcp reject with tcp reset"
nftr reject-icmpx inet input "reject with icmpx admin-prohibited"
nftr queue inet forward "queue num 0 bypass"
nftr ct-label inet prerouting "ct label set 3"
nftr socket inet prerouting "socket transparent 1"
nftr tproxy inet prerouting "meta l4proto tcp tproxy ip to 127.0.0.1:8443"
nftr log-group inet input "log group 1"
nftr limit inet prerouting "limit rate 10/second"
nftr quota inet prerouting "quota 10 mbytes"
nftr connlimit inet input "ct count over 10 drop"
nftr numgen inet prerouting "meta mark set numgen inc mod 2"
nftr hash inet prerouting "meta mark set jhash ip saddr mod 2"
nftr synproxy inet input "tcp dport 80 ct state invalid,untracked synproxy mss 1460 wscale 7"
nftr osf inet input "osf name \"Linux\" accept"
nftr dup ip prerouting "dup to 127.0.0.1"
nftr xfrm inet input "meta secpath exists accept"
# families and flowtables
printf 'table netdev probe {\n chain c {\n type filter hook ingress device lo priority 0;\n accept\n }\n}\n' > /tmp/r
run nft-netdev nft -f /tmp/r; nft delete table netdev probe 2>/dev/null
printf 'table arp probe {\n chain c {\n type filter hook input priority 0;\n accept\n }\n}\n' > /tmp/r
run nft-arp nft -f /tmp/r; nft delete table arp probe 2>/dev/null
printf 'table bridge probe {\n chain c {\n type filter hook input priority 0;\n meta ibrname "x" reject\n }\n}\n' > /tmp/r
run nft-bridge nft -f /tmp/r; nft delete table bridge probe 2>/dev/null
printf 'table inet probe {\n flowtable f {\n hook ingress priority 0; devices = { lo };\n }\n chain c {\n type filter hook forward priority 0;\n meta l4proto tcp flow add @f\n }\n}\n' > /tmp/r
run nft-flowtable nft -f /tmp/r; nft delete table inet probe 2>/dev/null
# iptables (iptables-nft, so through xtables)
ipt() { n=$1; shift; iptables -A INPUT "$@" >/tmp/e 2>&1; r=$?; [ $r = 0 ] && iptables -D INPUT "$@" 2>/dev/null; say "ipt-$n" $r; }
ipt nfqueue -p tcp --dport 9 -j NFQUEUE --queue-num 0 --queue-bypass
ipt nflog -j NFLOG --nflog-group 1
ipt recent -m recent --name probe --rcheck --seconds 60 -j DROP
ipt hashlimit -m hashlimit --hashlimit-above 10/sec --hashlimit-name probe -j DROP
ipt connlimit -p tcp -m connlimit --connlimit-above 10 -j DROP
ipt string -m string --algo bm --string probe -j DROP
ipt u32 -m u32 --u32 "0>>22&0x3C@0>>16=0x50" -j DROP
ipt state -m state --state NEW -j ACCEPT
ipt time -m time --timestart 09:00 --timestop 17:00 -j ACCEPT
ipt length -m length --length 1000:1500 -j ACCEPT
ipt mac -m mac --mac-source 02:00:00:00:00:01 -j DROP
run ipt-tproxy iptables -t mangle -A PREROUTING -p tcp --dport 9 -j TPROXY --on-port 9 --tproxy-mark 1
run ipt-tcpmss iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
run ipt-notrack iptables -t raw -A PREROUTING -p udp --dport 9 -j CT --notrack
run ip6t-raw ip6tables -t raw -A PREROUTING -p udp --dport 9 -j CT --notrack
run ebtables ebtables -t filter -L
# ipset, IPVS, tc
run ipset-netnet ipset create probe1 hash:net,net
run ipset-list ipset create probe2 list:set
ipset destroy probe2 2>/dev/null; ipset destroy probe1 2>/dev/null
run ipvs ipvsadm -A -t 10.255.0.1:80 -s rr
ipvsadm -C 2>/dev/null
run tc-netem tc qdisc add dev lo root netem delay 1ms
tc qdisc del dev lo root 2>/dev/null
run tc-ingress tc qdisc add dev lo clsact
run tc-flower tc filter add dev lo ingress protocol ip flower ip_proto tcp action drop
tc qdisc del dev lo clsact 2>/dev/null
# socket diagnostics
run ss ss -tan
ss -K dst 192.0.2.1 >/tmp/e 2>&1; if grep -qi "not supported" /tmp/e; then say ss-kill 1; else say ss-kill 0; fi
# interfaces and tunnels
# link NAME ARGS...: `ip link add ARGS` makes probe0, which goes again after.
link() { n=$1; shift; ip link add "$@" >/tmp/e 2>&1; say "link-$n" $?; ip link del probe0 2>/dev/null; }
link macvlan link eth0 probe0 type macvlan mode bridge
link ipvlan link eth0 probe0 type ipvlan mode l2
link vlan link eth0 probe0 type vlan id 10
link wireguard probe0 type wireguard
link vrf probe0 type vrf table 10
link bond probe0 type bond
link geneve probe0 type geneve id 10 remote 192.0.2.1
link gre probe0 type gre remote 192.0.2.1
link ipip probe0 type ipip remote 192.0.2.1
link ip6tnl probe0 type ip6tnl remote 2001:db8::1
link ifb probe0 type ifb
run xfrm ip xfrm state add src 192.0.2.1 dst 192.0.2.2 proto esp spi 0x1 mode tunnel enc 'cbc(aes)' 0x00112233445566778899aabbccddeeff auth 'hmac(sha256)' 0x00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff
ip xfrm state flush 2>/dev/null
+7
View File
@@ -40,6 +40,13 @@ t ipv6-cleanup "gone" "docker rm -f v6a web6 >/dev/null; docker network rm lh6 >
t ipv6-forwarding-restored "0" "cat /proc/sys/net/ipv6/conf/all/forwarding"
# A build's --add-host host-gateway is the bridge gateway, as for docker run (not the Mac VM's 198.19.248.254).
t build-host-gateway "GW-OK" "gw=\$(docker network inspect bridge --format '{{(index .IPAM.Config 0).Gateway}}'); mkdir -p /bhg && printf 'FROM alpine:3.21\\nRUN grep -w hgw /etc/hosts\\n' > /bhg/Dockerfile && DOCKER_BUILDKIT=0 docker build --no-cache --add-host hgw:host-gateway /bhg 2>&1 | grep -q \"\$gw\" && echo GW-OK"
# A privileged container must not touch the host's /dev. The kernel has one
# devtmpfs, so mount it, put ptmx back as the device it should be, run a
# privileged container and look again: once, ptmx became a link into the
# host's /dev/pts and no user on the machine could open a terminal.
t privileged-host-ptmx "character special file" "mkdir -p /hostdev && mount -t devtmpfs none /hostdev && { [ -c /hostdev/ptmx ] || { rm -f /hostdev/ptmx && mknod -m 666 /hostdev/ptmx c 5 2 && chgrp 5 /hostdev/ptmx; }; } && docker run --rm --privileged alpine true && stat -c %F /hostdev/ptmx; umount /hostdev"
t privileged-devices "DEVS-OK" "docker run --rm --privileged alpine sh -c 'test -c /dev/kmsg && test -c /dev/null && test -L /dev/ptmx && test -c /dev/pts/ptmx && echo DEVS-OK'"
t privileged-tty "/dev/pts/0" "docker run --rm -t --privileged alpine tty"
t cleanup "web" "docker rm -f web db dns"
$D rm -f kiri-linux-host >/dev/null
echo "$PASS passed, $FAIL failed"
+30
View File
@@ -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);
+166
View File
@@ -0,0 +1,166 @@
// parity: macos windows linux
// The built-in terminal: a panel under the page, with tabs, splits, find and
// its own text size, the same on every system (only the keys differ). Runs
// as each OS; what the panel offers is listed as ITEM lines.
const R = [], items = [];
const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } };
const ok = (c, m) => { if (!c) throw new Error(m); };
const terms = (name) => sent.filter((s) => s.type === "term" && s.name === name);
const decode = (b64) => new TextDecoder().decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));
const b64 = (s) => btoa(String.fromCharCode(...new TextEncoder().encode(s)));
const drawer = document.getElementById("htdrawer");
const panes = () => [...drawer.querySelectorAll(".htbody .htpane")];
const key = (target, o) => target.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...o }));
const OSK = WIN ? { sd: { key: "_", code: "Minus", altKey: true, shiftKey: true }, close: { key: "W", ctrlKey: true, shiftKey: true }, find: { key: "F", ctrlKey: true, shiftKey: true }, zin: { key: "=", ctrlKey: true } }
: LINUX ? { sd: { key: ")", ctrlKey: true, shiftKey: true }, close: { key: "W", ctrlKey: true, shiftKey: true }, find: { key: "F", ctrlKey: true, shiftKey: true }, zin: { key: "=", ctrlKey: true } }
: { sd: { key: "d", metaKey: true, shiftKey: true }, close: null, find: { key: "f", metaKey: true }, zin: { key: "=", metaKey: true } };
t("hidden at first, with a toggle in the status bar and the strip", () => {
ok(drawer.hidden, "drawer showing");
ok(document.querySelector("#statusbar [data-htterm]"), "no status bar toggle");
ok(document.getElementById("strip-term"), "no strip button");
items.push("terminal: status bar toggle", "terminal: strip button");
});
t("the first open asks for the shells, then starts the default one", () => {
document.querySelector("#statusbar [data-htterm]").click();
ok(terms("shells").length === 1, "didn't ask for shells");
kiri.on({ type: "term", ev: "shells", default: "/bin/zsh", shells: [{ id: "/bin/zsh", label: "zsh", group: "" }, { id: "/bin/bash", label: "bash", group: "" }, { id: "wsl:Ubuntu", label: "WSL · Ubuntu", group: "WSL" }] });
ok(!drawer.hidden, "drawer still hidden");
const open = terms("open");
ok(open.length === 1 && open[0].value.shell === "/bin/zsh", "open: " + JSON.stringify(open));
ok(open[0].value.cols > 10 && open[0].value.rows > 2, "size: " + JSON.stringify(open[0].value));
ok(drawer.querySelector(".httab.on")?.textContent.includes("zsh"), "tab label");
// The tab's close button is drawn: its icon has a stroke and a size.
const xs = getComputedStyle(drawer.querySelector(".httab.on .x svg"));
ok(xs.stroke !== "none" && parseFloat(xs.width) > 0, `close icon: stroke ${xs.stroke}, width ${xs.width}`);
ok(document.getElementById("strip-term").getAttribute("aria-pressed") === "true", "strip button not pressed");
for (const b of drawer.querySelectorAll(".hthead [data-ht]")) items.push(`terminal button: ${b.getAttribute("aria-label")}`);
});
const first = () => ht.panes.get(terms("open")[0].id);
t("what's typed goes to the shell as bytes", () => {
first().term.input("ls ✓\r");
const last = terms("input").pop();
ok(last && last.id === first().id && decode(last.value) === "ls ✓\r", "input: " + JSON.stringify(last));
});
t("the new-tab menu lists the shells, grouped", () => {
drawer.querySelector('[data-ht="menu"]').click();
const m = drawer.querySelector(".htmenu");
ok(!m.hidden, "menu hidden");
ok([...m.querySelectorAll("[data-htshell]")].map((b) => b.dataset.htshell).join() === "/bin/zsh,/bin/bash,wsl:Ubuntu", "items");
ok(m.querySelector(".ml")?.textContent === "WSL", "group heading");
m.querySelector('[data-htshell="/bin/bash"]').click();
ok(ht.tabs.length === 2 && terms("open").pop().value.shell === "/bin/bash", "second tab");
items.push("terminal: shell menu");
drawer.querySelector('[data-httab="0"]').click();
});
t("right-click a tab to pin it: first in the row, no ×, not closed by accident", () => {
const second = drawer.querySelector('[data-httab="1"]');
second.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 40, clientY: 10 }));
const menu = drawer.querySelector(".htctx");
ok(!menu.hidden && /Pin tab/.test(menu.textContent), "no menu");
menu.querySelector("[data-htpin]").click();
ok(ht.tabs[0].pinned && ht.tabs[0].shell === "/bin/bash", "not first");
const tab0 = drawer.querySelector('[data-httab="0"]');
ok(tab0.querySelector(".pin") && !tab0.querySelector("[data-htx]"), "still has ×");
const closes = terms("close").length;
ht.at = 0; htRender();
htDo("close");
ok(ht.tabs.length === 2 && terms("close").length === closes, "pinned tab closed");
drawer.querySelector('[data-httab="0"]').dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 40, clientY: 10 }));
ok(/Unpin tab/.test(menu.textContent), "no unpin");
menu.querySelector("[data-htpin]").click();
ok(!ht.tabs.some((t) => t.pinned), "still pinned");
items.push("terminal: pin a tab");
drawer.querySelector('[data-httab="0"]').click();
});
t("split right, then split down from the keyboard", () => {
drawer.querySelector('[data-ht="sr"]').click();
ok(panes().length === 2 && drawer.querySelector(".htbody").classList.contains("many"), "split right");
key(ht.panes.get(ht.focus).term.textarea, OSK.sd);
ok(panes().length === 3, `split down: ${panes().length} panes`);
ok(drawer.querySelector(".htsplit.v"), "no vertical split");
});
t("each split pane has its own ×", () => {
const before = panes().length, el = panes()[0], id = el.dataset.id;
ok(getComputedStyle(el.querySelector(".htpx svg")).stroke !== "none", "× not drawn");
el.querySelector("[data-htpx]").click();
ok(panes().length === before - 1 && terms("close").some((s) => s.id === id), "× didn't close the pane");
drawer.querySelector('[data-ht="sr"]').click();
});
t("a paste of several lines asks first", () => {
const p = ht.panes.get(ht.focus), before = terms("input").length;
kiri.on({ type: "term", ev: "paste", id: p.id, text: "echo a\necho b\n" });
const ask = p.el.querySelector(".htask");
ok(ask && /Paste 2 lines/.test(ask.textContent), "no question");
ok(terms("input").length === before, "pasted before asking");
ask.querySelector('[data-htask="yes"]').click();
ok(decode(terms("input").pop().value).includes("echo a\recho b"), "pasted text");
});
t("one line pastes straight in", () => {
const p = ht.panes.get(ht.focus);
kiri.on({ type: "term", ev: "paste", id: p.id, text: "docker ps" });
ok(!p.el.querySelector(".htask") && decode(terms("input").pop().value) === "docker ps", "single line");
});
t("text size: its own, from the keys and the window's ⌘+ while focused", () => {
const fs = htFs();
key(ht.panes.get(ht.focus).term.textarea, OSK.zin);
ok(htFs() === fs + 1, "key: " + htFs());
ht.panes.get(ht.focus).term.focus();
const scale = prefs.scale;
kiri.on({ type: "textsize", step: 1 });
ok(htFs() === fs + 2 && prefs.scale === scale, "menu step went to the window");
ok(sent.some((s) => s.type === "setpref" && s.name === "termFs"), "not saved");
kiri.on({ type: "textsize", step: 0 });
ok(htFs() === 12, "reset");
});
t("find opens from its key", () => {
key(ht.panes.get(ht.focus).term.textarea, OSK.find);
ok(!drawer.querySelector(".htfind").hidden, "find hidden");
drawer.querySelector('[data-ht="findx"]').click();
ok(drawer.querySelector(".htfind").hidden, "find still open");
});
t("closing a pane ends its shell", () => {
const id = ht.focus;
if (OSK.close) key(ht.panes.get(id).term.textarea, OSK.close);
else { ht.panes.get(id).term.focus(); kiri.on({ type: "closekey" }); }
ok(terms("close").some((s) => s.id === id), "no close sent");
ok(panes().length === 2, `${panes().length} panes`);
});
t("⌘W away from the terminal closes the window", () => {
document.activeElement?.blur();
kiri.on({ type: "closekey" });
ok(sent.some((s) => s.type === "closewindow"), "no closewindow");
});
t("a shell that exits closes its pane; one that can't start says why", () => {
const id = ht.focus;
kiri.on({ type: "term", ev: "exit", id, code: 0 });
ok(panes().length === 1 && !ht.panes.has(id), "pane stayed");
ok(!terms("close").some((s) => s.id === id), "closed an ended shell again");
const left = ht.focus;
kiri.on({ type: "term", ev: "exit", id: left, error: "No such file" });
ok(ht.panes.has(left) && ht.panes.get(left).exited, "a failed start vanished");
});
t("hiding keeps the shells running", () => {
const closes = terms("close").length;
drawer.querySelector('[data-ht="hide"]').click();
ok(drawer.hidden && terms("close").length === closes, "hide closed shells");
document.getElementById("strip-term").click();
ok(!drawer.hidden && ht.tabs.length === 2, "didn't come back as it was");
});
t("maximise fills the window, and restores", () => {
drawer.querySelector('[data-ht="max"]').click();
ok(drawer.classList.contains("max"), "not maximised");
drawer.querySelector('[data-ht="max"]').click();
ok(!drawer.classList.contains("max"), "not restored");
});
t("output reaches the screen", () => {
window.liveId = [...ht.panes.values()].find((p) => !p.exited).id;
kiri.on({ type: "term", ev: "data", id: liveId, b64: b64("hello from the shell") });
});
setTimeout(() => {
t("output reaches the screen (drawn)", () => {
const p = ht.panes.get(liveId);
ok(p.term.buffer.active.getLine(0).translateToString().includes("hello from the shell"), "not written");
});
report([...R, ...items.map((x) => "ITEM " + x)]);
}, 300);
+3 -1
View File
@@ -5,7 +5,9 @@ kiri.on({ type: "status", version: "0.1.4", dev: true, app: "Kiri Dev", ours: "k
const R = [];
const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } };
const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); };
const GLYPHS = [".ctx-flow .arr", ".sh-chev", ".sc-close", ".sh-x", "tr.group .chev"];
// The terminal emulator's own sheet (xterm.css, vendored): its scrollbar
// arrows are glyphs, and the terminal's text has its own size.
const GLYPHS = [".ctx-flow .arr", ".sh-chev", ".sc-close", ".sh-x", "tr.group .chev", ".xterm"];
t("every font size is on the scale", () => {
const off = [];
for (const sheet of document.styleSheets) for (const r of sheet.cssRules) {