Author SHA1 Message Date
Precious Okwu d6aea8390f Merge branch 'main' into linux-window-opaque-background 2026-11-08 13:10:44 +01:00
TalaatMagdyandPrecious Okwu 5981b2be32 docker push: RepoDigests names what the registry has, as with Docker (#67)
After a push, RepoDigests named the image ID for images built, loaded
or committed here, and the source index for a pulled image tagged for
another registry: digests the registry does not have. Deploy tools that
pin to it, such as wrangler, then failed.

- A push records the manifest it put, for every tag of the image in
  that repository, unless the name became another image meanwhile.
- An image no registry has yet lists no RepoDigest, instead of one
  made from its config digest.
- docker tag into another repository carries no digest of the old one.

Fixes #64

Co-authored-by: Precious Okwu <32944039+libracoder@users.noreply.github.com>
2026-11-08 13:02:17 +01:00
Precious Okwu 2af64d8868 Builds: amd64 steps run through Rosetta on Apple silicon, not QEMU (#70) 2026-11-08 12:43:31 +01:00
Precious Okwu 108dac0748 Security: run CodeQL on every pull request, forks included (#71) 2026-11-08 12:23:11 +01:00
ZY 3fa32335cc UI: keep Images Actions visible when a tag is long (#56)
Give the Images table fixed column shares (like Containers) so a long
repository or tag ellipsises instead of pushing the action buttons off
the window. Keep the 160px tag pill cap for other views.
2026-11-08 09:41:42 +01:00
Precious Okwu 8295c185ed Guest kernel: only root may load BPF programs (#65) 2026-11-08 07:14:26 +01:00
TalaatMagdy 4e32e842b0 Guest kernel: BPF JIT, perf events, kprobe events, BTF and SHA1 (#39)
Cilium does not start in a kind cluster: the guest kernel loads no
modules, and it lacked the eBPF features the agent needs. This builds
in the ones still missing after #20:

- BPF_JIT, which Cilium requires; seccomp filters are JIT-compiled too.
- PERF_EVENTS, FTRACE, KPROBES and KPROBE_EVENTS, which give BPF_EVENTS:
  the datapath sends drop and trace events with bpf_perf_event_output
  and the agent reads them through perf_event_open.
- DEBUG_INFO_BTF, for /sys/kernel/btf/vmlinux. It needs pahole at build
  time, so build.sh installs dwarves.
- CRYPTO_SHA1, which Cilium lists; the IPsec options select SHA256 only.

bpftrace and Tetragon need the same perf event, kprobe and BTF options.

For #38.
2026-11-08 07:10:29 +01:00
Precious Okwu 41ecc592d1 CI: run the UI tests on every pull request (#62) 2026-11-08 05:49:34 +01:00
Precious Okwu d4e361b5ba Guest kernel: per-process I/O accounting, so Typesense starts (#63) 2026-11-08 05:49:05 +01:00
Precious Okwu 64474185fb Linux: revoke removed users' engine access (#51) 2026-11-08 00:10:25 +01:00
ahp 7a7a4cc44f Views open at the top, not where the last page was scrolled to (#24)
Opening a container's, pod's or service's page scrolled the content
back to the top, but switching views from the sidebar didn't. Leaving a
container's Terminal or Logs tab scrolled down then opened the next view
at that offset, below its rows: Images looked empty, Networks showed only
its last network. show() now resets the scroll as those pages do.
2026-11-07 18:22:58 +01:00
Precious Okwu 98616431e7 Mac: hide the Dock icon while the window is closed (#46) 2026-11-07 18:04:41 +01:00
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
ahp b24a57733f Linux: the window no longer flickers with WebKitGTK 2.54
The view's
  background was transparent so there would be no white flash
  before the page paints. With hardware acceleration off, WebKitGTK 2.54
  then presents only each frame's repainted regions: the sidebar, the main
  pane and the hovered row take turns, and the rest of the window shows
  through. Seen on Arch (webkit2gtk-4.1 2.54.2), on Wayland and XWayland,
  with and without a GTK theme.

  The background is now opaque, in index.html's --bg for the light or dark
  scheme, set with the theme in set_appearance. Still no white flash, and
  acceleration stays off.
2026-11-05 11:27:08 +03:30
49 changed files with 4038 additions and 133 deletions

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
# CodeQL on every pull request, contributors' forks included, on every push
# to main, and once a week (new queries find old code).
#
# GitHub's default setup for code scanning skips pull requests from forks, so
# a contributor's change was first scanned after it was merged. This replaces
# it: turn default setup off (Settings > Code security > CodeQL analysis) when
# this lands, as GitHub refuses results from a workflow while it is on.
#
# Safe for pull requests from forks: it uses pull_request (never
# pull_request_target), so a fork's code runs with a read-only token and no
# secrets, and nothing is built (build-mode: none), so no fork code executes.
# If GitHub refuses a fork's upload, the analyze step fails: a pull request is
# never shown as scanned when it wasn't. The alerts are in the run's summary
# either way.
name: CodeQL
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "27 4 * * 1"
permissions:
contents: read
concurrency:
group: codeql-${{ github.event.pull_request.number || github.ref }}-${{ github.event_name }}
cancel-in-progress: true
jobs:
analyze:
name: Analyze (${{ matrix.language }})
runs-on: ubuntu-24.04
timeout-minutes: 60
permissions:
contents: read
actions: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [actions, javascript-typescript, python, rust]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
languages: ${{ matrix.language }}
build-mode: none
queries: security-extended
- uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
category: /language:${{ matrix.language }}
output: sarif
- name: List the alerts in the summary
if: always()
run: |
ls sarif/*.sarif >/dev/null 2>&1 || { echo "No CodeQL results: the analysis did not finish." >> "$GITHUB_STEP_SUMMARY"; exit 0; }
python3 - sarif/*.sarif >> "$GITHUB_STEP_SUMMARY" <<'EOF'
import json, sys
rows = []
for path in sys.argv[1:]:
for run in json.load(open(path))["runs"]:
for r in run["results"]:
loc = r["locations"][0]["physicalLocation"]
text = r["message"]["text"].splitlines()[0].replace("|", "\\|")
rows.append(f"| `{r['ruleId']}` | `{loc['artifactLocation']['uri']}:{loc['region'].get('startLine', '')}` | {text} |")
print(f"### CodeQL ({len(rows)} alerts, before dismissals)\n")
if rows:
print("| Rule | Where | What |\n|---|---|---|")
print("\n".join(rows))
EOF
+35
View File
@@ -0,0 +1,35 @@
# The window's page tests (scripts/ui-test.py) on every pull request, so a
# change that breaks one shows on the PR before review.
#
# Safe for pull requests from forks: it runs on GitHub's machines with a
# read-only token and no secrets, and uses pull_request (never
# pull_request_target), so a fork's code can't write to the repository.
name: UI tests
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
concurrency:
group: ui-tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
ui:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run the page tests in headless Chrome
run: |
# The runner's Chrome, without the sandbox: it needs user
# namespaces the runner doesn't allow.
printf '#!/bin/sh\nexec google-chrome --no-sandbox "$@"\n' > "$RUNNER_TEMP/chrome"
chmod +x "$RUNNER_TEMP/chrome"
CHROME="$RUNNER_TEMP/chrome" python3 scripts/ui-test.py
+2 -1
View File
@@ -33,7 +33,8 @@ once; see the README.
- `python3 scripts/ui-test.py` must pass. Its parity test opens the window as
each system and fails when one shows something another doesn't, unless
`tests/ui/parity-allow.txt` gives the reason. A new line there needs a
maintainer's OK.
maintainer's OK. It also runs on every pull request; on Linux, point
`CHROME` at your Chrome or Chromium.
## Pull requests
+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.
+79 -3
View File
@@ -80,8 +80,23 @@ impl Image {
}
/// `repo@digest` as Docker shows it, by the index's digest if there was one.
pub fn repo_digest(&self) -> String {
format!("{}@{}", self.repo(), self.index_digest.as_deref().unwrap_or(&self.digest))
/// None for an image no registry has yet (built, loaded, committed, tagged
/// for another repository): its digest is its config's, which a manifest's
/// can never be, as the manifest holds it.
pub fn repo_digest(&self) -> Option<String> {
let d = self.index_digest.as_deref().unwrap_or(&self.digest);
(d != self.config_digest).then(|| format!("{}@{d}", self.repo()))
}
/// This image under another name (`docker tag`). Its registry digests
/// belong to its repository: in another one it has none until a push.
pub fn tagged(&self, name: String) -> Image {
let mut i = Image { name, ..self.clone() };
if i.repo() != self.repo() {
i.digest = self.config_digest.clone();
i.index_digest = None;
}
i
}
/// True if `r` names this image: its name, or a digest of its repository
@@ -202,6 +217,20 @@ impl Store {
self.write_index(&images)
}
/// Records the manifest a push of `name` left in its registry, so
/// RepoDigests names what the registry has, as Docker's does: deploy tools
/// pin to it. Every tag of the image in that repository gets it, as there.
/// Not if `name` became another image during the push.
pub fn set_pushed(&self, name: &str, config_digest: &str, digest: &str) -> io::Result<()> {
let mut images = self.images()?;
let Some(repo) = images.iter().find(|i| i.name == name && i.config_digest == config_digest).map(|i| i.repo().to_owned()) else { return Ok(()) };
for i in images.iter_mut().filter(|i| i.config_digest == config_digest && i.repo() == repo) {
i.digest = digest.to_owned();
i.index_digest = None;
}
self.write_index(&images)
}
/// Removes the image and deletes blobs no remaining image uses.
pub fn remove_image(&self, name: &str) -> io::Result<Option<Image>> {
let mut images = self.images()?;
@@ -384,7 +413,7 @@ mod tests {
config: RunConfig::default(),
};
assert_eq!(image.repo(), "kindest/node");
assert_eq!(image.repo_digest(), format!("kindest/node@{index}"));
assert_eq!(image.repo_digest(), Some(format!("kindest/node@{index}")));
store.put_image(image).unwrap();
for name in [format!("kindest/node@{index}"), format!("kindest/node:v1.37.0@{index}"), format!("kindest/node@{manifest}"), manifest.clone()] {
assert!(store.find(&name).unwrap().is_some(), "{name}");
@@ -393,6 +422,53 @@ mod tests {
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn a_push_leaves_the_registry_manifest_in_repo_digests() {
let root = std::env::temp_dir().join(format!("kiri-store-push-test-{}", std::process::id()));
let store = Store::open(&root).unwrap();
let d = |c: &str| format!("sha256:{}", c.repeat(64));
let image = |name: &str, config: &str, index: Option<String>| Image {
name: name.into(),
digest: d(config),
index_digest: index,
config_digest: d(config),
layers: Vec::new(),
size: 0,
platform: "linux/arm64".into(),
created: String::new(),
pulled_at: 0,
config: RunConfig::default(),
};
// Built here: no registry has it yet, so no RepoDigest, as with Docker.
store.put_image(image("localhost:5000/built:1", "1", None)).unwrap();
// The same image's other tags: one in its repository, one in another registry.
store.put_image(image("localhost:5000/built:latest", "1", None)).unwrap();
store.put_image(image("localhost:5001/built:1", "1", None)).unwrap();
// Pulled: alpine's index. Tagged in its repository it keeps that; in
// another it has none there, rather than a digest that one lacks.
let pulled = Image { digest: d("8"), ..image("alpine:latest", "2", Some(d("9"))) };
assert_eq!(pulled.tagged("alpine:old".into()).repo_digest(), Some(format!("alpine@{}", d("9"))));
store.put_image(pulled.tagged("localhost:5000/tagged:1".into())).unwrap();
store.put_image(image("localhost:5000/other:1", "3", None)).unwrap();
let repo_digest = |n: &str| store.find(n).unwrap().unwrap().repo_digest();
for n in ["localhost:5000/built:1", "localhost:5000/tagged:1", "localhost:5000/other:1"] {
assert_eq!(repo_digest(n), None, "{n}");
}
store.set_pushed("localhost:5000/built:1", &d("1"), &d("a")).unwrap();
store.set_pushed("localhost:5000/tagged:1", &d("2"), &d("b")).unwrap();
// The name now another image: that one keeps its own.
store.set_pushed("localhost:5000/other:1", &d("4"), &d("c")).unwrap();
assert_eq!(repo_digest("localhost:5000/built:1"), Some(format!("localhost:5000/built@{}", d("a"))));
// Pushing one tag gives the repository's other tags of it the digest; elsewhere it has none.
assert_eq!(repo_digest("localhost:5000/built:latest"), Some(format!("localhost:5000/built@{}", d("a"))));
assert_eq!(repo_digest("localhost:5001/built:1"), None);
assert_eq!(repo_digest("localhost:5000/tagged:1"), Some(format!("localhost:5000/tagged@{}", d("b"))));
assert_eq!(repo_digest("localhost:5000/other:1"), None);
// And a pull by the pushed digest finds the image here.
assert!(store.find(&format!("localhost:5000/built@{}", d("a"))).unwrap().is_some());
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn repo_strips_a_tag_but_not_a_port() {
let named = |name: &str| Image {
+113 -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};
@@ -867,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 {
@@ -896,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)?;
@@ -905,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)?;
@@ -923,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
@@ -1004,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.
@@ -1054,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 };
@@ -1198,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),
@@ -1212,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)?;
@@ -1227,22 +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"),
] {
if privileged {
// devtmpfs is one filesystem for the whole kernel: this dev is the
// VM's /dev, and on a Linux host, where there is no VM, the host's
// own. Replacing its ptmx with a link to pts/ptmx (mode 000 in the
// host's devpts) stopped every new terminal on the host. Nothing
// there is changed, only what is missing is added: the real ptmx
// (5:2) opens the devpts mounted beside it at dev/pts below, so
// the container still gets its own ptys (Linux 4.7 and later).
if link == c"dev/ptmx" || fs::symlink_metadata(Path::new(std::ffi::OsStr::from_bytes(link.to_bytes()))).is_ok() {
continue;
}
// SAFETY: valid NUL-terminated strings.
unsafe { libc::symlink(target.as_ptr(), link.as_ptr()) };
continue;
}
// SAFETY: valid NUL-terminated strings.
// 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())
@@ -1263,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
@@ -1397,6 +1470,15 @@ 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 };
+1 -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()));
+4
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)?))
+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
+544 -27
View File
@@ -9,52 +9,372 @@
//!
//! The daemon writes the list when it makes the socket, and `kiri host-access`
//! (run as root, from the window's onboarding through pkexec) writes it again
//! after adding someone. Someone taken out of the group keeps their entry
//! until the engine restarts and the socket is made again.
//! after adding someone.
//!
//! An entry in the list outlives the membership it was written for, so the
//! daemon doesn't rely on it alone: a `Gate` checks every new connection
//! against the group, and every few seconds checks the people still connected,
//! closing the connections of anyone removed (streams and `exec` sessions
//! too) and writing the list again without them. Removal applies as soon as
//! the system's user database says so; where that is cached (nscd, sssd), it
//! is when the cache catches up.
use std::ffi::{CStr, CString};
use std::collections::{HashMap, HashSet};
use std::ffi::{CStr, CString, OsStr};
use std::io;
use std::net::Shutdown;
use std::os::fd::AsRawFd;
use std::os::raw::{c_char, c_int};
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// How often the people still connected are checked again.
const RECHECK: Duration = Duration::from_secs(2);
/// An account or group record and the buffer its strings live in.
struct Rec<T> {
rec: T,
_buf: Vec<c_char>,
}
/// Runs a reentrant NSS lookup (getpwuid_r and the like), growing the buffer
/// until the record fits. `Ok(None)`: there is no such account or group.
///
/// # Safety
/// `T` must be `libc::passwd` or `libc::group`, and `call` the matching `_r` lookup.
unsafe fn nss<T>(mut call: impl FnMut(*mut T, *mut c_char, usize, *mut *mut T) -> c_int) -> io::Result<Option<Rec<T>>> {
let mut size = 1024;
loop {
let mut buf: Vec<c_char> = vec![0; size];
// SAFETY: passwd and group are plain data; all-zero is a valid value.
let mut rec: T = unsafe { std::mem::zeroed() };
let mut out: *mut T = std::ptr::null_mut();
match call(&mut rec, buf.as_mut_ptr(), buf.len(), &mut out) {
0 if out.is_null() => return Ok(None),
// The record's strings point into `buf`, whose heap storage moves with it.
0 => return Ok(Some(Rec { rec, _buf: buf })),
// Groups of many thousands of names run to megabytes.
libc::ERANGE if size < 1 << 28 => size *= 2,
libc::ENOENT | libc::ESRCH => return Ok(None),
e => return Err(io::Error::from_raw_os_error(e)),
}
}
}
fn account_by_uid(uid: u32) -> io::Result<Option<Rec<libc::passwd>>> {
// SAFETY: getpwuid_r with a passwd record and a buffer of the stated size.
unsafe { nss(|rec, buf, len, out| libc::getpwuid_r(uid, rec, buf, len, out)) }
}
fn account_by_name(name: &CStr) -> io::Result<Option<Rec<libc::passwd>>> {
// SAFETY: getpwnam_r with a valid C string, a passwd record and a buffer of the stated size.
unsafe { nss(|rec, buf, len, out| libc::getpwnam_r(name.as_ptr(), rec, buf, len, out)) }
}
fn group_by_name(name: &CStr) -> io::Result<Rec<libc::group>> {
// SAFETY: getgrnam_r with a valid C string, a group record and a buffer of the stated size.
unsafe { nss(|rec, buf, len, out| libc::getgrnam_r(name.as_ptr(), rec, buf, len, out)) }?
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("no group {}", name.to_string_lossy())))
}
fn c_name(s: &str) -> io::Result<CString> {
CString::new(s).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))
}
/// The account names listed in a group record.
fn names(group: &libc::group) -> Vec<&CStr> {
let mut out = Vec::new();
let mut m = group.gr_mem;
// SAFETY: gr_mem is a NULL-terminated array of account names for this group.
unsafe {
while !m.is_null() && !(*m).is_null() {
out.push(CStr::from_ptr(*m));
m = m.add(1);
}
}
out
}
fn group_members(group: &CStr) -> io::Result<Vec<String>> {
let g = group_by_name(group)?;
Ok(names(&g.rec).iter().map(|n| n.to_string_lossy().into_owned()).collect())
}
/// The users in `group` by name (its member list, not primary-group users).
pub fn members(group: &str) -> io::Result<Vec<String>> {
let name = CString::new(group).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
// SAFETY: getgrnam with a valid C string; its result is copied out at once,
// before anything else could reuse its static storage.
unsafe {
let g = libc::getgrnam(name.as_ptr());
if g.is_null() {
return Err(io::Error::new(io::ErrorKind::NotFound, format!("no group {group}")));
}
let mut out = Vec::new();
let mut m = (*g).gr_mem;
while !m.is_null() && !(*m).is_null() {
out.push(CStr::from_ptr(*m).to_string_lossy().into_owned());
m = m.add(1);
}
Ok(out)
}
group_members(&c_name(group)?)
}
/// A user's numeric id, if the account exists.
pub fn uid(user: &str) -> Option<u32> {
let name = CString::new(user).ok()?;
// SAFETY: getpwnam with a valid C string; the uid is read at once.
unsafe {
let p = libc::getpwnam(name.as_ptr());
(!p.is_null()).then(|| (*p).pw_uid)
let a = account_by_name(&c_name(user).ok()?).ok()??;
Some(a.rec.pw_uid)
}
/// The uids of the names in a group record, sorted. A name with no account
/// is left out; a lookup that fails fails the whole list, so a slow directory
/// never shrinks it.
fn uids_of(group: &libc::group) -> io::Result<Vec<u32>> {
let mut out = Vec::new();
for name in names(group) {
if let Some(a) = account_by_name(name)? {
out.push(a.rec.pw_uid);
}
}
out.sort_unstable();
out.dedup();
Ok(out)
}
fn member_uids(group: &CStr) -> io::Result<Vec<u32>> {
uids_of(&group_by_name(group)?.rec)
}
/// Gives every member of `group` read-write access to `socket` by name, so a
/// member just added can use it without signing in again. Returns how many.
pub fn grant(socket: &Path, group: &str) -> io::Result<usize> {
let uids: Vec<u32> = members(group)?.iter().filter_map(|u| uid(u)).collect();
let uids = member_uids(&c_name(group)?)?;
set(socket, &uids)?;
Ok(uids.len())
}
/// The uid at the other end of an accepted connection.
fn peer_uid(conn: &UnixStream) -> io::Result<u32> {
// SAFETY: a connected socket and zeroed storage for its credentials.
let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
// SAFETY: the output pointers are valid and the buffer is the stated size.
let r = unsafe { libc::getsockopt(conn.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&mut cred as *mut libc::ucred).cast(), &mut len) };
if r != 0 || len as usize != std::mem::size_of::<libc::ucred>() {
return Err(if r != 0 { io::Error::last_os_error() } else { io::Error::new(io::ErrorKind::InvalidData, "short peer credentials") });
}
Ok(cred.uid)
}
/// Whether the account is in the group by name or as its primary group.
fn group_member(user: &CStr, primary_gid: libc::gid_t, group: &libc::group) -> bool {
primary_gid == group.gr_gid || names(group).contains(&user)
}
/// The group's record, or `None` if the group was deleted: that leaves
/// nobody in it, which is an answer, not a failure.
fn current(group: &CStr) -> io::Result<Option<Rec<libc::group>>> {
match group_by_name(group) {
Ok(g) => Ok(Some(g)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
/// Whether the account `uid` is in the group now. No account, or no group: no.
fn member_of(uid: u32, group: Option<&libc::group>) -> io::Result<bool> {
let Some(group) = group else { return Ok(false) };
let Some(a) = account_by_uid(uid)? else { return Ok(false) };
if a.rec.pw_name.is_null() {
return Ok(false);
}
// SAFETY: pw_name is a NUL-terminated string in the record's buffer.
let user = unsafe { CStr::from_ptr(a.rec.pw_name) };
Ok(group_member(user, a.rec.pw_gid, group))
}
fn member(uid: u32, group: &CStr) -> io::Result<bool> {
member_of(uid, current(group)?.as_ref().map(|g| &g.rec))
}
/// Who may use the engine's socket: root, the account the daemon runs as, and
/// the members of one group, checked when they connect and again while they
/// stay connected.
pub struct Gate {
group: CString,
socket: PathBuf,
owner: u32,
open: Mutex<HashMap<u64, (u32, UnixStream)>>,
next: AtomicU64,
failing: AtomicBool,
/// Recent answers by uid, so the docker CLI's burst of connections per
/// command costs one lookup. They last no longer than the recheck does.
recent: Mutex<HashMap<u32, (bool, Instant)>>,
}
/// A connection the gate let in; dropping it stops watching that connection.
pub struct Seat {
gate: Arc<Gate>,
id: u64,
}
impl Drop for Seat {
fn drop(&mut self) {
self.gate.open.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.id);
}
}
impl Gate {
pub fn new(socket: &Path, group: &OsStr) -> io::Result<Arc<Gate>> {
let group = CString::new(group.as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
// SAFETY: geteuid cannot fail.
let owner = unsafe { libc::geteuid() };
Ok(Arc::new(Gate { group, socket: socket.to_owned(), owner, open: Mutex::default(), next: AtomicU64::new(0), failing: AtomicBool::new(false), recent: Mutex::default() }))
}
fn name(&self) -> std::borrow::Cow<'_, str> {
self.group.to_string_lossy()
}
fn allowed(&self, uid: u32) -> io::Result<bool> {
if uid == 0 || uid == self.owner {
return Ok(true);
}
if let Some((yes, at)) = self.recent.lock().unwrap_or_else(|e| e.into_inner()).get(&uid)
&& at.elapsed() < RECHECK
{
return Ok(*yes);
}
let yes = member(uid, &self.group)?;
self.remember(uid, yes);
Ok(yes)
}
fn remember(&self, uid: u32, yes: bool) {
let mut recent = self.recent.lock().unwrap_or_else(|e| e.into_inner());
recent.retain(|_, (_, at)| at.elapsed() < RECHECK);
recent.insert(uid, (yes, Instant::now()));
}
/// One recheck: everyone connected against one read of the group, then
/// the access list, if the group's names changed since it was written.
/// `listed`: the names the list was last written for.
fn tick(&self, listed: &mut Option<Vec<CString>>) {
let group = current(&self.group);
let connected = !self.open.lock().unwrap_or_else(|e| e.into_inner()).is_empty();
if connected {
self.sweep_with(|uid| {
if uid == 0 || uid == self.owner {
return Ok(true);
}
let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?;
let yes = member_of(uid, g.as_ref().map(|g| &g.rec))?;
self.remember(uid, yes);
Ok(yes)
});
}
let Ok(group) = group else { return };
let now: Vec<CString> = group.as_ref().map(|g| names(&g.rec).into_iter().map(CStr::to_owned).collect()).unwrap_or_default();
if listed.as_ref() == Some(&now) {
return;
}
// Only a list actually written counts: anything else is tried again.
let written = group.as_ref().map_or(Ok(Vec::new()), |g| uids_of(&g.rec)).and_then(|uids| set(&self.socket, &uids).map(|()| uids.len()));
match written {
Ok(n) => {
crate::diag::info!("socket access list written", members = n);
*listed = Some(now);
}
Err(e) if unsupported(&e) => *listed = Some(now),
Err(e) => crate::diag::warn!("socket access list not written", error = e),
}
}
/// Writes the socket's access list for the group's current members.
pub fn grant(&self) -> io::Result<usize> {
let uids = member_uids(&self.group)?;
set(&self.socket, &uids)?;
Ok(uids.len())
}
/// Checks a new connection. `None`: refused, and the reason logged.
pub fn admit(self: &Arc<Self>, conn: &UnixStream) -> Option<Seat> {
self.admit_with(conn, |uid| self.allowed(uid))
}
fn admit_with(self: &Arc<Self>, conn: &UnixStream, check: impl Fn(u32) -> io::Result<bool>) -> Option<Seat> {
let checked = peer_uid(conn).and_then(|uid| Ok((uid, check(uid)?)));
let uid = match checked {
Ok((uid, true)) => uid,
Ok((uid, false)) => {
crate::diag::warn!("socket connection refused: user is not in the access group", group = self.name(), uid = uid);
return None;
}
Err(e) => {
crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e);
return None;
}
};
let keep = match conn.try_clone() {
Ok(c) => c,
Err(e) => {
crate::diag::warn!("socket connection refused: cannot watch it", error = e);
return None;
}
};
let id = self.next.fetch_add(1, Ordering::Relaxed);
self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (uid, keep));
Some(Seat { gate: self.clone(), id })
}
/// Checks everyone still connected, once per account, and closes the
/// connections of anyone no longer allowed. A failed lookup leaves the
/// connections open (new ones are refused until lookups work again).
fn sweep_with(&self, check: impl Fn(u32) -> io::Result<bool>) -> usize {
let uids: HashSet<u32> = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(u, _)| *u).collect();
let mut removed = HashSet::new();
let mut failed = None;
for uid in uids {
match check(uid) {
Ok(true) => {}
Ok(false) => {
removed.insert(uid);
}
Err(e) => failed = Some(e),
}
}
match failed {
Some(e) if !self.failing.swap(true, Ordering::Relaxed) => crate::diag::warn!("access check failed; open connections kept until it works again", group = self.name(), error = e),
None if self.failing.swap(false, Ordering::Relaxed) => crate::diag::info!("access check works again", group = self.name()),
_ => {}
}
if removed.is_empty() {
return 0;
}
let mut closed = 0;
// Taken out as they're closed, so a thread that takes a while to
// notice isn't closed and logged again on every recheck.
self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (uid, conn)| {
if !removed.contains(uid) {
return true;
}
// Ends the connection for every thread using it: reads see the
// end, writes fail, as if the client had hung up.
let _ = conn.shutdown(Shutdown::Both);
closed += 1;
false
});
for uid in &removed {
crate::diag::warn!("connections closed: user is no longer in the access group", group = self.name(), uid = uid);
}
closed
}
/// Checks everyone connected every few seconds, and writes the access
/// list again whenever the group's members change.
pub fn watch(self: Arc<Self>) -> io::Result<()> {
std::thread::Builder::new().name("kiri-access".into()).spawn(move || {
// Unknown at first: the first recheck writes the list once more,
// so a change between startup's write and now isn't missed.
let mut listed = None;
loop {
std::thread::sleep(RECHECK);
self.tick(&mut listed);
}
})?;
Ok(())
}
}
/// Writes the socket's access list: its owner and group (rw, as the mode
/// says), each of `uids` (rw), nobody else.
pub fn set(socket: &Path, uids: &[u32]) -> io::Result<()> {
@@ -116,6 +436,124 @@ mod tests {
assert_eq!(entries, vec![(1, 6, u32::MAX), (2, 6, 1000), (2, 6, 1001), (4, 6, u32::MAX), (0x10, 6, u32::MAX), (0x20, 0, u32::MAX)]);
}
#[test]
fn membership_includes_names_and_primary_group() {
let alice = c"alice";
let mut names = [alice.as_ptr().cast_mut(), std::ptr::null_mut()];
let group = libc::group {
gr_name: c"kiri".as_ptr().cast_mut(),
gr_passwd: c"x".as_ptr().cast_mut(),
gr_gid: 100,
gr_mem: names.as_mut_ptr(),
};
assert!(group_member(alice, 1, &group));
assert!(group_member(c"bob", 100, &group));
assert!(!group_member(c"bob", 1, &group));
}
#[test]
fn accepted_connection_reports_its_peer_uid() {
let (a, _b) = UnixStream::pair().unwrap();
// SAFETY: getuid cannot fail.
assert_eq!(peer_uid(&a).unwrap(), unsafe { libc::getuid() });
}
/// The real lookup, without the root and owner shortcuts. Skipped where
/// the test's uid has no account (some CI containers).
#[test]
fn current_users_primary_group_counts() {
// SAFETY: getuid cannot fail.
let uid = unsafe { libc::getuid() };
let Some(a) = account_by_uid(uid).unwrap() else { return };
let g = {
// SAFETY: getgrgid_r with a group record and a buffer of the stated size.
let gid = a.rec.pw_gid;
unsafe { nss(|rec, buf, len, out| libc::getgrgid_r(gid, rec, buf, len, out)) }.unwrap()
};
let Some(g) = g else { return };
// SAFETY: gr_name is a NUL-terminated string in the record's buffer.
let name = unsafe { CStr::from_ptr(g.rec.gr_name) }.to_owned();
assert!(member(uid, &name).unwrap());
assert!(!member(u32::MAX - 7, &name).unwrap(), "no such account");
assert!(!member(uid, c"kiri-no-such-group-x").unwrap(), "a deleted group has nobody in it");
}
#[test]
fn lookups_from_many_threads_agree() {
// SAFETY: getuid cannot fail.
let uid = unsafe { libc::getuid() };
let Some(a) = account_by_uid(uid).unwrap() else { return };
// SAFETY: pw_name is a NUL-terminated string in the record's buffer.
let me = unsafe { CStr::from_ptr(a.rec.pw_name) }.to_owned();
std::thread::scope(|s| {
for _ in 0..8 {
s.spawn(|| {
for _ in 0..200 {
let b = account_by_uid(uid).unwrap().unwrap();
// SAFETY: as above.
assert_eq!(unsafe { CStr::from_ptr(b.rec.pw_name) }, me.as_c_str());
assert!(account_by_uid(u32::MAX - 7).unwrap().is_none());
}
});
}
});
}
fn gate() -> Arc<Gate> {
let mut g = Gate::new(Path::new("/nonexistent"), OsStr::new("kiri")).unwrap();
Arc::get_mut(&mut g).unwrap().owner = u32::MAX;
g
}
#[test]
fn root_and_the_daemons_own_account_need_no_group() {
let g = gate();
assert!(g.allowed(0).unwrap());
let mut g2 = Gate::new(Path::new("/nonexistent"), OsStr::new("kiri-no-such-group-x")).unwrap();
Arc::get_mut(&mut g2).unwrap().owner = 4242;
assert!(g2.allowed(4242).unwrap());
assert!(!g2.allowed(4243).unwrap(), "anyone else is looked up");
}
#[test]
fn refused_or_failed_checks_keep_the_connection_out() {
let g = gate();
let (a, _b) = UnixStream::pair().unwrap();
assert!(g.admit_with(&a, |_| Ok(false)).is_none());
assert!(g.admit_with(&a, |_| Err(io::Error::other("nss down"))).is_none());
assert!(g.open.lock().unwrap().is_empty());
let seat = g.admit_with(&a, |_| Ok(true)).unwrap();
assert_eq!(g.open.lock().unwrap().len(), 1);
drop(seat);
assert!(g.open.lock().unwrap().is_empty(), "a closed connection isn't watched");
}
#[test]
fn removal_closes_an_open_connection_mid_stream() {
use std::io::{Read, Write};
let g = gate();
let (a, mut b) = UnixStream::pair().unwrap();
let _seat = g.admit_with(&a, |_| Ok(true)).unwrap();
// A thread blocked reading the client, as an exec session's stdin is.
let mut reader = a.try_clone().unwrap();
let blocked = std::thread::spawn(move || reader.read(&mut [0; 16]).unwrap());
b.write_all(b"x").unwrap();
// Still a member: nothing happens.
assert_eq!(g.sweep_with(|_| Ok(true)), 0);
// A lookup failure keeps it open too.
assert_eq!(g.sweep_with(|_| Err(io::Error::other("nss down"))), 0);
assert_eq!(blocked.join().unwrap(), 1);
let mut reader = a.try_clone().unwrap();
let blocked = std::thread::spawn(move || reader.read(&mut [0; 16]).unwrap());
std::thread::sleep(Duration::from_millis(50));
// Removed: the blocked read sees the end, and the client does too.
assert_eq!(g.sweep_with(|_| Ok(false)), 1);
assert_eq!(g.sweep_with(|_| Ok(false)), 0, "closed once, not again on every recheck");
assert_eq!(blocked.join().unwrap(), 0);
assert_eq!(b.read(&mut [0; 16]).unwrap(), 0);
assert!((&a).write_all(b"y").is_err());
}
/// The kernel takes the list and lets a user who isn't in the socket's
/// group in by it, at once. Needs root (cargo test -- --ignored, as root).
#[test]
@@ -126,7 +564,7 @@ mod tests {
std::fs::create_dir_all(&dir).unwrap();
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
let sock = dir.join("s.sock");
let _l = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660)).unwrap();
// As uid `as_uid` (no groups): can it connect?
let try_as = |as_uid: u32| {
@@ -148,6 +586,85 @@ mod tests {
set(&sock, &[65534]).unwrap();
assert!(try_as(65534), "a listed user gets in");
assert!(!try_as(65533), "an unlisted one doesn't");
set(&sock, &[]).unwrap();
assert!(!try_as(65534), "removing the entry takes access away");
// An old ACL entry is not enough: the daemon's group check still says no.
set(&sock, &[65534]).unwrap();
assert!(try_as(65534));
let (conn, _) = listener.accept().unwrap();
let mut gate = Gate::new(&sock, OsStr::new("root")).unwrap();
Arc::get_mut(&mut gate).unwrap().owner = u32::MAX;
assert!(gate.admit(&conn).is_none(), "nobody is not in root's group");
std::fs::remove_dir_all(&dir).unwrap();
}
/// A real account, added to a real group and taken out again while
/// connected: its open connection is closed and the list rewritten.
/// Needs root and useradd (cargo test -- --ignored, as root, in a throwaway system).
#[test]
#[ignore]
fn removing_a_real_member_closes_their_connection() {
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::process::Command;
let run = |args: &[&str]| assert!(Command::new(args[0]).args(&args[1..]).status().unwrap().success(), "{args:?}");
let _ = Command::new("userdel").arg("kiritest").status();
let _ = Command::new("groupdel").arg("kiritestg").status();
run(&["groupadd", "kiritestg"]);
run(&["useradd", "-M", "-G", "kiritestg", "kiritest"]);
let who = uid("kiritest").unwrap();
assert!(members("kiritestg").unwrap().contains(&"kiritest".to_owned()));
let dir = Path::new("/dev/shm").join(format!("kiri-gate-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
let sock = dir.join("s.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660)).unwrap();
let mut gate = Gate::new(&sock, OsStr::new("kiritestg")).unwrap();
Arc::get_mut(&mut gate).unwrap().owner = u32::MAX;
assert_eq!(gate.grant().unwrap(), 1);
// The member connects (by the list: they have no group in this
// process) and waits for an answer that never comes.
// SAFETY: fork in a test; the child only drops ids, connects, reads and exits.
let pid = unsafe {
let pid = libc::fork();
if pid == 0 {
// A gid that isn't the test group, so only the list can let it in.
if libc::setgroups(0, std::ptr::null()) != 0 || libc::setgid(65534) != 0 || libc::setuid(who) != 0 {
libc::_exit(3);
}
let code = match std::os::unix::net::UnixStream::connect(&sock) {
Ok(mut c) => match c.read(&mut [0; 1]) {
Ok(0) => 0,
_ => 2,
},
Err(_) => 1,
};
libc::_exit(code);
}
pid
};
let (conn, _) = listener.accept().unwrap();
let _seat = gate.admit(&conn).expect("a member is let in");
let mut listed = None;
gate.tick(&mut listed);
assert_eq!(gate.open.lock().unwrap().len(), 1, "still a member");
run(&["gpasswd", "-d", "kiritest", "kiritestg"]);
gate.tick(&mut listed);
assert!(gate.open.lock().unwrap().is_empty(), "removed: their connection is closed");
assert_eq!(listed, Some(vec![]), "and the list is written without them");
let mut status = 0;
// SAFETY: waits for the child forked above.
unsafe { libc::waitpid(pid, &mut status, 0) };
assert_eq!(libc::WEXITSTATUS(status), 0, "the client saw the connection end");
assert_eq!(gate.grant().unwrap(), 0, "and the list no longer names them");
let _ = Command::new("userdel").arg("kiritest").status();
let _ = Command::new("groupdel").arg("kiritestg").status();
std::fs::remove_dir_all(&dir).unwrap();
}
+6 -3
View File
@@ -389,7 +389,7 @@ fn images(req: &Request, engine: &Engine) -> Result<Value, Error> {
"Id": i.config_digest,
"ParentId": "",
"RepoTags": [i.name],
"RepoDigests": [i.repo_digest()],
"RepoDigests": i.repo_digest().into_iter().collect::<Vec<_>>(),
"Created": time::parse_unix(&i.created),
"Size": i.size,
"SharedSize": -1,
@@ -409,7 +409,7 @@ fn image_inspect(engine: &Engine, name: &str) -> Result<Value, Error> {
Ok(json!({
"Id": i.config_digest,
"RepoTags": [i.name],
"RepoDigests": [i.repo_digest()],
"RepoDigests": i.repo_digest().into_iter().collect::<Vec<_>>(),
"Created": i.created,
"Size": i.size,
"Architecture": i.platform.rsplit('/').next().unwrap_or(go_arch()),
@@ -455,7 +455,7 @@ fn image_tag(req: &Request, engine: &Engine, source: &str) -> Result<(), Error>
let tag = req.query("tag").filter(|t| !t.is_empty()).unwrap_or("latest");
let full = format!("{repo}:{tag}");
let name = Reference::parse(&full).map(|r| r.short()).map_err(|e| Error::BadRequest(format!("invalid reference format: {e}")))?;
engine.store.put_image(kiri_image::Image { name: name.clone(), ..i.clone() })?;
engine.store.put_image(i.tagged(name.clone()))?;
engine.emit_image("tag", &i.config_digest, &name);
Ok(())
}
@@ -665,6 +665,9 @@ fn push(req: &Request, engine: &Engine, name: &str, w: &mut UnixStream) -> io::R
});
match result {
Ok((digest, size)) => {
if let Err(e) = engine.store.set_pushed(&image.name, &image.config_digest, &digest) {
crate::diag::warn!("pushed digest not recorded", image = image.name, error = e);
}
line(json!({"status": format!("{}: digest: {digest} size: {size}", target.reference)}));
line(json!({"progressDetail": {}, "aux": {"Tag": target.reference, "Digest": digest, "Size": size}}));
}
+36
View File
@@ -240,6 +240,31 @@ fn write_config(engine: &Engine, id: &str) {
if let Err(e) = copy_in(engine, id, "/etc", &mut io::Cursor::new(archive)) {
crate::diag::warn!("builder config not written", error = format!("{e:?}"));
}
if kiri_vmm::rosetta_installed() {
hide_amd64_qemu(engine, id);
}
}
/// BuildKit's x86-64 emulator, which it runs amd64 build steps under when it
/// thinks the machine can't run them itself.
const AMD64_QEMU: &str = "buildkit-qemu-x86_64";
/// With Rosetta shared into the VM, amd64 build steps run through Rosetta,
/// as `docker run --platform linux/amd64` does. BuildKit decides whether
/// amd64 runs natively by starting a tiny amd64 program in an empty chroot,
/// where Rosetta can't start (it needs `/proc/self/exe`), so it would run
/// every amd64 step under its own QEMU instead: much slower, and some
/// programs crash there (Bun aborts with "MemoryExhaustion"). With no
/// executable emulator BuildKit runs the step directly, and the kernel
/// hands it to Rosetta, which works inside the step's container. Other
/// platforms (arm/v7, riscv64…) keep their emulators. An empty file, not
/// executable, takes the emulator's place, so builders made before this
/// change get it too.
fn hide_amd64_qemu(engine: &Engine, id: &str) {
let archive = tar(&[(AMD64_QEMU, Some(&[]))]);
if let Err(e) = copy_in(engine, id, "/usr/bin", &mut io::Cursor::new(archive)) {
crate::diag::warn!("builder amd64 emulator not hidden", error = format!("{e:?}"));
}
}
/// `POST /containers/create` for the builder's name, from buildx when it
@@ -1005,6 +1030,17 @@ fn du_rows(text: &str) -> Value {
mod tests {
use super::*;
/// BuildKit looks the emulator up by name and skips it when it isn't
/// executable, so the file taking its place must be a plain 0644 file.
#[test]
fn hidden_amd64_emulator_is_not_executable() {
let archive = tar(&[(AMD64_QEMU, Some(&[]))]);
assert_eq!(&archive[..AMD64_QEMU.len() + 1], format!("{AMD64_QEMU}\0").as_bytes());
assert_eq!(&archive[100..108], b"0000644\0");
assert_eq!(archive[156], b'0');
assert_eq!(&archive[124..136], b"00000000000\0");
}
fn req(query: &[(&str, &str)]) -> Request {
Request::internal("POST", "/build", query, Vec::new())
}
+2 -2
View File
@@ -3024,7 +3024,7 @@ mod image_lookup_tests {
] {
assert!(found(&pulled, &name), "{name}");
}
assert_eq!(pulled[0].repo_digest(), format!("kindest/node@{INDEX}"));
assert_eq!(pulled[0].repo_digest(), Some(format!("kindest/node@{INDEX}")));
}
#[test]
@@ -3041,7 +3041,7 @@ mod image_lookup_tests {
#[test]
fn an_image_without_an_index_shows_its_manifest_digest() {
let pulled = image("alpine:latest", None);
assert_eq!(pulled.repo_digest(), format!("alpine@{ARM64}"));
assert_eq!(pulled.repo_digest(), Some(format!("alpine@{ARM64}")));
assert!(found(&[pulled], &format!("alpine:3@{ARM64}")));
}
}
+31 -8
View File
@@ -92,15 +92,26 @@ pub fn run(_args: &[String]) -> io::Result<()> {
std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?;
// On a Linux host the daemon runs as root; `KIRI_SOCKET_GROUP=kiri`
// lets that group's users in, as the docker group does for dockerd.
if let Some(group) = std::env::var_os("KIRI_SOCKET_GROUP") {
socket_group(&socket, &group)?;
// And each member by name, so one just added needn't sign in again.
#[cfg(target_os = "linux")]
match access::grant(&socket, &group.to_string_lossy()) {
Ok(n) => diag::info!("socket access list written", members = n),
Err(e) => diag::warn!("socket access list not written: new members sign in again first", error = e),
}
let access_group = std::env::var_os("KIRI_SOCKET_GROUP");
if let Some(group) = &access_group {
socket_group(&socket, group)?;
}
// Each member by name too, so one just added needn't sign in again; and
// connections are checked against the group when made and while open, so
// a member removed is let go at once, whatever the list still says.
#[cfg(target_os = "linux")]
let gate = match &access_group {
Some(group) => {
let gate = access::Gate::new(&socket, group)?;
match gate.grant() {
Ok(n) => diag::info!("socket access list written", members = n),
Err(e) => diag::warn!("socket access list not written: new members sign in again first", error = e),
}
gate.clone().watch()?;
Some(gate)
}
None => None,
};
// SIGINT/SIGTERM shut down cleanly: power the guest off, remove the socket.
// Blocked here so every thread inherits it; one thread waits for them.
@@ -172,7 +183,19 @@ pub fn run(_args: &[String]) -> io::Result<()> {
for conn in listener.incoming() {
let Ok(conn) = conn else { continue };
let engine = engine.clone();
#[cfg(target_os = "linux")]
let gate = gate.clone();
let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || {
// Checked here, not in the accept loop: a slow user lookup holds up
// this connection only.
#[cfg(target_os = "linux")]
let _seat = match &gate {
Some(gate) => match gate.admit(&conn) {
Some(seat) => Some(seat),
None => return,
},
None => None,
};
let _ = api::serve(conn, engine);
});
if let Err(e) = spawned {
+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());
}
}
+32 -10
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.
@@ -74,10 +74,10 @@ pub fn run(autostart: bool, view: Option<String>) -> io::Result<()> {
settings.set_hardware_acceleration_policy(webkit2gtk::HardwareAccelerationPolicy::Never);
settings.set_enable_write_console_messages_to_stdout(cfg!(debug_assertions));
}
// 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);
// Before set_appearance, which gives it its background.
WEBVIEW.with(|v| *v.borrow_mut() = Some(webview));
set_appearance(prefs()["theme"].as_str().unwrap_or("system"));
let quit_tx = tx;
@@ -87,7 +87,6 @@ pub fn run(autostart: bool, view: Option<String>) -> io::Result<()> {
glib::Propagation::Proceed
});
window.show_all();
WEBVIEW.with(|v| *v.borrow_mut() = Some(webview));
WINDOW.with(|v| *v.borrow_mut() = Some(window));
gtk::main();
let _ = engine.join();
@@ -142,16 +141,32 @@ pub(super) fn zoom() {
pub(super) fn set_appearance(theme: &str) {
let theme = theme.to_owned();
glib::MainContext::default().invoke(move || {
let dark = match theme.as_str() {
"dark" => true,
"light" => false,
_ => desktop_dark(),
};
if let Some(settings) = gtk::Settings::default() {
match theme.as_str() {
"dark" => settings.set_gtk_application_prefer_dark_theme(true),
"light" => settings.set_gtk_application_prefer_dark_theme(false),
_ => settings.set_gtk_application_prefer_dark_theme(desktop_dark()),
}
settings.set_gtk_application_prefer_dark_theme(dark);
}
WEBVIEW.with(|v| {
if let Some(webview) = v.borrow().as_ref() {
webview.set_background_color(&page_background(dark));
}
});
});
}
/// The view's background under the page: index.html's `--bg` for the scheme,
/// so there is no white flash before the page paints. Opaque on purpose: with
/// a transparent view and no GPU compositing (see `run`), WebKitGTK 2.54 keeps
/// only the regions repainted in each frame, and the rest of the window
/// flickers through to whatever is behind it.
fn page_background(dark: bool) -> gtk::gdk::RGBA {
let (r, g, b) = if dark { (0x0F, 0x14, 0x19) } else { (0xF5, 0xF7, 0xFA) };
gtk::gdk::RGBA::new(f64::from(r) / 255.0, f64::from(g) / 255.0, f64::from(b) / 255.0, 1.0)
}
/// GNOME's (and most desktops') dark preference, through the settings portal's key.
fn desktop_dark() -> bool {
std::process::Command::new("gsettings")
@@ -171,6 +186,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 { ":" };
+717 -9
View File
@@ -376,7 +376,8 @@ td.r, th.r { text-align: right; }
.name { display: flex; align-items: center; gap: 10px; }
.tile { width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; flex: none; background: var(--raised); color: var(--faint); box-shadow: inset 0 0 0 1px var(--line); }
.tile svg { width: 18px; height: 18px; fill: currentColor; }
/* A tag never stretches its column: a long one ends in an ellipsis, whole in its title. */
/* A tag never stretches its column: a long one ends in an ellipsis, whole in its title.
Cap the pill at 160px; Images' Tag cell (td.clip + fixed shares) can clip further when narrow. */
.tag.k8s { margin-left: 6px; color: var(--blue); border-color: color-mix(in srgb, var(--blue) 40%, transparent); background: color-mix(in srgb, var(--blue) 10%, transparent); }
.k8s-mark { margin-left: 6px; display: inline-flex; vertical-align: -3px; }
.k8s-mark svg { width: 16px; height: 16px; fill: #326CE5; }
@@ -1919,7 +1920,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">
@@ -1990,6 +2092,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);
@@ -2206,6 +2310,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. */
@@ -3315,6 +3420,9 @@ function show(view) {
if (view === "share") { send("shares"); send("shareusage"); shPoll(); }
if (view === "settings") { if (!fontLists.families.length) send("fonts"); send("about"); send("logins"); send("resources"); send("proxy"); if (!ui.imp.sources) send("importsources"); if (prefs.tab === "diagnostics") diagOpen(); }
render();
// From the top, as a container's or pod's page opens: leaving a page scrolled
// down (a long Terminal or Logs tab) otherwise opened the next view below its rows.
$("content").scrollTop = 0;
}
const empty = {
@@ -3374,8 +3482,10 @@ function fitColumns() {
const fixed = (th) => !!th.dataset.fixed;
let w = widths()[tbl.dataset.view];
if (w && cells.length !== w.cols.length) w = null;
// A table with fixed columns is always laid out here; one without, only once it's been resized.
if (!w && !cells.some(fixed)) return;
// Laid out when columns declare a share or a fixed width, or after the
// person has resized once (saved widths). Share-only tables (Images,
// Containers) must not wait for a drag — otherwise a long tag pushes Actions off.
if (!w && !cells.some((th) => fixed(th) || th.dataset.share)) return;
tbl.classList.add("sized");
const box = getComputedStyle(tbl.parentElement);
// Actions take what their buttons need, not a saved width: a saved one can be stale or inflated.
@@ -3930,8 +4040,8 @@ function renderImages() {
const [repo, tag] = untagged(i) ? ["<none>", ""] : split(name);
const picked = ui.picked && (i.RepoTags || []).some((t) => t === ui.picked || t === `${ui.picked}:latest`);
rows.push(`<tr class="row${picked ? " picked" : ""}${chosen("images", i)}" data-rowopen="img" data-key="${esc(name)}"${pickAt("images", i)}>
${pickCell("images", i)}<td><div class="name" data-img="${esc(name)}">${tile(i.icon)}<div><span class="link">${esc(repo)}</span></div></div></td>
<td>${untagged(i) ? '<span class="tag none">untagged</span>' : tagPill(tag)}</td>
${pickCell("images", i)}<td class="clip"><div class="name" data-img="${esc(name)}" title="${esc(repo)}">${tile(i.icon)}<div><span class="link">${esc(repo)}</span></div></div></td>
<td class="clip">${untagged(i) ? '<span class="tag none">untagged</span>' : tagPill(tag)}</td>
${usedCell(i, lit)}
<td class="mono muted col-id"><span class="sel">${esc(short(i.Id))}</span>${copyBtn(i.Id, "image ID")}</td>
<td class="r num">${size(i.Size)}</td>
@@ -3943,7 +4053,9 @@ function renderImages() {
${ibtn("trash", "Remove", `data-rmi="${esc(name)}"`, "danger")}
</div></td></tr>`);
}
table([["Repository", "", "repo"], ["Tag", "", "tag"], ["Used by", "", "used"], ["ID", "col-id", "id"], ["Size", "r", "size"], ["Created", "col-created", "created"], ["Pulled", "", "pulled"]], rows, "images");
// Shares like Containers: the table is always fixed-layout so a long repo or
// tag ellipsises instead of pushing Actions off the window.
table([["Repository", "", "repo", { share: 3 }], ["Tag", "", "tag", { share: 1.2 }], ["Used by", "", "used", { share: 1.4 }], ["ID", "col-id", "id", { share: 1 }], ["Size", "r", "size", { share: 0.8 }], ["Created", "col-created", "created", { share: 1 }], ["Pulled", "", "pulled", { share: 1 }]], rows, "images");
}
// An image's page: Images › name, with its layers and settings read from Kiri's store.
@@ -4384,6 +4496,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>`,
@@ -5765,7 +5878,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;
@@ -5786,6 +5902,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;
}
@@ -5794,7 +5912,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;
@@ -5862,7 +5980,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;
}
@@ -5975,6 +6093,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]");
@@ -8508,6 +8627,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");
+36 -6
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));
@@ -228,8 +228,10 @@ pub(super) fn set_appearance(theme: &str) {
}
}
/// Shows the window (after it was closed or hidden) and brings Kiri forward.
/// Shows the window (after it was closed or hidden) and brings Kiri forward,
/// putting the Dock icon back that closing the window took away.
fn show_window(mtm: MainThreadMarker) {
NSApplication::sharedApplication(mtm).setActivationPolicy(NSApplicationActivationPolicy::Regular);
WINDOW.with(|w| {
if let Some(window) = w.borrow().as_ref() {
window.makeKeyAndOrderFront(None);
@@ -259,7 +261,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 +320,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 +346,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};
@@ -423,9 +444,11 @@ define_class!(
unsafe impl NSObjectProtocol for AppDelegate {}
unsafe impl NSApplicationDelegate for AppDelegate {
/// Closing the window leaves Kiri in the menu bar, as OrbStack does.
/// Closing the window leaves Kiri in the menu bar only, as the tray
/// does on Windows: the Dock icon goes until the window opens again.
#[unsafe(method(applicationShouldTerminateAfterLastWindowClosed:))]
fn should_terminate_after_last_window(&self, _app: &NSApplication) -> bool {
fn should_terminate_after_last_window(&self, app: &NSApplication) -> bool {
app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
false
}
@@ -494,6 +517,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
+2 -1
View File
@@ -41,7 +41,8 @@ Apple silicon and Intel Macs (macOS 14+), Windows 10 and 11 (x86-64 and Arm, thr
`save`, `load`, `history`, `search`, `image prune`, `system df`;
**amd64 images run through Rosetta**, `--platform` honoured
- **Builds**: `docker build` / `buildx build` through BuildKit running in a
Kiri container (buildx's docker-container driver), stopped when idle
Kiri container (buildx's docker-container driver), stopped when idle;
on Apple silicon, amd64 build steps run through Rosetta too
- **Compose**: `up`, `down`, `ps`, `logs`, `exec`, multiple networks, events
- **Mac integration**: container files at `~/Kiri` in Finder (read-only
NFS, always current), SSH agent forwarding at
+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.
+2 -2
View File
@@ -14,7 +14,7 @@ case "$KARCH-$(uname -m)" in
arm64-*) cross=aarch64-linux-gnu- pkgs=gcc-aarch64-linux-gnu ;;
*) echo "KARCH must be arm64 or x86_64" >&2; exit 1 ;;
esac
apt-get update -qq && apt-get install -y -qq build-essential flex bison bc libssl-dev libelf-dev curl xz-utils python3 $pkgs >/dev/null
apt-get update -qq && apt-get install -y -qq build-essential flex bison bc libssl-dev libelf-dev dwarves curl xz-utils python3 $pkgs >/dev/null
cd /build
[ -f "linux-$KVER/Makefile" ] && [ -f "linux-$KVER/scripts/Kbuild.include" ] || { rm -rf "linux-$KVER"; curl -fsSL "https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-$KVER.tar.xz" | tar xJ; }
cd "linux-$KVER"
@@ -34,7 +34,7 @@ missing=0
for line in $(grep -E '^CONFIG_[A-Z0-9_]+=y' "$config"); do
grep -qx "$line" .config || { echo "MISSING: $line"; missing=1; }
done
[ "$missing" = 0 ] || echo "some options were not applied (dependency not met)"
[ "$missing" = 0 ] || { echo "some options were not applied (dependency not met)" >&2; exit 1; }
if [ "$KARCH" = x86_64 ]; then
make -s -j"$(nproc)" ARCH=x86_64 CROSS_COMPILE="$cross" bzImage
cp arch/x86/boot/bzImage .config /out/
+305 -1
View File
@@ -32,8 +32,16 @@ CONFIG_HIGH_RES_TIMERS=y
CONFIG_NO_HZ_IDLE=y
CONFIG_PREEMPT_VOLUNTARY=y
CONFIG_PSI=y
# /proc/<pid>/io: per-process read and write counts. Programs that read it at
# start (Typesense's metrics, monitoring agents) crash or fail without it.
CONFIG_TASKSTATS=y
CONFIG_TASK_XACCT=y
CONFIG_TASK_IO_ACCOUNTING=y
# Only root may load BPF programs (kernel.unprivileged_bpf_disabled=2), as on
# every major distribution. Cilium and other eBPF tools run as root.
CONFIG_BPF_UNPRIV_DEFAULT_OFF=y
CONFIG_BPF_SYSCALL=y
# CONFIG_BPF_JIT is not set
CONFIG_BPF_JIT=y
CONFIG_KEYS=y
CONFIG_SECCOMP=y
CONFIG_SECCOMP_FILTER=y
@@ -218,3 +226,299 @@ 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
# --- eBPF tools: Cilium, bpftrace, Tetragon -----------------------------------
# With BPF_JIT above. Perf events carry the datapath's drop and trace events
# (bpf_perf_event_output); BPF_EVENTS follows from perf events plus kprobe
# events. BTF (/sys/kernel/btf/vmlinux) needs debug info and pahole at build
# time; the debug info itself is not in the Image. SHA1 is on Cilium's list;
# the IPsec options above select SHA256 only.
CONFIG_PERF_EVENTS=y
CONFIG_FTRACE=y
CONFIG_KPROBES=y
CONFIG_KPROBE_EVENTS=y
CONFIG_DEBUG_KERNEL=y
CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y
CONFIG_DEBUG_INFO_BTF=y
CONFIG_CRYPTO_SHA1=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()
+39 -8
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")
@@ -228,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'
@@ -414,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
@@ -527,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}}'"
@@ -572,9 +593,14 @@ t login-wrong "incorrect username or password" bash -c "echo nope | $R login loc
t login "Login Succeeded" bash -c "echo kiripass | $R login localhost:5055 -u kiriuser --password-stdin 2>&1"
t push "digest: sha256:" bash -c "$R tag alpine localhost:5055/team/alp:1 && $R push localhost:5055/team/alp:1 2>&1"
t push-again "already exists" bash -c "$R push localhost:5055/team/alp:1 2>&1"
# Deploy tools pin to the RepoDigest after a push: it must be the manifest the
# registry has, not the image ID or the index alpine was pulled from.
t push-repo-digest "same" bash -c "d=\$($R push localhost:5055/team/alp:1 2>&1 | sed -n 's/.*digest: \(sha256:[0-9a-f]*\).*/\1/p'); [ -n \"\$d\" ] && [ \"\$($R image inspect localhost:5055/team/alp:1 --format '{{index .RepoDigests 0}}')\" = localhost:5055/team/alp@\$d ] && echo same"
t pull-auth "3." bash -c "$R rmi localhost:5055/team/alp:1 >/dev/null && $R pull -q localhost:5055/team/alp:1 >/dev/null && $R run --rm localhost:5055/team/alp:1 cat /etc/alpine-release"
t pull-no-auth "pull access denied" bash -c "$R logout localhost:5055 >/dev/null; $R rmi localhost:5055/team/alp:1 >/dev/null; $R pull localhost:5055/team/alp:1 2>&1"
t push-no-auth "authentication required" bash -c "$R tag alpine localhost:5055/team/alp:2 && $R push localhost:5055/team/alp:2 2>&1"
# Not pushed, so no RepoDigest: not alpine's from Docker Hub, nor one made up.
t push-failed-no-digest "[]" $R image inspect localhost:5055/team/alp:2 --format '{{json .RepoDigests}}'
$D rmi localhost:5055/team/alp:2 >/dev/null 2>&1; $D rm -f reg >/dev/null; rm -rf "$REG"
section "limits, stats, top, pause, update"
@@ -683,7 +709,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"
@@ -736,14 +765,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"
@@ -764,7 +795,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"
+39
View File
@@ -0,0 +1,39 @@
// Images: a long repository or tag must not push Actions' buttons past the
// column — the list always uses fixed column shares, like Containers.
const R = [];
const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } };
const nowS = Date.now() / 1000;
kiri.on({ type: "lists", containers: [], images: [
{ Id: "sha256:" + "a".repeat(64), RepoTags: ["harbor.example.com:9090/szda/very-long-path/rustfs:arm-1.0.0-beta.8-extra-long"], Size: 1e8, Created: nowS - 60, Pulled: nowS - 30 },
{ Id: "sha256:" + "b".repeat(64), RepoTags: ["nginx:alpine"], Size: 1e7, Created: nowS - 120, Pulled: nowS - 90 },
], volumes: [], networks: [] });
document.body.style.width = "1100px";
show("images");
t("Images is laid out with fixed shares without a prior resize", () => {
const tbl = document.querySelector("#content table[data-view=images]");
if (!tbl?.classList.contains("sized")) throw new Error("not sized");
if (![...tbl.tHead.rows[0].cells].some((th) => th.dataset.share)) throw new Error("no shares on headings");
});
t("a long tag and repository leave every Actions button inside its column", () => {
const tbl = document.querySelector("#content table.sized");
for (const r of tbl.tBodies[0].rows) {
const td = r.cells[r.cells.length - 1];
if (!td.classList.contains("actions")) throw new Error("last cell is not actions");
const colR = td.getBoundingClientRect().right;
for (const b of td.querySelectorAll("button")) {
if (b.getBoundingClientRect().right > colR + 0.5) throw new Error(`button past column: ${b.getAttribute("aria-label")}`);
}
}
});
t("the long tag is clipped with its full value in the title", () => {
const pill = document.querySelector('#content tr[data-key*="rustfs"] .tag');
if (!pill) throw new Error("no tag pill");
if (!/arm-1\.0\.0-beta\.8/.test(pill.title)) throw new Error("title missing full tag: " + pill.title);
if (pill.scrollWidth <= pill.clientWidth + 1 && pill.textContent.length > 20) {
// May or may not overflow depending on column share; the cell must still clip.
}
const cell = pill.closest("td");
if (!cell.classList.contains("clip")) throw new Error("tag cell not clip");
});
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) {